surplus

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 18 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 surplus polls the Surplus Intelligence market, model list and balance on a fixed schedule.

Index

Constants

View Source
const (
	ErrMinimumDiscountNotMet         = "minimum_discount_not_met"
	ErrMinimumDiscountSupplyCooldown = "minimum_discount_supply_cooldown"
	ErrNoHealthySellers              = "no_healthy_sellers"
	ErrNoHealthyTrustedSellers       = "no_healthy_trusted_sellers"
	ErrInsufficientCredit            = "insufficient_credit"
	ErrBudgetExceeded                = "budget_exceeded"
)

Surplus upstream error codes handled specially by remora's cooling.

Verified 2026-12-03 from https://www.surplusintelligence.ai/llms-full.txt: param appears only on 400 validation errors, never on 404 or 402, so the front door falls back in-request on 404 minimum_discount_not_met (B/core/failureclass.go:194,318-324) and remora cools the member for 60 s.

View Source
const (
	MinInterval     = 5 * time.Minute
	DefaultInterval = 5 * time.Minute
)

Polling cadence bounds.

View Source
const DefaultBaseURL = "https://api.surplusintelligence.ai"

DefaultBaseURL is the public Surplus Intelligence host root; /api/markets and /v1 sit beside each other.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	Provider, KeyID, Secret string
}

Account identifies a Surplus provider and its first enabled key.

type Balance

type Balance struct {
	CreditMicroUSD int64
	CheckedAt      time.Time
	Err            string
}

Balance is the last checked credit balance of one Surplus provider.

type Charges

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

Charges bridges proxy response headers and the log feed to supply real Surplus per-request charges. Inline charges are returned synchronously from Actual; missing or streamed charges are looked up via GET /v1/requests/{id} and settled once both the response end and the engine log row are observed.

func NewCharges

func NewCharges(
	baseURL string,
	secret func(ctx context.Context, keyID string) (string, error),
	settle SettleFunc,
	isSurplus func(provider string) bool,
	log *slog.Logger,
) *Charges

NewCharges creates a Charges store. A nil log discards.

func (*Charges) Actual

func (c *Charges) Actual(row bifrost.Log) (float64, bool)

Actual returns the real USD charge for a successful Surplus log row. It is idempotent on re-delivery. Non-success rows and unknown/pending charges return (0, false).

func (*Charges) Ended

func (c *Charges) Ended(reqID, engineProvider, model string)

Ended marks the HTTP response body as finished and queues a lookup job if the log row has already arrived.

func (*Charges) Run

func (c *Charges) Run(ctx context.Context)

Run drains pending charge lookup jobs through a 4/s rate limiter until ctx is cancelled.

func (*Charges) Seen

func (c *Charges) Seen(reqID, engineProvider, model, upstreamID, keyID string, microUSD *int64)

Seen records the upstream request id and optional inline micro-USD charge captured from response headers. If the log feed already delivered the row via Actual before headers arrived, Seen merges the metadata and either queues an immediate settlement (when an inline charge is present) or lets Ended queue the lookup.

func (*Charges) Wants

func (c *Charges) Wants(engineProvider string) bool

Wants reports whether engineProvider is a Surplus provider whose responses should be tracked.

type Config

type Config struct {
	BaseURL  string                                     // DefaultBaseURL unless overridden
	Interval time.Duration                              // DefaultInterval when <= 0
	Client   *http.Client                               // default client with timeout when nil
	OnCredit func(ctx context.Context, provider string) // called when a balance read returns > 0
}

Config configures the Surplus market, model and balance Worker.

type Equivalent

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

Equivalent supplies Surplus direct list prices from a Worker's cached /v1/models and /api/markets snapshots.

func NewEquivalent

func NewEquivalent(w *Worker) *Equivalent

NewEquivalent constructs an Equivalent source backed by w.

func (*Equivalent) Equivalent

func (e *Equivalent) Equivalent(_, model string) (prices.Price, bool)

Equivalent returns the direct USD-per-1M-token rates for model when known, else ok=false so the pricer falls back to the daily price catalogue. Missing cache read/write rates default to direct input, matching prices.Catalog.

type Quote

type Quote struct {
	Input, Output, CacheRead, CacheWrite                         *int64
	DirectInput, DirectOutput, DirectCacheRead, DirectCacheWrite *int64
	HealthySellers                                               int
	DiscountPct                                                  *float64
	Trend                                                        *Trend
}

Quote holds the best trusted-seller prices and direct reference prices for one model, in micro-USD per 1M tokens (nil = not offered).

type SettleFunc

type SettleFunc func(ctx context.Context, logID string, usd float64, state string) error

SettleFunc records a late actual charge for a previously unpriced log row.

type Trend

type Trend struct {
	CurrentPct, PreviousPct float64
	Direction               string
}

Trend describes the recent change in live discount for a model.

type Worker

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

Worker periodically reads /api/markets, per-provider /v1/payments/balance, and daily /v1/models from Surplus, keeping the last good snapshot on failure.

func NewWorker

func NewWorker(cfg Config, providers func(context.Context) ([]Account, error), log *slog.Logger) *Worker

NewWorker returns a Worker configured with cfg. A nil log discards.

func (*Worker) Balance

func (w *Worker) Balance(provider string) (Balance, bool)

Balance returns the last recorded balance for provider.

func (*Worker) LastError

func (w *Worker) LastError() string

LastError returns the error from the most recent /api/markets read, or "".

func (*Worker) Market

func (w *Worker) Market(model string) (Quote, bool)

Market returns the last good quote for model, if present.

func (*Worker) MarketStatus

func (w *Worker) MarketStatus() (map[string]Quote, time.Time, string)

MarketStatus atomically returns the last good snapshot, its fetch time, and the last market error.

func (*Worker) Markets

func (w *Worker) Markets() (map[string]Quote, time.Time)

Markets returns a copy of the last good market snapshot and its fetch time.

func (*Worker) Models

func (w *Worker) Models() []string

Models returns the sorted model IDs from the last good /v1/models read.

func (*Worker) Ready

func (w *Worker) Ready() <-chan struct{}

Ready returns a channel that closes once after the first successful /api/markets read.

func (*Worker) RefreshBalance

func (w *Worker) RefreshBalance(ctx context.Context, provider string) bool

RefreshBalance immediately reads /v1/payments/balance for provider when it is a configured Surplus provider, updating the cached balance and firing OnCredit if credit > 0.

func (*Worker) Run

func (w *Worker) Run(ctx context.Context)

Run polls at once and then every cfg.Interval until ctx is cancelled.

func (*Worker) Wake

func (w *Worker) Wake()

Wake schedules an immediate poll instead of waiting for the next interval tick.

Jump to

Keyboard shortcuts

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