api

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package api hosts VORTEX's management HTTP server. In M1.2 this is just a health endpoint that reports liveness and the active config hash, so a reload can be verified externally (e.g. curl localhost:9090/health). It is built on net/http from the standard library (Non-Negotiable Rule #10).

Index

Constants

View Source
const DefaultAddr = ":9090"

DefaultAddr is the management server's default listen address.

Variables

View Source
var ErrAgentBusy = errors.New("api: agent runtime busy")

ErrAgentBusy signals the agent runtime's concurrency cap is reached; the submit handler maps it to 503. The runtime adapter (in start.go) translates the agents-package error into this one to keep api decoupled from agents.

Functions

This section is empty.

Types

type AICostInfo added in v0.2.0

type AICostInfo struct {
	Provider        string  `json:"provider"`
	TotalUSD        float64 `json:"total_usd"`
	RequestsToday   int     `json:"requests_today"`
	DailyBudget     float64 `json:"daily_budget"`
	RemainingBudget float64 `json:"remaining_budget"`
	Free            bool    `json:"free"`
}

AICostInfo is the AI usage/cost summary returned by GET /api/ai/cost.

type AgentRuntime added in v0.2.0

type AgentRuntime interface {
	Submit(ctx context.Context, userMsg, sessionID string) (<-chan string, error)
	Stats() AgentRuntimeStats
	// Approve resolves a pending tool-action approval for a session (the TUI
	// [Y]/[N]). On approval it executes the stashed action and returns a result
	// transcript; matched is false when no action was pending.
	Approve(sessionID string, approved bool) (transcript string, matched bool)
	// ListSessions returns stored conversation sessions (newest first).
	ListSessions() []SessionSummary
	// SessionHistory returns the persisted messages for a session.
	SessionHistory(sessionID string) []SessionMessage
}

AgentRuntime is the subset of the agent runtime the API needs. It is satisfied by *agents.Runtime; declaring it here keeps the api package decoupled from the agents package.

type AgentRuntimeStats added in v0.2.0

type AgentRuntimeStats struct {
	ActiveAgents  int   `json:"active_agents"`
	TotalMessages int64 `json:"total_messages"`
	QueueDepth    int   `json:"queue_depth"`
}

AgentRuntimeStats mirrors the runtime's stats for the API. The wiring in start.go adapts agents.RuntimeStats into this type.

type DevOpsServer added in v0.3.0

type DevOpsServer struct {
	Name string `json:"name"`
}

DevOpsServer is a connected server summary (GET /api/devops/servers).

type ForgeJob added in v0.2.0

type ForgeJob struct {
	ID              string          `json:"id"`
	Message         string          `json:"message"`
	State           string          `json:"state"`
	Progress        string          `json:"progress"`
	ProgressHistory []string        `json:"progress_history,omitempty"`
	Questions       []ForgeQuestion `json:"questions,omitempty"`
	Result          string          `json:"result,omitempty"`
	DurationMs      int64           `json:"duration_ms,omitempty"`
	Error           string          `json:"error,omitempty"`
}

ForgeJob mirrors a forge.Job for the API (kept here so api stays decoupled from the forge package).

type ForgeQuestion added in v0.2.0

type ForgeQuestion struct {
	Question string   `json:"question"`
	Options  []string `json:"options,omitempty"`
	Key      string   `json:"key"`
}

ForgeQuestion is a structured clarifying question for option-selection UIs.

type ForgeRuntime added in v0.2.0

type ForgeRuntime interface {
	Submit(ctx context.Context, message, sessionID string, chatID int64) string
	Get(id string) (ForgeJob, bool)
	List() []ForgeJob
}

ForgeRuntime is the subset of the forge job manager the API needs. The wiring in start.go adapts *forge.JobManager to this interface.

type HealingCheck added in v0.3.0

type HealingCheck struct {
	Name                string    `json:"name"`
	Healthy             bool      `json:"healthy"`
	LatencyMs           int64     `json:"latency_ms"`
	LastCheck           time.Time `json:"last_check"`
	ConsecutiveFailures int       `json:"consecutive_failures"`
}

HealingCheck is one monitored check's status.

type HealingRecoveryStats added in v0.3.0

type HealingRecoveryStats struct {
	TotalEvents     int64 `json:"total_events"`
	ActionsExecuted int64 `json:"actions_executed"`
}

HealingRecoveryStats summarises recovery activity.

type HealingSLOAlert added in v0.3.0

type HealingSLOAlert struct {
	RouteName  string  `json:"route_name"`
	Target     float64 `json:"target"`
	Current    float64 `json:"current"`
	BurnRate   float64 `json:"burn_rate"`
	AlertLevel string  `json:"alert_level"`
}

HealingSLOAlert is a current SLO breach.

type HealingStatus added in v0.3.0

type HealingStatus struct {
	Healthy       bool                 `json:"healthy"`
	Checks        []HealingCheck       `json:"checks"`
	SLOAlerts     []HealingSLOAlert    `json:"slo_alerts"`
	RecoveryStats HealingRecoveryStats `json:"recovery_stats"`
}

HealingStatus is the GET /api/healing/status response (M14).

type LogBuffer added in v0.2.0

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

LogBuffer is a fixed-capacity ring buffer of recent log entries, safe for concurrent writes (the logger) and reads (the /api/logs handler).

func NewLogBuffer added in v0.2.0

func NewLogBuffer(capacity int) *LogBuffer

NewLogBuffer creates a buffer holding the last cap entries (min 1).

func (*LogBuffer) Last added in v0.2.0

func (b *LogBuffer) Last(n int) []LogEntry

Last returns the most recent n entries (oldest→newest), thread-safe.

func (*LogBuffer) Len added in v0.2.0

func (b *LogBuffer) Len() int

Len returns the number of buffered entries.

func (*LogBuffer) Write added in v0.2.0

func (b *LogBuffer) Write(e LogEntry)

Write appends an entry, evicting the oldest when at capacity.

type LogEntry added in v0.2.0

type LogEntry struct {
	Time   string            `json:"time"`
	Level  string            `json:"level"`
	Msg    string            `json:"msg"`
	Fields map[string]string `json:"fields,omitempty"`
}

LogEntry is one structured log line captured for the TUI/log viewer.

type NamespaceInfo added in v0.2.0

type NamespaceInfo struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	OrgID  string `json:"org_id"`
	Quotas struct {
		MaxRoutes      int   `json:"max_routes"`
		MaxSecrets     int   `json:"max_secrets"`
		MaxConnections int64 `json:"max_connections"`
		BandwidthMbps  int64 `json:"bandwidth_mbps"`
	} `json:"quotas"`
}

NamespaceInfo mirrors a tenant namespace for the API.

type NamespaceStats added in v0.2.0

type NamespaceStats struct {
	ActiveConns   int64 `json:"active_conns"`
	BandwidthUsed int64 `json:"bandwidth_used"`
	RouteCount    int   `json:"route_count"`
}

NamespaceStats is a namespace's live usage for the API.

type OrchestrateResult added in v0.3.0

type OrchestrateResult struct {
	Summary string `json:"summary"`
}

OrchestrateResult is the analyze response.

type PipelineResultInfo added in v0.3.0

type PipelineResultInfo struct {
	Summary   string   `json:"summary"`
	DataPath  string   `json:"data_path"`
	ChartPath string   `json:"chart_path"`
	Rows      int      `json:"rows"`
	Columns   []string `json:"columns"`
}

PipelineResultInfo is the analyze response.

type PluginInfo added in v0.2.0

type PluginInfo struct {
	Name        string   `json:"name"`
	Version     string   `json:"version"`
	Description string   `json:"description,omitempty"`
	HookTypes   []string `json:"hook_types,omitempty"`
}

PluginInfo mirrors a plugin manifest for GET /api/plugins.

type ResearchReport added in v0.3.0

type ResearchReport struct {
	Title    string    `json:"title"`
	FilePath string    `json:"file_path"`
	SavedAt  time.Time `json:"saved_at"`
}

ResearchReport is a saved research report summary (GET /api/research/reports).

type RouteHealth added in v0.2.0

type RouteHealth struct {
	Name     string `json:"name"`
	Protocol string `json:"protocol"`
	Listen   string `json:"listen"`
	Active   int64  `json:"active"`
}

RouteHealth is one route's health summary in the /health response.

type SecretStatus added in v0.2.0

type SecretStatus struct {
	Name string `json:"name"`
	Set  bool   `json:"set"`
}

SecretStatus is one declared secret's set/unset state (never its value).

type Server

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

Server is the management HTTP server.

func New

func New(addr string, holder *config.Holder, version string, log *slog.Logger) *Server

New constructs a management Server. holder supplies the live config so /health always reports the currently active hash, including after a reload.

func (*Server) AICostSnapshot added in v0.2.0

func (s *Server) AICostSnapshot() AICostInfo

AICostSnapshot returns the current AI cost summary (free when unwired).

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the configured listen address.

func (*Server) SetAICostProvider added in v0.2.0

func (s *Server) SetAICostProvider(fn func() AICostInfo)

SetAICostProvider wires the GET /api/ai/cost data source. When nil, the endpoint reports zero/free.

func (*Server) SetAgentRuntime added in v0.2.0

func (s *Server) SetAgentRuntime(rt AgentRuntime)

SetAgentRuntime wires the agent runtime backing the /api/agents endpoints. When nil, those endpoints return 503.

func (*Server) SetAuditLog added in v0.2.0

func (s *Server) SetAuditLog(l *audit.Log)

SetAuditLog wires the audit log used to record reload and key-management events. A nil log disables audit recording.

func (*Server) SetAuth added in v0.2.0

func (s *Server) SetAuth(mw func(http.Handler) http.Handler, keys *auth.APIKeyStore, rbac *auth.RBAC)

SetAuth wires the authentication middleware and the key/role stores backing the /api/keys endpoints. It must be called before New builds the mux — so it is passed through New via the optional AuthDeps rather than set afterward. (Provided as a method for symmetry with the other Set* wirings used in tests that construct the server in stages.)

func (*Server) SetBurstNotifier added in v0.3.0

func (s *Server) SetBurstNotifier(fn func(title, body string))

SetBurstNotifier wires the out-of-band alert (e.g. Telegram via the notification router) sent when burst protection bans an IP.

func (*Server) SetDevOpsProvider added in v0.3.0

func (s *Server) SetDevOpsProvider(servers func() []DevOpsServer, run func(ctx context.Context, server, command string) (string, error))

SetDevOpsProvider wires the DevOps endpoints. servers lists connected hosts; run executes a command on a server (approval-gated server-side). When unset, the endpoints return empty / 503.

func (*Server) SetForgeRuntime added in v0.2.0

func (s *Server) SetForgeRuntime(rt ForgeRuntime)

SetForgeRuntime wires the forge job manager backing the /api/forge endpoints. When nil, those endpoints return 503.

func (*Server) SetHealingProvider added in v0.3.0

func (s *Server) SetHealingProvider(fn func() HealingStatus)

SetHealingProvider wires the GET /api/healing/status data source. When nil, the endpoint returns an empty healthy status.

func (*Server) SetLogBuffer added in v0.2.0

func (s *Server) SetLogBuffer(b *LogBuffer)

SetLogBuffer wires the log ring buffer backing GET /api/logs.

func (*Server) SetMetricsHandler added in v0.2.0

func (s *Server) SetMetricsHandler(h http.Handler)

SetMetricsHandler wires the Prometheus metrics handler served at /metrics.

func (*Server) SetNamespaceHooks added in v0.2.0

func (s *Server) SetNamespaceHooks(
	lister func() []NamespaceInfo,
	creator func(NamespaceInfo) error,
	deleter func(id string) error,
	stats func(id string) (NamespaceStats, bool),
)

SetNamespaceHooks wires the namespace management endpoints.

func (*Server) SetOrchestrateProvider added in v0.3.0

func (s *Server) SetOrchestrateProvider(run func(ctx context.Context, goal string) (string, error))

SetOrchestrateProvider wires POST /api/orchestrate. When unset, the endpoint returns 503.

func (*Server) SetPipelineProvider added in v0.3.0

func (s *Server) SetPipelineProvider(analyze func(ctx context.Context, source, data, request string) (PipelineResultInfo, error))

SetPipelineProvider wires POST /api/pipeline/analyze. When unset, the endpoint returns 503.

func (*Server) SetPluginsProvider added in v0.2.0

func (s *Server) SetPluginsProvider(fn func() []PluginInfo)

SetPluginsProvider wires the GET /api/plugins data source.

func (*Server) SetReadinessFunc added in v0.3.0

func (s *Server) SetReadinessFunc(fn func() error)

SetReadinessFunc registers a callback that reports whether the server's subsystems are ready. When set, /ready returns 503 if it returns a non-nil error, instead of always reporting ready (production audit I3). The error message is surfaced in the response body.

func (*Server) SetReloadFunc

func (s *Server) SetReloadFunc(fn func() error)

SetReloadFunc registers the callback invoked by POST /internal/reload. It should re-read and re-validate the config and return an error if invalid.

func (*Server) SetResearchProvider added in v0.3.0

func (s *Server) SetResearchProvider(list func() []ResearchReport, get func(name string) (string, bool))

SetResearchProvider wires the research report endpoints. list returns saved reports; get returns a report's markdown by filename. When unset, the endpoints return empty/404.

func (*Server) SetRouteStats added in v0.2.0

func (s *Server) SetRouteStats(fn func() []RouteHealth)

SetRouteStats registers a callback supplying live per-route stats for the /health response. start.go wires this to the proxy manager after it starts.

func (*Server) SetSecretsProvider added in v0.2.0

func (s *Server) SetSecretsProvider(fn func() []SecretStatus)

SetSecretsProvider wires the GET /api/secrets/status data source.

func (*Server) SetShutdownFunc

func (s *Server) SetShutdownFunc(fn func())

SetShutdownFunc registers the callback invoked by POST /internal/shutdown to begin a graceful shutdown.

func (*Server) SetStatusProvider added in v0.2.0

func (s *Server) SetStatusProvider(fn func() StatusInfo)

SetStatusProvider wires the GET /api/status data source.

func (*Server) SetStudioHandler added in v0.2.0

func (s *Server) SetStudioHandler(h http.Handler)

SetStudioHandler wires the VORTEX Studio handler tree (mounted under /studio/). Studio is a data-plane console (it can run terminals, git, DB queries), so it requires a real API key even from localhost — no control- plane loopback bypass. When nil, /studio/* returns 404.

The /studio/terminal endpoint is a WebSocket: requireAPIKey checks the key (which a browser sends as a query param or header) before the upgrade.

func (*Server) SetWebhooks added in v0.2.0

func (s *Server) SetWebhooks(specs []WebhookSpec)

SetWebhooks installs the given webhook handlers. They are matched by exact path under the /webhook/ prefix and are NOT protected by API-key auth (each verifies its own platform signature); they ARE per-IP rate limited.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully stops the server, respecting ctx's deadline.

func (*Server) Start

func (s *Server) Start()

Start begins serving in a background goroutine. It returns immediately; serve errors other than graceful shutdown are logged.

func (*Server) StartCleanup added in v0.3.0

func (s *Server) StartCleanup(ctx context.Context)

StartCleanup runs the background sweeps that bound the rate-limiter maps (per-IP agent limiter, per-key limiter, burst-protection windows/bans) so none grows without bound under a churn of distinct IPs/keys (production audit H5). It returns when ctx is cancelled.

func (*Server) StatusSnapshot added in v0.2.0

func (s *Server) StatusSnapshot() StatusInfo

StatusSnapshot returns the current extended status (for non-HTTP callers like the Telegram bot). Empty when no provider is wired.

type SessionMessage added in v0.2.0

type SessionMessage struct {
	Role      string    `json:"role"`
	Content   string    `json:"content"`
	Timestamp time.Time `json:"timestamp"`
}

SessionMessage is one persisted conversation turn.

type SessionSummary added in v0.2.0

type SessionSummary struct {
	SessionID string    `json:"session_id"`
	Summary   string    `json:"summary"`
	UpdatedAt time.Time `json:"updated_at"`
}

SessionSummary describes a stored conversation for /api/agents/history.

type StatusInfo added in v0.2.0

type StatusInfo struct {
	NodeID          string   `json:"node_id"`
	TrustDomain     string   `json:"trust_domain"`
	TLSProvider     string   `json:"tls_provider"`
	SecretBackend   string   `json:"secret_backend"`
	PolicyDefault   bool     `json:"policy_default"`
	PluginCount     int      `json:"plugin_count"`
	AuditEntryCount int      `json:"audit_entry_count"`
	ClusterName     string   `json:"cluster_name"`
	Version         string   `json:"version"`
	WorkingDir      string   `json:"working_dir"`
	Routes          int      `json:"routes"`
	RouteNames      []string `json:"route_names,omitempty"`
}

StatusInfo is the extended status returned by GET /api/status.

type WebhookSpec added in v0.2.0

type WebhookSpec struct {
	Path    string // e.g. "/webhook/telegram"
	Handler http.Handler
	RPM     int // per-IP requests/min (0 → a sane default of 60)
}

WebhookSpec registers an external-platform webhook handler under /webhook/. Each webhook carries its own per-IP rate limit (separate from the management API and agent-submit limits) because these endpoints are internet-facing and authenticate via their platform's own signature, not an API key.

Jump to

Keyboard shortcuts

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