api

package
v0.32.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 33 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 api is the run-request API (§4): once SP3 ships, the only way to create an AgentRun. The principal comes from the caller's token, never from the body.

Index

Constants

View Source
const (
	LedgerPrefix = "agent-factory-ledger-usd-"
	// LegacyLedgerPrefix names the token ledgers the USD ones replaced (#155): nothing reads or
	// writes them; the meter's pruner deletes them once they are older than its retention.
	LegacyLedgerPrefix = "agent-factory-ledger-"
	// LedgerSpent is one JSON map, principal → micro-USD. It is a map rather than one key per
	// principal because principal ids carry ":", which no ConfigMap key may hold. The meter
	// owns this column; admission only reads it.
	LedgerSpent = "spent"
	// LedgerReserved prefixes one key per admitted run — reserved.<runId>, whose C2 id is
	// key-safe — holding {principal, person, room, maxMicroUSD}. Release drops the entry when the
	// run ends or its claim goes (#55); the spend it made stays: deleting a run refunds nothing.
	LedgerReserved = "reserved."
	// LedgerSettled prefixes one key per metered run, settled.<runId>: the micro-USD charged to
	// that run that day, written by the meter in the same write as spent. Per key, spent is the
	// sum of settled over the runs charged to it; summed over the retained days, it is how much
	// of a run any meter has charged, so a new leader charges neither twice nor less (TC6). One
	// exception: on the day a lifted run (R10) is first charged, its settled entry also holds the
	// lift, which spent never counted, so settled exceeds that run's share of spent by it.
	LedgerSettled = "settled."
	// LedgerDayLayout labels the ledger with the UTC day it counts.
	LedgerDayLayout = "20060102"
	// LedgerAttempts bounds the conflict-retry loop: steady contention of that depth is
	// failure, not patience.
	LedgerAttempts = 5
)

Ledger layout (R50). One ConfigMap per UTC day, agent-factory-ledger-usd-<YYYYMMDD>, in the factory's namespace: the apiserver's resourceVersion is the transaction, so two replicas cannot take one slot. Every amount is micro-USD (truthful costs TC6). Exported so the meter reads and writes the same encoding: admission owns the reservations, the meter owns the spend.

View Source
const AudienceSystem = "agent-factory"

AudienceSystem is what a system caller's projected token carries (R23).

View Source
const KeyLifetime = 24 * time.Hour

KeyLifetime is how long an Idempotency-Key answers with its first run: the ledger's day.

View Source
const (
	MeterHeartbeat = "agent-factory-meter"
)

The meter's heartbeat (#54). Every replica admits but only the leader meters, so the meter's health lives in the apiserver beside the ledgers: one ConfigMap the meter stamps after each tick that metered, holding when, and how long admission may go on without a newer stamp.

Variables

View Source
var (
	ErrOverBudget = errors.New("ledger: over the daily budget")
	// ErrPersonOverBudget is the person's day, not the fleet's (D4): checked first, so a refusal
	// names whose cap it is.
	ErrPersonOverBudget = errors.New("ledger: over the person's daily budget")
	ErrRunBusy          = errors.New("ledger: the run id holds another reservation")
	ErrRoomBusy         = errors.New("ledger: a reservation holds the room")
	ErrLedgerBusy       = errors.New("ledger: busy")
)

Reserve's refusals. Any other error is the ledger unread or unwritten.

View Source
var ErrMeterBlind = errors.New("ledger: the meter is blind")

ErrMeterBlind is Reserve's refusal while the meter has not metered within its blind interval, so no cap it feeds holds.

Functions

func AddSettled

func AddSettled(cm *corev1.ConfigMap, inc map[string]int64) error

AddSettled adds each run's micro-USD to its settled.<runId> entry: the meter's half of the one write that also carries the spent column.

func DayUsed

func DayUsed(ctx context.Context, c client.Reader, ns, principal string, now time.Time) (int64, error)

DayUsed reads principal's use of the UTC day of now from that day's ledger, in micro-USD, as admission does: a missing ledger is a day with nothing used. c must read ConfigMaps live: the factory's cached watch sees the stop object only.

func LedgerDay

func LedgerDay(name, prefix string) (string, bool)

LedgerDay is the UTC day name carries after prefix, and whether name is prefix followed by a day at all. LegacyLedgerPrefix is a prefix of LedgerPrefix, so a USD ledger read against it yields "usd-<day>", which is no day: test LedgerPrefix first.

func LedgerSpentColumn

func LedgerSpentColumn(cm *corev1.ConfigMap) (map[string]int64, error)

LedgerSpentColumn reads a ledger's spent map, nil when the column is empty. Exported with the layout constants above so admission and the meter parse and write one encoding.

func OverDaily

func OverDaily(usedMicroUSD, maxMicroUSD, limit int64) bool

OverDaily is the daily cap's one decision (R50), in micro-USD (TC7): a run that may spend maxMicroUSD does not fit beside what the principal's day already holds. The API's admission and the factory's Queued (N2) both decide on it.

func Release

func Release(ctx context.Context, c client.Client, ns string, day time.Time, ids ...string) error

Release drops the reservations of ids from the ledger of day's UTC day (#55): a run's occupancy ends however the run ended, its spend stays in the spent column. Idempotent by run id — an absent ledger or entry is already released, and a conflict re-reads — so a replay after a crash, or a second releaser, drops nothing twice and never another run's entry.

func Reserve

func Reserve(ctx context.Context, c client.Client, ns string, now time.Time, id string, mine Reservation,
	limit, personLimit int64, enforce bool) (over string, err error)

Reserve is R50's atomic admission, shared by the API and the factory's Queued (#78): read the UTC day of now's ledger, check spent + reserved + maxMicroUSD against limit and that no reservation holds mine.Room, then write reserved.<id> — the Update conflicts against a concurrent writer's, and the retry re-reads and re-checks, so exactly one admission per slot lands whatever the interleaving. Unless enforce (R3's shadow), an over day is reported as over, written, and never refused; room exclusion stays exact. An enforced cap also refuses while the meter is blind (#54): its spend column is then stale. Release drops the entry when the run ends.

mine.Person, when set, is checked against personLimit in the same read and charged by the same write (D3). over names the key whose day the run does not fit, the person's first; "" fits.

func SetLedgerSpentColumn

func SetLedgerSpentColumn(cm *corev1.ConfigMap, spent map[string]int64) error

SetLedgerSpentColumn writes the spent map as the ledger's one JSON column.

func SettledByRun

func SettledByRun(ctx context.Context, c client.Reader, ns string) (map[string]int64, error)

SettledByRun sums settled.<runId> over every day ledger in ns: what the meters have charged each run so far, the floor a meter that first sees a run starts it from (TC6). The pruner bounds the sum to the retained days. c must list ConfigMaps live: the factory's cache sees the stop object only. One entry that does not parse fails the whole read: a meter must not guess what was charged.

func SettledByRunDay

func SettledByRunDay(ctx context.Context, c client.Reader, ns string) (map[string]map[string]int64, error)

SettledByRunDay is SettledByRun's read by UTC day: each run's settled entries, day by day.

func SettledColumn

func SettledColumn(cm *corev1.ConfigMap) (map[string]int64, error)

SettledColumn reads a day ledger's settled.<runId> entries: the micro-USD charged to each run that day. Nil when there are none.

func StampMeter

func StampMeter(ctx context.Context, c client.Client, ns string, at time.Time, blindAfter time.Duration) error

StampMeter records that the meter metered at at, and the interval past which admission counts it blind. A failed stamp is the next tick's to retry.

Types

type Authenticating

type Authenticating interface {
	Authenticate(*http.Request) (authn.Principal, error)
}

Authenticating maps a request to its caller. Task 5.1's Authenticator satisfies it; the principal is always the token's, never the body's (SC-13).

type Authenticator

type Authenticator struct {
	Humans      *authn.Verifier   // ZITADEL, offline against its JWKS
	Groups      policy.Groups     // the two agents groups; a human must be in one (R23)
	ClientIDs   func() []string   // rooms-proxy (the broker forwards it) and maku (the CLI)
	Systems     *authn.Verifier   // the cluster's issuer; nil when no system caller is allowed
	SystemAllow map[string]string // ServiceAccount sub → system:<component>; empty ships: none exists yet
	// Sponsored is F4's third branch; nil while api.sponsored is empty.
	Sponsored *authn.Sponsored
}

Authenticator maps a run-request to its caller: a human through one of the two rooms clients (the broker forwards rooms-proxy's token, maku sends its own), or an allowlisted system caller on the cluster's issuer.

func (*Authenticator) Authenticate

func (a *Authenticator) Authenticate(r *http.Request) (authn.Principal, error)

Authenticate maps r to its caller's principal, from the bearer token alone. A valid token for a rejected caller is not mistaken for an invalid one: an unadmitted human and an unlisted system caller are ErrForbidden, every other refusal ErrUnauthenticated.

type GitHubAccess

type GitHubAccess struct {
	Identity interface {
		Login(ctx context.Context, sub, repository string) (string, error)
	}
	Perms interface {
		CanWrite(ctx context.Context, repository, login string) (bool, error)
	}
}

GitHubAccess is v2 D4's WriteChecker: the principal's GitHub login from their ZITADEL link (the broker forwards the token, never a login), then that login's permission on the repository. No link is no write; a lookup that fails is an error, which the server refuses.

func (GitHubAccess) CanWrite

func (a GitHubAccess) CanWrite(ctx context.Context, p authn.Principal, repository string) (bool, error)

CanWrite implements WriteChecker.

func (GitHubAccess) Person

func (a GitHubAccess) Person(ctx context.Context, p authn.Principal, repository string) (string, error)

Person implements PersonResolver (v2 per-person caps D1): github:<login> from the same link CanWrite reads, "" with no sub or no link.

type Incident

type Incident struct {
	Alert      string  `json:"alert"`
	Resource   string  `json:"resource"`
	Severity   string  `json:"severity"`
	Cluster    string  `json:"cluster"`
	Verdict    string  `json:"verdict"`
	Confidence float64 `json:"confidence"`
}

Incident is RunLore's finding, as an internal principal sends it (RA3, RA6): identifiers for the stub issue and the gates' inputs. The finding itself is the request's text.

type IssueFiler

type IssueFiler interface {
	CreateIssue(ctx context.Context, title, body string, labels []string) (forge.Issue, error)
}

IssueFiler files an issue as the factory App: RunLore's CreateIssue, whose answer is a forge.Issue since the splitter (#195).

type LoginResolver

type LoginResolver interface {
	Login(ctx context.Context, sub, repository string) (string, error)
}

LoginResolver is a ZITADEL sub's current GitHub login, "" when it has none; ghidentity.ErrInactive when the user is not active. *ghidentity.Resolver implements it.

type PersonResolver

type PersonResolver interface {
	Person(ctx context.Context, p authn.Principal, repository string) (string, error)
}

PersonResolver names the person a human principal is charged as (v2 per-person caps D1): github:<login> through their ZITADEL link, "" with no link. An error is no answer.

type Reservation

type Reservation struct {
	Principal   string `json:"principal"`
	Person      string `json:"person,omitempty"`
	Room        string `json:"room,omitempty"`
	MaxMicroUSD int64  `json:"maxMicroUSD"`
}

Reservation is one ledger entry: what the run may spend, in micro-USD, on whose behalf and on which room. Person is the second key the same entry charges (v2 per-person caps D3): the person who caused the run, beside the fleet as Principal. One key per run is what makes both reservations one write: no run ever holds one without the other.

type RunRequest

type RunRequest struct {
	Role       string `json:"role"`
	Repository string `json:"repository"`
	BaseRef    string `json:"baseRef"`
	Task       struct {
		Text string `json:"text"`
		URL  string `json:"url"`
	} `json:"task"`
	DataClass      string   `json:"dataClass"`
	RoomRef        string   `json:"roomRef"`
	Model          string   `json:"model"`
	MaxTokens      int64    `json:"maxTokens"`
	EgressProfiles []string `json:"egressProfiles"`
	// R35: a stopped run's branch, to resume on. Never a task's or a live run's.
	ResumeBranch string `json:"resumeBranch"`
}

RunRequest is the POST /v1/runs body (§4). Unknown fields — principal and branch included — are ignored: the principal is the token's (SC-13) and the branch the factory's (C3).

type RunStore

type RunStore interface {
	Create(ctx context.Context, s runs.Spec) error
	List(ctx context.Context) ([]runs.Run, error)
}

RunStore creates the claim and lists the live runs the room and branch checks read. Since R50 the daily budget does not come from List: it is admitted through the day's ledger.

type Server

type Server struct {
	Auth Authenticating
	// Groups names the two agents groups: policy's StartRun rule is the room UI's rule, so
	// the CLI grants nothing the UI refuses (SP2 §1).
	Groups policy.Groups
	Cfg    *config.Config
	Runs   RunStore
	// Rooms is the manager's client: it reads Rooms and Tasks (rights, R35), and R50's
	// ledger reservation writes ConfigMaps, so a client.Reader would not do.
	Rooms     client.Client
	Namespace string
	Stopped   func(context.Context) bool // the stop object (§6.1); true on doubt
	NewRunID  func() string
	Now       func() time.Time
	Metrics   *fmetrics.Set
	// Owned is v2 D7's fence: whether the repository's default branch names this factory. nil owns
	// nothing.
	Owned func(repository string) bool
	// Access is v2 D4: whether a human may write the repository on GitHub. nil refuses every
	// human: GitHub is the one answer to who may change a repository, and there is no bypass.
	Access WriteChecker
	// SlackLinks is the broker's self-serve link records (GET /v1/links/slack) and Logins the
	// ZITADEL resolver that turns a linked sub into its current GitHub login: read only for a
	// sponsored principal with onBehalfOf.slackLinks. Either nil makes every such link not_linked.
	SlackLinks SlackLinkReader
	Logins     LoginResolver
	// People is D1's identity link, read only while budgets.perPerson is on: the person a human
	// token is charged as. nil charges every human as their own principal.
	People PersonResolver
	// Forges files an api task's issue as the factory App on its repository (R10): nil files none;
	// a nil filer for a repository refuses a titled request.
	Forges func(repository string) IssueFiler
	// Log records the causes the intake never answers; nil records none.
	Log *slog.Logger
	// Redact is the broker's secret redactor (*redact.Redactor), applied to an api task's issue
	// before it is filed; nil refuses a titled request.
	Redact interface {
		String(s string) (string, []string)
	}
}

Server is the run-request API (§4). It serves on every replica (NeedLeaderElection is false), and admission is atomic across replicas through the day's ledger (R50).

func (*Server) Handler

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

Handler is the API's mux: POST /v1/runs, admission in §4's order, and POST /v1/tasks while a sponsored principal is declared.

func (*Server) NeedLeaderElection

func (s *Server) NeedLeaderElection() bool

NeedLeaderElection is false: every replica serves intake.

func (*Server) Start

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

Start serves on api.listen until ctx ends, then drains.

type SlackLinkReader

type SlackLinkReader interface {
	SlackLink(ctx context.Context, team, user string) (sub string, found bool, err error)
}

SlackLinkReader is the broker's self-serve link records: the ZITADEL sub a Slack user linked; *rooms.Client implements it.

type TaskRequest

type TaskRequest struct {
	Repository string  `json:"repository"`
	Title      string  `json:"title,omitempty"`
	Text       string  `json:"text"`
	DataClass  string  `json:"dataClass"`
	MaxCostUSD float64 `json:"maxCostUSD"`
	OnBehalfOf string  `json:"onBehalfOf,omitempty"`
	Ref        string  `json:"ref,omitempty"`
	// Incident is an internal principal's finding (RA3); a sponsored principal's request refuses it.
	Incident *Incident `json:"incident,omitempty"`
}

TaskRequest is POST /v1/tasks's body (F4). Unknown fields are refused: class, tier, template, auto-merge and egress are never the caller's (F8, R11).

type WriteChecker

type WriteChecker interface {
	CanWrite(ctx context.Context, p authn.Principal, repository string) (bool, error)
}

WriteChecker answers v2 D4 for a human principal: write or higher on repository, from GitHub. An error is no answer, and the caller refuses.

Jump to

Keyboard shortcuts

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