proxydb

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package proxydb is the pgx data layer: api keys, the model registry, routing rules, encrypted vendor keys, and the config version counter.

Index

Constants

View Source
const (
	TaskSubmitted     = "submitted"
	TaskWorking       = "working"
	TaskInputRequired = "input-required"
	TaskCompleted     = "completed"
	TaskFailed        = "failed"
	TaskCanceled      = "canceled"
)

Task statuses, as A2A names them.

View Source
const (
	ReasonQuestion  = "question"       // the recipient asks the sender
	ReasonGuardHold = "guardrail_hold" // a guardrail holds it for the recipient's person
	ReasonOwner     = "needs_owner"    // the recipient's agent asks its own person
)

Why a task is input-required.

View Source
const (
	AuthorAgent = "agent"
	AuthorOwner = "owner"
)

Who wrote a message on its side of the task.

View Source
const (
	PinnedFrom   = "from"
	PinnedTo     = "to"
	PinnedEither = "either"
)

Sides of a task for TaskFilter.Pinned.

View Source
const AcceptRevoked = "revoked:"

AcceptRevoked marks an accept_from entry whose agent's key was revoked.

View Source
const AgentsChannel = "ktms_agents"

AgentsChannel is the Postgres channel that names, after each commit, the agents whose tasks changed; waiting inbox calls of every replica listen.

View Source
const BatchRuleAttribute = "matched_rule"

BatchRuleAttribute is the batch attribute holding the rule that chose its model, so the poller's results and usage events name it as a live call does.

Variables

View Source
var (
	ErrNotFound      = errors.New("proxydb: not found")
	ErrAlreadyExists = errors.New("proxydb: already exists")
	ErrTenantInUse   = errors.New("proxydb: tenant still has active api keys")
)
View Source
var ErrBatchAlreadyExists = errors.New("proxydb: batch already exists")

ErrBatchAlreadyExists is returned on idempotency conflict if client resubmitted.

View Source
var ErrContextFull = errors.New("proxydb: conversation message limit reached")

ErrContextFull is a message beyond the limit of one conversation.

View Source
var ErrCorrectionLate = errors.New("proxydb: the task ended too long ago to correct")

ErrCorrectionLate is a correction to a task that ended longer ago than the window allows.

View Source
var ErrPairBusy = errors.New("proxydb: task limit between two agents reached")

ErrPairBusy is a task beyond the hourly limit of tasks one agent sends another.

View Source
var ErrTaskClosed = errors.New("proxydb: task already ended")

ErrTaskClosed is a change to a task that has already ended.

View Source
var ErrTaskOpen = errors.New("proxydb: task has not ended")

ErrTaskOpen is a correction to a task that has not ended: reply instead.

View Source
var ErrTooManyPins = errors.New("proxydb: too many pinned tasks")

ErrTooManyPins is a pin beyond the limit of one agent.

ReasonCodes are all reasons a task waits.

TaskOpenStatuses are the statuses of a task that has not ended.

TaskStatuses are all task statuses, in the order a task goes through them.

Functions

func CreateTeamTx added in v0.14.0

func CreateTeamTx(ctx context.Context, tx pgx.Tx, team *Team) error

func DeleteMCPCredential added in v1.4.0

func DeleteMCPCredential(ctx context.Context, tx pgx.Tx, server string) error

func DeleteMCPServer added in v1.4.0

func DeleteMCPServer(ctx context.Context, tx pgx.Tx, name string) error

DeleteMCPServer removes the server; its credential goes with it (cascade).

func DeleteModel

func DeleteModel(ctx context.Context, tx pgx.Tx, id string) error

func DeleteOrganizationTx added in v0.14.0

func DeleteOrganizationTx(ctx context.Context, tx pgx.Tx, id string) error

DeleteOrganizationTx removes an organization, its teams (cascade) and their spend limits, detaching disabled keys like DeleteTeamTx; active keys refuse it.

func DeleteSpendLimit

func DeleteSpendLimit(ctx context.Context, tx pgx.Tx, subjectType, subjectID, period string) error

func DeleteTeamTx added in v0.14.0

func DeleteTeamTx(ctx context.Context, tx pgx.Tx, id string) error

DeleteTeamTx removes a team and its spend limits. Disabled keys are detached (keys are never deleted, so they would pin the team forever); active keys make it ErrTenantInUse: revoke or move them first.

func DeleteUserRateLimit

func DeleteUserRateLimit(ctx context.Context, tx pgx.Tx, userID, modelID string) error

func DeleteVendorKey

func DeleteVendorKey(ctx context.Context, tx pgx.Tx, apiKeyID, vendor string) error

func Migrate

func Migrate(ctx context.Context, pool *pgxpool.Pool, src fs.FS) error

Migrate applies every embedded file that the ledger has not recorded yet.

Each file runs in its own transaction, so a failure leaves the earlier ones applied and the rest pending. A failure is the caller's cue to refuse to serve: half-migrated is a state the code was not written for.

func ReplaceRules

func ReplaceRules(ctx context.Context, tx pgx.Tx, rules []*Rule) error

ReplaceRules swaps the whole rule set; position encodes chain order.

func SetMCPCredential added in v1.4.0

func SetMCPCredential(ctx context.Context, tx pgx.Tx, c *MCPCredential) error

SetMCPCredential stores a server's credential; an unknown server is a foreign key violation (23503).

func SetTeamBudgetTx added in v0.14.0

func SetTeamBudgetTx(ctx context.Context, tx pgx.Tx, teamID string, limitNanoUSD int64) error

SetTeamBudgetTx makes the team's monthly spend limit match its budget: the team row and spend_limit change together, so they cannot drift apart.

func SetVendorKey

func SetVendorKey(ctx context.Context, tx pgx.Tx, v *VendorKey) error

func TaskTerminal added in v1.6.0

func TaskTerminal(status string) bool

TaskTerminal reports whether a task in this status can change no more.

func UpdateMCPCredentialCiphertext added in v1.4.0

func UpdateMCPCredentialCiphertext(ctx context.Context, tx pgx.Tx, server string, ciphertext []byte, version int32) error

UpdateMCPCredentialCiphertext is the rotation path: same value, newer keyring version.

func UpdateTeamTx added in v0.14.0

func UpdateTeamTx(ctx context.Context, tx pgx.Tx, team *Team, dataClassification *string) error

UpdateTeamTx replaces a team's settings; a nil dataClassification keeps the stored one, as in SetAPIKeyPolicy.

func UpdateVendorKeyCiphertext

func UpdateVendorKeyCiphertext(ctx context.Context, tx pgx.Tx, id string, ciphertext []byte, version int32) error

UpdateVendorKeyCiphertext is the rotation path: same secret, newer keyring version.

func UpsertMCPServer added in v1.4.0

func UpsertMCPServer(ctx context.Context, tx pgx.Tx, m *MCPServer) error

func UpsertModel

func UpsertModel(ctx context.Context, tx pgx.Tx, m *Model) error

func UpsertSpendLimit

func UpsertSpendLimit(ctx context.Context, tx pgx.Tx, l *SpendLimit) error

func UpsertUserRateLimit

func UpsertUserRateLimit(ctx context.Context, tx pgx.Tx, u *UserRateLimit) error

func ValidTaskStatus added in v1.6.0

func ValidTaskStatus(status string) bool

ValidTaskStatus reports whether status is one of TaskStatuses.

Types

type APIKey

type APIKey struct {
	ID                string
	Name              string
	KeyLookup         string
	KeyHash           string
	Scopes            []string
	DisabledAt        *time.Time
	CreatedAt         time.Time
	OrgID             *string
	TeamID            *string
	TeamAllowedModels []string
	// Policy of the key itself; empty and 0 mean no limit.
	AllowedModels []string
	RPMLimit      int32
	TPMLimit      int64
	// MCP servers and tools the key, and its team, may use; empty = any.
	AllowedMCP     []string
	TeamAllowedMCP []string
	// "restricted" on the key or its team keeps its calls on self-hosted nodes.
	DataClassification     string
	TeamDataClassification string
	// Owner is the person the key belongs to (an e-mail); "" for a service key.
	Owner string
}

func (*APIKey) Active

func (k *APIKey) Active() bool

type Agent added in v1.6.0

type Agent struct {
	KeyID       string
	Name        string
	Description string
	Skills      []string
	Repos       []string
	AcceptFrom  []string
	Recording   string
	// Released: the key was revoked and the name is free for another key.
	Released bool
	// From the key and its team.
	KeyName        string
	Owner          string
	OrgID          string
	TeamID         string
	Disabled       bool
	Scopes         []string
	KeyAllowedMCP  []string
	TeamAllowedMCP []string

	CreatedAt time.Time
	UpdatedAt time.Time
}

Agent is a client key's card: who it is and who may send it tasks.

type AgentCard added in v1.6.0

type AgentCard struct {
	Description *string
	Skills      []string
	Repos       []string
	AcceptFrom  []string
}

AgentCard is a change to an agent's card; a nil field keeps its value.

type AgentFilter added in v1.6.0

type AgentFilter struct {
	Owner          string
	IncludeRevoked bool
	// Org, when set, keeps the agents of that organization; "" in it means none.
	Org *string
}

AgentFilter picks agents for a listing; an empty owner does not filter.

type AgentMessage added in v1.6.0

type AgentMessage struct {
	ID        int64
	TaskID    string
	ContextID string
	FromAgent string
	FromName  string
	Role      string // "user" for the sender of the task, "agent" for its recipient
	Author    string // AuthorAgent, or AuthorOwner when the agent's person wrote it
	// Correction amends an answer after the task ended.
	Correction bool
	Text       string
	// Truncated: Text is the start of a longer message, cut by a bounded load.
	Truncated bool
	CreatedAt time.Time
}

type AgentTask added in v1.6.0

type AgentTask struct {
	ID           string
	ContextID    string
	FromAgent    string
	FromName     string
	ToAgent      string
	ToName       string
	Status       string
	StatusReason string
	ReasonCode   string // question, guardrail_hold or needs_owner while input-required
	// ExternalRef ties the task to an issue elsewhere, such as PROJ-123 or a URL.
	ExternalRef string
	// Each side pins for itself; a task pinned by either outlives the retention sweep.
	PinnedByFrom bool
	PinnedByTo   bool
	Depth        int32
	CreatedAt    time.Time
	UpdatedAt    time.Time
	// LastAuthor wrote the newest message on the recipient's side, read with
	// the task so answered_by holds when its messages are not loaded.
	LastAuthor string
	Messages   []*AgentMessage
	// Omitted counts the messages a bounded load left out.
	Omitted int
}

AgentTask is one request from one agent to another and its conversation.

type Batch

type Batch struct {
	ID            string
	ClientBatchID string
	APIKeyID      string
	KeyName       string
	Model         string
	VendorJobName string
	State         string // PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, EXPIRED
	TotalCount    int32
	DoneCount     int32
	FailedCount   int32
	Attributes    map[string]string
	ActionID      string
	CreatedAt     time.Time
	CompletedAt   *time.Time
	LeasedUntil   *time.Time
	// The submitting key's tenant, read on lease: stored attributes predate
	// the reserved team keys and may carry a caller's own team_id.
	OrgID  string
	TeamID string
}

type BatchItem

type BatchItem struct {
	BatchID        string
	CustomID       string
	Position       int32
	Status         string // PENDING, SUCCEEDED, FAILED
	ResponseSchema []byte // optional JSON representation of ResponseSchema
	Result         []byte // raw JSON of GenerateTextResponse
	Error          []byte // raw JSON of BatchItemError
	InputTokens    int64
	OutputTokens   int64
}

type DB

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

func New

func New(pool *pgxpool.Pool) *DB

func (*DB) AddAgentCorrection added in v1.6.0

func (d *DB) AddAgentCorrection(ctx context.Context, taskID, fromAgent, author, text string, window time.Duration, maxMessages int64) (*AgentTask, error)

AddAgentCorrection appends a correction to a task that has ended, within window of its last change; the task keeps its status, and its change wakes both agents. ErrTaskOpen while it has not ended.

func (*DB) AddAgentMessage added in v1.6.0

func (d *DB) AddAgentMessage(ctx context.Context, taskID, fromAgent, role, author, text, status, reason, reasonCode string, maxMessages int64) (*AgentTask, error)

AddAgentMessage appends a message to a task that has not ended and moves it to status; reason is kept with the status. ErrTaskClosed once it has ended. It returns the task without its messages.

func (*DB) AgentInContext added in v1.6.0

func (d *DB) AgentInContext(ctx context.Context, keyID, contextID string) (bool, error)

AgentInContext reports whether the agent sent or received a task of the conversation.

func (*DB) AgentKeysByName added in v1.6.0

func (d *DB) AgentKeysByName(ctx context.Context, name string) ([]string, error)

AgentKeysByName is the keys whose agents have ever had the name, a revoked key's included, so an audit finds the tasks of each.

func (*DB) ClearNodeOverride added in v1.5.0

func (d *DB) ClearNodeOverride(ctx context.Context, nodeID string) (*NodeSchedule, error)

ClearNodeOverride removes the override. A row that held only the override goes with it, so it never reads as a schedule someone set; ErrNotFound when there was no row.

func (*DB) CompleteBatch

func (d *DB) CompleteBatch(ctx context.Context, id string, finalState string, doneCount, failedCount int32, completedAt time.Time, items []*BatchItem) error

func (*DB) ConfigVersion

func (d *DB) ConfigVersion(ctx context.Context) (int64, error)

func (*DB) ContextDepth added in v1.6.0

func (d *DB) ContextDepth(ctx context.Context, contextID, toAgent string) (int32, error)

ContextDepth is the depth of the deepest task of a conversation sent to the agent, -1 for none.

func (*DB) ContextRef added in v1.6.0

func (d *DB) ContextRef(ctx context.Context, contextID string) (string, error)

ContextRef is the external_ref of the first task of a conversation, the one that opened it; "" for none.

func (*DB) CountAgentTasks added in v1.6.0

func (d *DB) CountAgentTasks(ctx context.Context) (map[string]int64, error)

CountAgentTasks is the number of tasks in each status; a status with no tasks is absent.

func (*DB) CreateAgentTask added in v1.6.0

func (d *DB) CreateAgentTask(ctx context.Context, t *AgentTask, text string, lim TaskLimits) error

CreateAgentTask stores a task with its first message, counting against the limits in the same transaction.

func (*DB) CreateBatch

func (d *DB) CreateBatch(ctx context.Context, b *Batch, items []*BatchItem) (*Batch, error)

func (*DB) CreateOrganization added in v0.14.0

func (d *DB) CreateOrganization(ctx context.Context, org *Organization) error

func (*DB) DeleteAgentTasksBefore added in v1.6.0

func (d *DB) DeleteAgentTasksBefore(ctx context.Context, cutoff time.Time) (int64, error)

DeleteAgentTasksBefore removes tasks unchanged since before cutoff, with their messages, and reports how many went. Pinned tasks stay.

func (*DB) DeleteBatchesOlderThan

func (d *DB) DeleteBatchesOlderThan(ctx context.Context, cutoff time.Time) (int64, error)

func (*DB) DeleteNodeSchedule added in v1.5.0

func (d *DB) DeleteNodeSchedule(ctx context.Context, nodeID string) error

func (*DB) DisableAPIKey

func (d *DB) DisableAPIKey(ctx context.Context, name string) error

DisableAPIKey revokes a key and frees its agent's name for another key.

func (*DB) ExpireBatch

func (d *DB) ExpireBatch(ctx context.Context, id string, expiredAt time.Time) error

func (*DB) GetAPIKeyByLookup

func (d *DB) GetAPIKeyByLookup(ctx context.Context, lookup string) (*APIKey, error)

func (*DB) GetAPIKeyByLowerName added in v1.6.0

func (d *DB) GetAPIKeyByLowerName(ctx context.Context, name string) (*APIKey, error)

GetAPIKeyByLowerName finds a key by its name in any case, an active one first.

func (*DB) GetAPIKeyByName

func (d *DB) GetAPIKeyByName(ctx context.Context, name string) (*APIKey, error)

func (*DB) GetAgentByKey added in v1.6.0

func (d *DB) GetAgentByKey(ctx context.Context, keyID string) (*Agent, error)

func (*DB) GetAgentByName added in v1.6.0

func (d *DB) GetAgentByName(ctx context.Context, name string) (*Agent, error)

GetAgentByName is the named agent of a live key, else the latest released one.

func (*DB) GetAgentTask added in v1.6.0

func (d *DB) GetAgentTask(ctx context.Context, id string) (*AgentTask, error)

GetAgentTask is a task without its messages.

func (*DB) GetBatch

func (d *DB) GetBatch(ctx context.Context, id, apiKeyID string) (*Batch, error)

func (*DB) GetBatchByClientBatchID

func (d *DB) GetBatchByClientBatchID(ctx context.Context, apiKeyID, clientBatchID string) (*Batch, error)

func (*DB) GetBatchByID

func (d *DB) GetBatchByID(ctx context.Context, id string) (*Batch, error)

func (*DB) GetNodeKeyByLookup

func (d *DB) GetNodeKeyByLookup(ctx context.Context, lookup string) (*NodeKey, error)

func (*DB) GetNodeSchedule added in v1.5.0

func (d *DB) GetNodeSchedule(ctx context.Context, nodeID string) (*NodeSchedule, error)

func (*DB) GetOrganization added in v0.14.0

func (d *DB) GetOrganization(ctx context.Context, id string) (*Organization, error)

func (*DB) GetTeam added in v0.14.0

func (d *DB) GetTeam(ctx context.Context, id string) (*Team, error)

func (*DB) InsertAPIKey

func (d *DB) InsertAPIKey(ctx context.Context, k *APIKey) error

func (*DB) InsertAgent added in v1.6.0

func (d *DB) InsertAgent(ctx context.Context, keyID, name string) error

InsertAgent gives a key its agent named name, unless it has one. A name kept by a revoked key's agent is taken over; ErrAlreadyExists when a live key's agent has it.

func (*DB) InsertNodeKey

func (d *DB) InsertNodeKey(ctx context.Context, k *NodeKey) error

func (*DB) LeaseUnfinishedBatches

func (d *DB) LeaseUnfinishedBatches(ctx context.Context, leaseDuration time.Duration, limit int) ([]*Batch, error)

func (*DB) ListAPIKeys

func (d *DB) ListAPIKeys(ctx context.Context) ([]*APIKey, error)

func (*DB) ListAgentTasks added in v1.6.0

func (d *DB) ListAgentTasks(ctx context.Context, f TaskFilter) ([]*AgentTask, error)

ListAgentTasks lists tasks without their messages, most recently changed first.

func (*DB) ListAgents added in v1.6.0

func (d *DB) ListAgents(ctx context.Context, f AgentFilter) ([]*Agent, error)

ListAgents lists agents by name, by default only those whose key is active.

func (*DB) ListAllBatchItems

func (d *DB) ListAllBatchItems(ctx context.Context, batchID string) ([]*BatchItem, error)

func (*DB) ListBatchItems

func (d *DB) ListBatchItems(ctx context.Context, batchID string, limit, offset int) ([]*BatchItem, error)

func (*DB) ListNodeKeys

func (d *DB) ListNodeKeys(ctx context.Context) ([]*NodeKey, error)

func (*DB) ListNodeSchedules added in v1.5.0

func (d *DB) ListNodeSchedules(ctx context.Context) ([]*NodeSchedule, error)

func (*DB) ListOrganizations added in v0.14.0

func (d *DB) ListOrganizations(ctx context.Context) ([]*Organization, error)

func (*DB) ListTeams added in v0.14.0

func (d *DB) ListTeams(ctx context.Context, orgID string) ([]*Team, error)

func (*DB) ListenAgents added in v1.6.0

func (d *DB) ListenAgents(ctx context.Context, wake func(keyID string)) error

ListenAgents calls wake with the key id of each agent whose tasks changed, until ctx ends or the connection fails; the caller listens again.

func (*DB) LoadMCPCredentials added in v1.4.0

func (d *DB) LoadMCPCredentials(ctx context.Context) ([]*MCPCredential, error)

func (*DB) LoadMCPServers added in v1.4.0

func (d *DB) LoadMCPServers(ctx context.Context) ([]*MCPServer, error)

func (*DB) LoadModels

func (d *DB) LoadModels(ctx context.Context) ([]*Model, error)

func (*DB) LoadRules

func (d *DB) LoadRules(ctx context.Context) ([]*Rule, error)

func (*DB) LoadSpendLimits

func (d *DB) LoadSpendLimits(ctx context.Context) ([]*SpendLimit, error)

func (*DB) LoadUserRateLimits

func (d *DB) LoadUserRateLimits(ctx context.Context) ([]*UserRateLimit, error)

func (*DB) LoadVendorKeys

func (d *DB) LoadVendorKeys(ctx context.Context) ([]*VendorKey, error)

func (*DB) Mutate

func (d *DB) Mutate(ctx context.Context, fn func(tx pgx.Tx) error,
	validate func(models []*Model, rules []*Rule) error) (int64, error)

Mutate runs fn inside a transaction, then revalidates the resulting config via validate and bumps the version counter. Any error rolls everything back.

func (*DB) RevokeNodeKey

func (d *DB) RevokeNodeKey(ctx context.Context, id int64) (string, error)

func (*DB) SetAPIKeyPolicy added in v1.0.0

func (d *DB) SetAPIKeyPolicy(ctx context.Context, name string, allowedModels []string, rpm int32, tpm int64, allowedMCP []string, dataClassification *string) error

SetAPIKeyPolicy replaces the policy of the key with this name. SetAPIKeyPolicy replaces a key's policy. A nil dataClassification keeps the stored one, decided in the same UPDATE so a concurrent lift is not undone.

func (*DB) SetAgentRecording added in v1.6.0

func (d *DB) SetAgentRecording(ctx context.Context, name, recording string) error

SetAgentRecording sets the journal level of the named agent.

func (*DB) SetAgentTaskPinned added in v1.6.0

func (d *DB) SetAgentTaskPinned(ctx context.Context, taskID, byAgent string, pinned bool, maxPinned int64) (*AgentTask, error)

SetAgentTaskPinned pins or unpins a task on byAgent's side; ErrNotFound when byAgent is neither its sender nor its recipient. maxPinned bounds the tasks byAgent has pinned, counted under a lock on that agent; 0 means no bound. It leaves updated_at alone, so a pin neither renews the retention of a task nor reopens its correction window.

func (*DB) SetNodeOverride added in v1.5.0

func (d *DB) SetNodeOverride(ctx context.Context, nodeID string, level int32, until time.Time) (*NodeSchedule, error)

SetNodeOverride sets the override and bumps the version; a node with no row gets one with no rules.

func (*DB) SetNodeScheduleText added in v1.5.0

func (d *DB) SetNodeScheduleText(ctx context.Context, nodeID, text string) (*NodeSchedule, error)

SetNodeScheduleText stores the rules and bumps the version, keeping any override.

func (*DB) UpdateAgentCard added in v1.6.0

func (d *DB) UpdateAgentCard(ctx context.Context, keyID string, c AgentCard) error

UpdateAgentCard changes the fields of c on the key's card.

func (*DB) UpdateBatchRunning

func (d *DB) UpdateBatchRunning(ctx context.Context, id string, total, done, failed int32) error

func (*DB) WithAgentMessages added in v1.6.0

func (d *DB) WithAgentMessages(ctx context.Context, tasks []*AgentTask, window int) error

WithAgentMessages fills in the messages of the tasks, oldest first. With a window above 0 each task keeps its first message, cut to window bytes, and its newest within window bytes; Omitted counts the others.

type MCPCredential added in v1.4.0

type MCPCredential struct {
	Server          string
	Header          string
	ValueCiphertext []byte
	ValueVersion    int32
	CreatedAt       time.Time
}

MCPCredential is the header the gateway adds to a server's requests.

func LockStaleMCPCredentialsTx added in v1.4.0

func LockStaleMCPCredentialsTx(ctx context.Context, tx pgx.Tx, version int32) ([]*MCPCredential, error)

LockStaleMCPCredentialsTx is LockStaleVendorKeysTx for MCP credentials.

type MCPServer added in v1.4.0

type MCPServer struct {
	Name             string
	URL              string
	Transport        string // "streamable_http" | "sse"
	Enabled          bool
	AllowPrivate     bool
	TimeoutMs        int32
	MaxResponseBytes int64
	ToolRPM          int32
}

MCPServer is an upstream MCP server the gateway proxies.

type Model

type Model struct {
	ID       string
	Vendor   string
	Endpoint string
	Efforts  []string // deprecated: read as general (registry.Competencies), until 2.0
	// Competencies is topic -> level (basic | proficient | expert), 1.7.
	Competencies    map[string]string
	Capabilities    []string
	RPM             int32
	PriceInPerMtok  float64
	PriceOutPerMtok float64
	// Peak rates, 0 when the vendor bills one price around the clock. DeepSeek
	// V4 doubles for two windows a day, so one price understates its cost.
	PriceInPeakPerMtok  float64
	PriceOutPeakPerMtok float64
	// Batch rates, 0 means half the standard (off-peak) rate.
	PriceInBatchPerMtok  float64
	PriceOutBatchPerMtok float64
	// Prompt-cache rates at the standard rate, 0 = the vendor default.
	PriceCacheReadPerMtok  float64
	PriceCacheWritePerMtok float64
	DailyTokensPerKey      int64
	DailyTokensPerUser     int64
	Burst                  int32
	QueueTimeoutMs         int32
	BudgetGraceMargin      float64
	Enabled                bool
	// Translate: language pairs served ("*" for any, required on translate
	// models) and a price per million source characters, added to tokens.
	LanguagesSource      []string
	LanguagesTarget      []string
	PricePerMillionChars float64
}

func (*Model) BatchPriceInPerMtok

func (m *Model) BatchPriceInPerMtok() float64

func (*Model) BatchPriceOutPerMtok

func (m *Model) BatchPriceOutPerMtok() float64

func (*Model) CacheReadPerMtok added in v1.0.0

func (m *Model) CacheReadPerMtok() float64

CacheReadPerMtok is the standard rate for input read from the prompt cache. Unset, a vendor ratio that never undercharges: Anthropic's 0.1x holds for every Claude model, Bedrock's 0.25x covers Claude (0.1x) and Nova (0.25x).

func (*Model) CacheWritePerMtok added in v1.0.0

func (m *Model) CacheWritePerMtok() float64

CacheWritePerMtok is the standard rate for input written to the prompt cache: Anthropic and Bedrock charge Claude 1.25x input for the default 5-minute cache.

func (*Model) EffectiveBurst

func (m *Model) EffectiveBurst() int32

type NodeKey

type NodeKey struct {
	ID             int64
	NodeID         string
	Name           string
	KeyLookup      string
	KeyHash        string
	AllowedCIDRs   []string
	AllowedModels  []string
	MaxBaseWeight  float64
	MaxConcurrency int32
	DisabledAt     *time.Time
	CreatedAt      time.Time
}

func (*NodeKey) Active

func (k *NodeKey) Active() bool

type NodeSchedule added in v1.5.0

type NodeSchedule struct {
	NodeID        string
	Text          string
	Version       int64
	OverrideLevel *int32
	OverrideUntil *time.Time
	UpdatedAt     time.Time
}

NodeSchedule is the schedule KTMS sends a node that takes its levels from it.

type Organization added in v0.14.0

type Organization struct {
	ID        string
	Name      string
	CreatedAt time.Time
}

type Rule

type Rule struct {
	ID               string
	Name             string
	Priority         int32
	Effort           string            // "" = any; deprecated: use Needs, until 2.0
	Needs            map[string]string // topic -> least level the request needs, 1.7
	Attributes       map[string]string
	Enabled          bool
	Use              []string // ordered model ids
	Weights          []int32  // optional traffic weights per model in Use
	ShadowModel      string   // optional shadow model for async traffic mirroring
	ShadowPercentage float64  // 0.0 to 100.0 percent of traffic mirrored to ShadowModel
	ShadowEval       bool     // optional automated quality evaluation using Judge
}

type SpendLimit

type SpendLimit struct {
	SubjectType  string // "key" | "user" | "team"
	SubjectID    string // key name / user id, or "*" for the subject type's default
	Period       string // "day" | "month"
	LimitNanoUSD int64
}

SpendLimit caps spend for one subject over one UTC calendar period.

type TaskFilter added in v1.6.0

type TaskFilter struct {
	ToAgent   string
	FromAgent string
	// Either side: one of the agents sent or received the task.
	Agents   []string
	Statuses []string
	// Only waiting for these reasons (question, guardrail_hold, needs_owner).
	ReasonCodes []string
	// Only tasks changed after this moment; zero for any.
	Since       time.Time
	ExternalRef string
	// Only pinned tasks: PinnedFrom (by their sender), PinnedTo (by their
	// recipient) or PinnedEither.
	Pinned string
	Limit  int
}

TaskFilter picks tasks for a listing; empty fields do not filter.

type TaskLimits added in v1.6.0

type TaskLimits struct {
	Messages    int64 // in one conversation
	PairPerHour int64 // tasks one agent sends another within an hour
}

TaskLimits bound new tasks; 0 means no bound.

type Team added in v0.14.0

type Team struct {
	ID               string
	OrgID            string
	Name             string
	MonthlyBudgetUSD float64
	AllowedModels    []string
	AllowedMCP       []string
	CreatedAt        time.Time
	// "restricted" keeps every key of the team on self-hosted nodes; "" does not.
	DataClassification string
}

type UserRateLimit

type UserRateLimit struct {
	UserID         string
	ModelID        string
	RPM            int32
	Burst          int32
	QueueTimeoutMs int32
	DailyTokens    int64
}

func (*UserRateLimit) EffectiveBurst

func (u *UserRateLimit) EffectiveBurst() int32

type VendorKey

type VendorKey struct {
	ID            string
	APIKeyID      string
	APIKeyName    string // joined for admin listings
	Vendor        string
	KeyCiphertext []byte
	KeyVersion    int32
	CreatedAt     time.Time
}

func LockStaleVendorKeysTx added in v0.14.0

func LockStaleVendorKeysTx(ctx context.Context, tx pgx.Tx, version int32) ([]*VendorKey, error)

LockStaleVendorKeysTx reads the vendor keys not at version and locks them until the transaction ends, so a key set meanwhile cannot be overwritten by a stale re-encryption of the previous one. Keys already at version are left unlocked: a rotation never rewrites them.

Jump to

Keyboard shortcuts

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