Documentation
¶
Overview ¶
Package core implements Switchboard's domain: API keys, agent tokens and OAuth, channels, the request broker (queue, claims, leases, streaming), conversation reconstruction, sessions and statistics. Both the server and the CLI use it directly against the same SQLite database.
Index ¶
- Constants
- Variables
- func AvgLatencyMs(c sqlcgen.Channel) int64
- func ChannelModels(c sqlcgen.Channel) []string
- func ChannelServesModel(c sqlcgen.Channel, model string) bool
- func ClientAllowsRedirect(c sqlcgen.OauthClient, uri string) bool
- func ClientRedirectURIs(c sqlcgen.OauthClient) []string
- func IsActive(status string) bool
- func IsTerminal(status string) bool
- func JoinList(items []string) string
- func KeyAllowsModel(k sqlcgen.ApiKey, model string) bool
- func MatchModel(patterns []string, model string) bool
- func MsPtrTime(p *int64) *time.Time
- func MsTime(ms int64) time.Time
- func ParseAnswer(r sqlcgen.Request) (openai.Answer, bool)
- func ParseRequestBody(r sqlcgen.Request) (*openai.ChatRequest, error)
- func Percentile(samples []int64, p float64) int64
- func SplitList(s string) []string
- func TitleFrom(text string) string
- func ValidateSetting(key, value string) error
- func VerifyOAuthClientSecret(c sqlcgen.OauthClient, presented string) bool
- type APIKeyInput
- type Bucket
- type ChannelInput
- type ConversationFilter
- type EventFilter
- type Limiter
- type OAuthClientInput
- type OAuthError
- type Outcome
- type Overview
- type RequestFilter
- type RequestStateError
- type Service
- func (s *Service) ActiveRequests(ctx context.Context) ([]sqlcgen.Request, error)
- func (s *Service) AllowRequest(k sqlcgen.ApiKey) (ok bool, remaining int64, retryAfter time.Duration, limit int64)
- func (s *Service) AnswerRequest(ctx context.Context, requestID string, a openai.Answer, force bool) (sqlcgen.Request, error)
- func (s *Service) AuthenticateAPIKey(ctx context.Context, plaintext string) (sqlcgen.ApiKey, error)
- func (s *Service) AuthenticateAgentToken(ctx context.Context, plaintext string) (sqlcgen.AgentToken, error)
- func (s *Service) BaseURL(reqHost string, tls bool) string
- func (s *Service) CancelRequest(ctx context.Context, requestID, reason string) error
- func (s *Service) ChannelInFlight(ctx context.Context, id string) (int64, error)
- func (s *Service) ClaimRequest(ctx context.Context, channelID, tokenID string, wait time.Duration) (*sqlcgen.Request, error)
- func (s *Service) Close()
- func (s *Service) CloseChannel(ctx context.Context, id, tokenID, reason string) error
- func (s *Service) CompleteRequest(ctx context.Context, channelID, tokenID, requestID string, a openai.Answer) (sqlcgen.Request, error)
- func (s *Service) ConsumeLoginToken(ctx context.Context, token string) bool
- func (s *Service) ConversationRequests(ctx context.Context, id string) ([]sqlcgen.Request, error)
- func (s *Service) CreateAPIKey(ctx context.Context, in APIKeyInput) (sqlcgen.ApiKey, string, error)
- func (s *Service) CreateAgentToken(ctx context.Context, name string) (sqlcgen.AgentToken, string, error)
- func (s *Service) CreateLoginToken(ctx context.Context, ttl time.Duration) (string, error)
- func (s *Service) CreateSession(ctx context.Context, userAgent string) (string, error)
- func (s *Service) DeleteAPIKey(ctx context.Context, id string) error
- func (s *Service) DeleteAgentToken(ctx context.Context, id string) error
- func (s *Service) DeleteChannel(ctx context.Context, id string) error
- func (s *Service) DeleteConversation(ctx context.Context, id string) error
- func (s *Service) DeleteOAuthClient(ctx context.Context, id string) error
- func (s *Service) DeleteSession(ctx context.Context, token string) error
- func (s *Service) DistinctModels(ctx context.Context) ([]string, error)
- func (s *Service) EnsurePassword(ctx context.Context) (string, error)
- func (s *Service) EventKinds(ctx context.Context) ([]string, error)
- func (s *Service) ExchangeAuthCode(ctx context.Context, code, clientID, redirectURI, verifier string) (TokenPair, error)
- func (s *Service) ExtendLease(ctx context.Context, channelID, tokenID, requestID string) error
- func (s *Service) FailRequest(ctx context.Context, channelID, tokenID, requestID, reason string, ...) error
- func (s *Service) GetAPIKey(ctx context.Context, id string) (sqlcgen.ApiKey, error)
- func (s *Service) GetAgentToken(ctx context.Context, id string) (sqlcgen.AgentToken, error)
- func (s *Service) GetChannel(ctx context.Context, id string) (sqlcgen.Channel, error)
- func (s *Service) GetConversation(ctx context.Context, id string) (sqlcgen.Conversation, error)
- func (s *Service) GetOAuthClient(ctx context.Context, id string) (sqlcgen.OauthClient, error)
- func (s *Service) GetRequest(ctx context.Context, id string) (sqlcgen.Request, error)
- func (s *Service) HasPassword() bool
- func (s *Service) Heartbeat(ctx context.Context, id, tokenID string) (sqlcgen.Channel, error)
- func (s *Service) IssueAuthCode(ctx context.Context, ...) (string, error)
- func (s *Service) ListAPIKeys(ctx context.Context) ([]sqlcgen.ApiKey, error)
- func (s *Service) ListAgentTokens(ctx context.Context) ([]sqlcgen.AgentToken, error)
- func (s *Service) ListChannels(ctx context.Context) ([]sqlcgen.Channel, error)
- func (s *Service) ListConversations(ctx context.Context, f ConversationFilter) ([]sqlcgen.Conversation, int64, error)
- func (s *Service) ListEvents(ctx context.Context, f EventFilter) ([]sqlcgen.Event, int64, error)
- func (s *Service) ListOAuthClients(ctx context.Context) ([]sqlcgen.OauthClient, error)
- func (s *Service) ListOnlineChannels(ctx context.Context) ([]sqlcgen.Channel, error)
- func (s *Service) ListOpenChannels(ctx context.Context) ([]sqlcgen.Channel, error)
- func (s *Service) ListRequests(ctx context.Context, f RequestFilter) ([]sqlcgen.Request, int64, error)
- func (s *Service) LiveCount() int
- func (s *Service) LocalURL() string
- func (s *Service) LocalURLHost() string
- func (s *Service) LoginAllowed(clientIP string) (bool, time.Duration)
- func (s *Service) LoginLinkURL(token string) string
- func (s *Service) OpenChannel(ctx context.Context, tokenID string, in ChannelInput) (sqlcgen.Channel, bool, error)
- func (s *Service) Overview(ctx context.Context, window time.Duration) (Overview, error)
- func (s *Service) Prune(ctx context.Context)
- func (s *Service) QuickCounts(ctx context.Context) (queued, inFlight, online int64, err error)
- func (s *Service) RawSetting(key string) (string, bool)
- func (s *Service) RecentEvents(ctx context.Context, n int64) ([]sqlcgen.Event, error)
- func (s *Service) RecentRequests(ctx context.Context, n int64) ([]sqlcgen.Request, error)
- func (s *Service) RefreshOAuthToken(ctx context.Context, refreshToken, clientID string) (TokenPair, error)
- func (s *Service) RegisterOAuthClient(ctx context.Context, in OAuthClientInput) (sqlcgen.OauthClient, string, error)
- func (s *Service) ReleaseRequest(ctx context.Context, channelID, tokenID, requestID, reason string) error
- func (s *Service) RequestEvents(ctx context.Context, id string) ([]sqlcgen.Event, error)
- func (s *Service) RequeueRequest(ctx context.Context, requestID, reason string) error
- func (s *Service) RevokeAPIKey(ctx context.Context, id string) error
- func (s *Service) RevokeAgentToken(ctx context.Context, id string) error
- func (s *Service) RevokeAllSessions(ctx context.Context) (int64, error)
- func (s *Service) SetChannelDraining(ctx context.Context, id string, draining bool) error
- func (s *Service) SetPassword(ctx context.Context, password string) error
- func (s *Service) SetSetting(ctx context.Context, key, value string) error
- func (s *Service) SettingValues() map[string]string
- func (s *Service) Settings() Settings
- func (s *Service) Start(ctx context.Context) error
- func (s *Service) StreamDelta(ctx context.Context, channelID, tokenID, requestID string, d openai.Delta) error
- func (s *Service) SubmitRequest(ctx context.Context, in SubmitInput) (sqlcgen.Request, error)
- func (s *Service) SubscribeRequest(id string) (deltas <-chan openai.Delta, replay []openai.Delta, done <-chan struct{}, ...)
- func (s *Service) Throughput(ctx context.Context, window, bucket time.Duration) ([]Bucket, error)
- func (s *Service) UpdateAPIKey(ctx context.Context, id string, in APIKeyInput) error
- func (s *Service) UpdateChannel(ctx context.Context, id string, in ChannelInput) error
- func (s *Service) Uptime() time.Duration
- func (s *Service) ValidateSession(ctx context.Context, token string) bool
- func (s *Service) VerifyPassword(password string) bool
- func (s *Service) WaitRequest(ctx context.Context, requestID string) (Outcome, sqlcgen.Request, error)
- type SettingDef
- type Settings
- type Store
- type SubmitInput
- type TokenPair
Constants ¶
const ( StatusQueued = "queued" StatusClaimed = "claimed" StatusStreaming = "streaming" StatusCompleted = "completed" StatusFailed = "failed" StatusCancelled = "cancelled" StatusExpired = "expired" )
Request statuses.
const ( ChannelOnline = "online" ChannelOffline = "offline" ChannelDraining = "draining" )
Channel statuses.
const ( KeyInstanceName = "instance_name" KeyPublicURL = "public_url" KeyRequestTimeout = "request_timeout_seconds" KeyLease = "lease_seconds" KeyChannelStale = "channel_stale_seconds" KeyMaxAttempts = "max_attempts" KeyRetentionDays = "retention_days" KeyModels = "models" KeyAcceptAnyModel = "accept_any_model" KeyOAuthAccessTTL = "oauth_access_ttl_seconds" KeyOAuthRefreshTTL = "oauth_refresh_ttl_seconds" KeySessionTTLDays = "session_ttl_days" KeyStreamKeepalive = "stream_keepalive_seconds" KeyPasswordHash = "admin.password_hash" KeyMaxQueueDepth = "max_queue_depth" KeyDefaultRateLimit = "default_rate_limit_rpm" )
Setting keys stored in the settings table.
const ( TokenKindStatic = "static" TokenKindOAuth = "oauth" )
Token kinds.
const ManualChannelName = "manual"
ManualChannelName is the channel used when a human answers from the CLI or dashboard.
Variables ¶
var ( ErrRequestNotFound = errors.New("request not found") ErrQueueFull = errors.New("queue is full") )
Broker errors.
var ( ErrChannelNotFound = errors.New("channel not found") ErrChannelClosed = errors.New("channel is closed") ErrChannelNotOwned = errors.New("channel belongs to a different agent token") )
Channel errors.
var ( ErrKeyRevoked = errors.New("api key revoked") ErrKeyInvalid = errors.New("invalid api key") )
Key errors.
var ( ErrTokenInvalid = errors.New("invalid token") ErrTokenExpired = errors.New("token expired") ErrTokenRevoked = errors.New("token revoked") )
Token errors.
var AllStatuses = []string{StatusQueued, StatusClaimed, StatusStreaming, StatusCompleted, StatusFailed, StatusCancelled, StatusExpired}
AllStatuses lists statuses in display order.
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when a lookup matches nothing.
var SettingDefs = []SettingDef{ {KeyInstanceName, "Instance name", "Shown in the dashboard header and MCP server info.", "string", "Switchboard", false}, {KeyPublicURL, "Public URL", "External base URL when reachable through a tunnel or reverse proxy (used for OAuth issuer and MCP resource identifiers). Leave empty for localhost.", "string", "", false}, {KeyModels, "Advertised models", "Models listed by GET /v1/models when no channel declares any. Comma separated.", "list", "switchboard/auto", false}, {KeyAcceptAnyModel, "Accept any model", "Queue requests for models no channel has declared (they wait until a wildcard channel claims them).", "bool", "true", false}, {KeyRequestTimeout, "Request timeout (s)", "Maximum time a caller waits for an answer before receiving 504.", "int", "600", false}, {KeyLease, "Claim lease (s)", "How long an agent may hold a claimed request without streaming or completing before it is requeued.", "int", "120", false}, {KeyChannelStale, "Channel stale after (s)", "A channel with no MCP activity for this long is marked offline and its in-flight requests requeued.", "int", "90", false}, {KeyMaxAttempts, "Max attempts", "Times a request may be claimed before it fails permanently.", "int", "3", false}, {KeyMaxQueueDepth, "Max queue depth", "Reject new requests with 429 when this many are queued (0 = unlimited).", "int", "0", false}, {KeyDefaultRateLimit, "Default rate limit (rpm)", "Requests per minute for keys without their own limit (0 = unlimited).", "int", "0", false}, {KeyStreamKeepalive, "Stream keepalive (s)", "Interval of SSE comments sent to streaming callers while waiting.", "int", "15", false}, {KeyRetentionDays, "Retention (days)", "Finished requests and events older than this are pruned.", "int", "30", false}, {KeyOAuthAccessTTL, "OAuth access token TTL (s)", "Lifetime of MCP OAuth access tokens.", "int", "86400", false}, {KeyOAuthRefreshTTL, "OAuth refresh token TTL (s)", "Lifetime of MCP OAuth refresh tokens.", "int", "2592000", false}, {KeySessionTTLDays, "Dashboard session TTL (days)", "How long a dashboard login stays valid.", "int", "30", false}, }
SettingDefs lists every user-editable setting in display order.
Functions ¶
func AvgLatencyMs ¶
AvgLatencyMs is the mean end-to-end latency of requests a channel served.
func ChannelModels ¶
ChannelModels returns the model patterns a channel serves.
func ChannelServesModel ¶
ChannelServesModel reports whether a channel accepts a model.
func ClientAllowsRedirect ¶
func ClientAllowsRedirect(c sqlcgen.OauthClient, uri string) bool
ClientAllowsRedirect checks an exact match against registered URIs.
func ClientRedirectURIs ¶
func ClientRedirectURIs(c sqlcgen.OauthClient) []string
ClientRedirectURIs decodes a client's registered redirect URIs.
func KeyAllowsModel ¶
KeyAllowsModel reports whether a key may request the model (empty allowlist means any model). Patterns support '*' globs.
func MatchModel ¶
MatchModel reports whether model matches any pattern ('*' wildcard, case-insensitive, glob via path.Match).
func ParseAnswer ¶
ParseAnswer extracts the assistant's answer from a stored response body.
func ParseRequestBody ¶
func ParseRequestBody(r sqlcgen.Request) (*openai.ChatRequest, error)
ParseRequestBody decodes a stored request body leniently (no validation).
func Percentile ¶
Percentile returns the p-th percentile (0-100) of samples, 0 if empty.
func ValidateSetting ¶
ValidateSetting checks a value against its definition.
func VerifyOAuthClientSecret ¶
func VerifyOAuthClientSecret(c sqlcgen.OauthClient, presented string) bool
VerifyOAuthClientSecret checks a confidential client's secret.
Types ¶
type APIKeyInput ¶
type APIKeyInput struct {
Name string
RateLimitRPM int64
AllowedModels []string
PinnedChannelID string
TimeoutSeconds int64
Priority int64
}
APIKeyInput holds the editable fields of an API key.
type ChannelInput ¶
ChannelInput holds the editable fields of a channel.
type ConversationFilter ¶
ConversationFilter narrows ListConversations.
type EventFilter ¶
type EventFilter struct {
Kind string
Level string
RequestID string
ChannelID string
APIKeyID string
Search string
Limit int64
Offset int64
}
EventFilter narrows ListEvents.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is a per-key token bucket keyed by an arbitrary string (API key id, client IP). Buckets refill continuously at rate/minute.
type OAuthClientInput ¶
type OAuthClientInput struct {
Name string
RedirectURIs []string
GrantTypes []string
TokenEndpointAuthMethod string
Metadata map[string]any
}
OAuthClientInput is the dynamic client registration payload (RFC 7591).
type OAuthError ¶
OAuth errors map onto RFC 6749 error codes via Code.
func (*OAuthError) Error ¶
func (e *OAuthError) Error() string
type Outcome ¶
Outcome is the terminal result of a request as seen by its caller.
func OutcomeFromRequest ¶
OutcomeFromRequest reconstructs an Outcome from a stored terminal request.
type Overview ¶
type Overview struct {
Window time.Duration
Queued int64
InFlight int64
ChannelsOnline int64
ChannelsOpen int64
KeysActive int64
Total int64
Completed int64
Failed int64
Dropped int64
PromptTokens int64
CompletionTokens int64
SuccessRate float64 // percent of finished requests that completed
RPM float64 // requests per minute over the window
P50Ms, P95Ms, P99Ms int64
TTFTP50Ms, TTFTP95Ms int64
QueueP50Ms, QueueP95Ms int64
LatencySamples int
Buckets []Bucket
Models []sqlcgen.ModelUsageSinceRow
Keys []sqlcgen.KeyUsageSinceRow
ChannelUsage []sqlcgen.ChannelUsageSinceRow
}
Overview is the dashboard's headline metrics for a time window.
type RequestFilter ¶
type RequestFilter struct {
Status string
APIKeyID string
ChannelID string
ConversationID string
Model string
Search string
Limit int64
Offset int64
}
RequestFilter narrows ListRequests. Empty fields are ignored.
type RequestStateError ¶
RequestStateError reports an operation that conflicts with a request's current state (e.g. completing a request another channel holds).
func (*RequestStateError) Error ¶
func (e *RequestStateError) Error() string
type Service ¶
type Service struct {
*Store
Bus *events.Bus
Log *slog.Logger
// ListenAddr is the address the HTTP server is bound to (set by the app).
ListenAddr string
StartedAt time.Time
// contains filtered or unexported fields
}
Service is the façade over the domain.
func (*Service) ActiveRequests ¶
ActiveRequests returns everything queued or in flight, oldest first.
func (*Service) AllowRequest ¶
func (s *Service) AllowRequest(k sqlcgen.ApiKey) (ok bool, remaining int64, retryAfter time.Duration, limit int64)
AllowRequest applies the per-key rate limit.
func (*Service) AnswerRequest ¶
func (s *Service) AnswerRequest(ctx context.Context, requestID string, a openai.Answer, force bool) (sqlcgen.Request, error)
AnswerRequest lets a human (CLI/dashboard) answer a request directly via the "manual" channel. force steals a request another channel holds.
func (*Service) AuthenticateAPIKey ¶
AuthenticateAPIKey resolves a plaintext key to its record.
func (*Service) AuthenticateAgentToken ¶
func (s *Service) AuthenticateAgentToken(ctx context.Context, plaintext string) (sqlcgen.AgentToken, error)
AuthenticateAgentToken resolves a bearer token presented to the MCP endpoint and records its use.
func (*Service) BaseURL ¶
BaseURL returns the externally visible base URL: the configured public URL if set, otherwise one derived from the request host (or the listen address).
func (*Service) CancelRequest ¶
CancelRequest aborts a request on behalf of its caller or an operator.
func (*Service) ChannelInFlight ¶
ChannelInFlight counts requests currently held by a channel.
func (*Service) ClaimRequest ¶
func (s *Service) ClaimRequest(ctx context.Context, channelID, tokenID string, wait time.Duration) (*sqlcgen.Request, error)
ClaimRequest hands the next eligible queued request to a channel, waiting up to wait for one to arrive. It returns nil when nothing was claimed.
func (*Service) Close ¶
func (s *Service) Close()
Close stops background work and flushes the event bus.
func (*Service) CloseChannel ¶
CloseChannel takes a channel out of service and returns its in-flight requests to the queue.
func (*Service) CompleteRequest ¶
func (s *Service) CompleteRequest(ctx context.Context, channelID, tokenID, requestID string, a openai.Answer) (sqlcgen.Request, error)
CompleteRequest records the final answer, builds the OpenAI response and wakes the caller.
func (*Service) ConsumeLoginToken ¶
ConsumeLoginToken redeems a magic-link token exactly once.
func (*Service) ConversationRequests ¶
ConversationRequests returns a conversation's requests in turn order.
func (*Service) CreateAPIKey ¶
CreateAPIKey mints a key. The plaintext is returned exactly once.
func (*Service) CreateAgentToken ¶
func (s *Service) CreateAgentToken(ctx context.Context, name string) (sqlcgen.AgentToken, string, error)
CreateAgentToken mints a static MCP bearer token. Plaintext returned once.
func (*Service) CreateLoginToken ¶
CreateLoginToken mints a one-time magic-link token.
func (*Service) CreateSession ¶
CreateSession issues a dashboard session token (stored hashed).
func (*Service) DeleteAPIKey ¶
DeleteAPIKey removes a key record entirely (history keeps the id).
func (*Service) DeleteAgentToken ¶
DeleteAgentToken removes a token record.
func (*Service) DeleteChannel ¶
DeleteChannel removes a closed channel record.
func (*Service) DeleteConversation ¶
DeleteConversation removes the conversation record (requests keep the id).
func (*Service) DeleteOAuthClient ¶
DeleteOAuthClient removes a client registration.
func (*Service) DeleteSession ¶
DeleteSession logs a session out.
func (*Service) DistinctModels ¶
DistinctModels lists every model name seen in requests.
func (*Service) EnsurePassword ¶
EnsurePassword generates and stores a random password when none exists. The plaintext is returned only in that case so it can be shown once.
func (*Service) EventKinds ¶
EventKinds lists the distinct event kinds recorded.
func (*Service) ExchangeAuthCode ¶
func (s *Service) ExchangeAuthCode(ctx context.Context, code, clientID, redirectURI, verifier string) (TokenPair, error)
ExchangeAuthCode implements grant_type=authorization_code with PKCE.
func (*Service) ExtendLease ¶
ExtendLease renews a claimed request's lease (agent heartbeat per request).
func (*Service) FailRequest ¶
func (s *Service) FailRequest(ctx context.Context, channelID, tokenID, requestID, reason string, retryable bool) error
FailRequest reports that the serving channel could not answer. Retryable failures return the request to the queue while attempts remain and nothing has been streamed to the caller yet.
func (*Service) GetAgentToken ¶
GetAgentToken fetches a token by id.
func (*Service) GetChannel ¶
GetChannel fetches a channel.
func (*Service) GetConversation ¶
GetConversation fetches a conversation.
func (*Service) GetOAuthClient ¶
GetOAuthClient fetches a client.
func (*Service) GetRequest ¶
GetRequest fetches one request.
func (*Service) HasPassword ¶
HasPassword reports whether a dashboard password is configured.
func (*Service) IssueAuthCode ¶
func (s *Service) IssueAuthCode(ctx context.Context, clientID, redirectURI, challenge, method, scope, resource string) (string, error)
IssueAuthCode creates a short-lived authorization code after user consent.
func (*Service) ListAPIKeys ¶
ListAPIKeys returns all keys, newest first.
func (*Service) ListAgentTokens ¶
ListAgentTokens returns every token (static and OAuth-issued).
func (*Service) ListChannels ¶
ListChannels returns every channel, open ones first.
func (*Service) ListConversations ¶
func (s *Service) ListConversations(ctx context.Context, f ConversationFilter) ([]sqlcgen.Conversation, int64, error)
ListConversations pages conversations newest-activity first.
func (*Service) ListEvents ¶
ListEvents pages events newest first with the total matching count.
func (*Service) ListOAuthClients ¶
ListOAuthClients returns all registered clients.
func (*Service) ListOnlineChannels ¶
ListOnlineChannels returns channels currently online.
func (*Service) ListOpenChannels ¶
ListOpenChannels returns channels that have not been closed.
func (*Service) ListRequests ¶
func (s *Service) ListRequests(ctx context.Context, f RequestFilter) ([]sqlcgen.Request, int64, error)
ListRequests pages requests newest first with the total matching count.
func (*Service) LocalURLHost ¶
LocalURLHost renders the listen address as a host suitable for a URL (0.0.0.0 and :: become 127.0.0.1 / localhost).
func (*Service) LoginAllowed ¶
LoginAllowed rate-limits login attempts per client address.
func (*Service) LoginLinkURL ¶
LoginLinkURL renders a magic-link URL for a token.
func (*Service) OpenChannel ¶
func (s *Service) OpenChannel(ctx context.Context, tokenID string, in ChannelInput) (sqlcgen.Channel, bool, error)
OpenChannel registers an agent instance. If an open channel with the same name exists it is reused when it is offline or owned by the same token; otherwise a suffixed name is allocated so instances never collide.
func (*Service) QuickCounts ¶
QuickCounts returns the live gauges (for the TUI and header).
func (*Service) RawSetting ¶
RawSetting returns a stored value (including non-user-facing keys).
func (*Service) RecentEvents ¶
RecentEvents returns the newest n events.
func (*Service) RecentRequests ¶
RecentRequests returns the newest n requests.
func (*Service) RefreshOAuthToken ¶
func (s *Service) RefreshOAuthToken(ctx context.Context, refreshToken, clientID string) (TokenPair, error)
RefreshOAuthToken implements grant_type=refresh_token with rotation.
func (*Service) RegisterOAuthClient ¶
func (s *Service) RegisterOAuthClient(ctx context.Context, in OAuthClientInput) (sqlcgen.OauthClient, string, error)
RegisterOAuthClient stores a dynamically registered client.
func (*Service) ReleaseRequest ¶
func (s *Service) ReleaseRequest(ctx context.Context, channelID, tokenID, requestID, reason string) error
ReleaseRequest gives a claimed request back without blame (e.g. the agent is shutting down). Partially streamed requests cannot be released.
func (*Service) RequestEvents ¶
RequestEvents returns a request's timeline oldest first.
func (*Service) RequeueRequest ¶
RequeueRequest is the operator action for a stuck in-flight request.
func (*Service) RevokeAPIKey ¶
RevokeAPIKey disables a key; existing requests are unaffected.
func (*Service) RevokeAgentToken ¶
RevokeAgentToken disables a token; channels opened with it stay but can no longer be driven.
func (*Service) RevokeAllSessions ¶
RevokeAllSessions logs every dashboard session out.
func (*Service) SetChannelDraining ¶
SetChannelDraining stops new claims while in-flight work finishes.
func (*Service) SetPassword ¶
SetPassword stores a new dashboard password.
func (*Service) SetSetting ¶
SetSetting validates, stores and reloads one setting.
func (*Service) SettingValues ¶
SettingValues returns raw values with defaults filled in, for display.
func (*Service) Start ¶
Start recovers state from a previous run and launches background upkeep. Call it only from the long-running server, never from one-shot CLI use.
func (*Service) StreamDelta ¶
func (s *Service) StreamDelta(ctx context.Context, channelID, tokenID, requestID string, d openai.Delta) error
StreamDelta appends partial output from the serving channel. The first delta moves the request to streaming and records time-to-first-token.
func (*Service) SubmitRequest ¶
SubmitRequest records an incoming request, links it to its conversation and places it on the queue.
func (*Service) SubscribeRequest ¶
func (s *Service) SubscribeRequest(id string) (deltas <-chan openai.Delta, replay []openai.Delta, done <-chan struct{}, unsub func())
SubscribeRequest attaches to a request's live delta stream. replay holds deltas emitted before subscription; done closes when the request ends.
func (*Service) Throughput ¶
Throughput returns gap-filled request counts per bucket over the window.
func (*Service) UpdateAPIKey ¶
UpdateAPIKey edits a key's settings.
func (*Service) UpdateChannel ¶
UpdateChannel edits channel configuration from the dashboard.
func (*Service) ValidateSession ¶
ValidateSession reports whether a session token is live.
func (*Service) VerifyPassword ¶
VerifyPassword checks a dashboard password.
func (*Service) WaitRequest ¶
func (s *Service) WaitRequest(ctx context.Context, requestID string) (Outcome, sqlcgen.Request, error)
WaitRequest blocks until the request reaches a terminal state or ctx ends. It listens on the in-memory signal and also polls the database so answers written by another process (the CLI) are picked up.
type SettingDef ¶
type SettingDef struct {
Key string
Label string
Description string
Type string // string | int | bool | list
Default string
Secret bool
}
SettingDef describes one tunable for the dashboard and CLI.
type Settings ¶
type Settings struct {
InstanceName string
PublicURL string
Models []string
AcceptAnyModel bool
RequestTimeout time.Duration
Lease time.Duration
ChannelStale time.Duration
MaxAttempts int64
MaxQueueDepth int64
DefaultRateLimit int64
StreamKeepalive time.Duration
RetentionDays int64
OAuthAccessTTL time.Duration
OAuthRefreshTTL time.Duration
SessionTTL time.Duration
}
Settings is a typed snapshot of the tunables.
type SubmitInput ¶
type SubmitInput struct {
Key sqlcgen.ApiKey
Req *openai.ChatRequest
Endpoint string // "chat.completions" | "completions"
Body []byte
ClientIP string
UserAgent string
}
SubmitInput is an incoming OpenAI-compatible request.