ports

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 8 Imported by: 1 module, 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 ports holds the contract between the platform and the code around it: the four ports a caller implements (Storage, EventBus, Queue, Kv), the platform's own AdminStore, and every DTO that crosses those boundaries.

In the TypeScript package these types are spread over core/types.ts, core/state.ts and ports/*.ts. Go cannot have an import cycle between core and ports, so the shared types live here, in the leaf package, and core imports them. The file names still follow the TypeScript ones.

Index

Constants

This section is empty.

Variables

View Source
var MainAgent = &MessageScope{}

MainAgent scopes a message listing to the main agent's stream.

Functions

func Ptr

func Ptr[T any](v T) *T

Ptr is a small helper for building a RunPatch.

Types

type AdminStore

type AdminStore interface {
	Threads() AdminThreadStore
	Runs() RunStore
	Steps() StepStore
	// Close releases any handles. Development stores hold an open file.
	Close() error
}

AdminStore is operational history: run records and step timings (§2.9).

NOT a port a caller implements. The platform owns this data and stores it itself: SQLite in development, Postgres in production. Callers only ever read it back, through the runtime's Admin API.

It carries no StorageContext. A run's state belongs to the caller's own data (§2.10); operational history is the platform's.

type AdminThread

type AdminThread struct {
	ID          string         `json:"id"`
	State       ExecutionState `json:"state"`
	Model       string         `json:"model"`
	FirstSeenAt time.Time      `json:"firstSeenAt"`
	UpdatedAt   time.Time      `json:"updatedAt"`
	// StartedWith is the parameters that started it; nil for a thread seen
	// before this was recorded.
	StartedWith *ThreadStart `json:"startedWith,omitempty"`
}

AdminThread is the platform's view of one thread.

type AdminThreadFilter

type AdminThreadFilter struct {
	State []ExecutionState
	Since *time.Time
	// Limit defaults to 100 in the shipped stores.
	Limit int
}

AdminThreadFilter narrows an admin thread listing.

type AdminThreadStore

type AdminThreadStore interface {
	// Upsert records a thread at its current state. Called on every transition.
	Upsert(ctx context.Context, t NewAdminThread) error
	CountByState(ctx context.Context) (map[ExecutionState]int, error)
	List(ctx context.Context, f AdminThreadFilter) ([]AdminThread, error)
}

AdminThreadStore is the platform's OWN view of threads (§2.9): a copy of the few fields an operational view needs, never the caller's thread table.

type AgentConfig

type AgentConfig struct {
	// HITLTTL is how long a parked HITL request stays answerable (§2.5).
	HITLTTL time.Duration
	// ReclaimGrace is the grace beyond the HITL TTL before orphan reclamation
	// may claim a thread (§2.5).
	ReclaimGrace time.Duration
	// MaxSteps is the round-trip ceiling per run (§2.1 safety cap).
	MaxSteps int
	// RunMaxAttempts is the queue redrive attempts before a run finalizes
	// FAILED (§2.8).
	RunMaxAttempts int
	// StopPoll is how often a running worker re-reads the stop signal (§2.1).
	StopPoll time.Duration
	// RunRedriveDelay is the delay before re-dispatching a job that found the
	// run lock still held by an OLDER run (§2.8).
	RunRedriveDelay time.Duration
	// TokenBudget is the default per-run token budget (input + output). Zero
	// means unbounded apart from MaxSteps.
	TokenBudget int
	// CostBudgetMicros is the default per-run money cap (§4), in millionths
	// of the pricer's currency: 250_000 is roughly a quarter of a dollar
	// when the pricer works in USD. Zero means unbounded. Checked between
	// steps, exactly like TokenBudget, so the step that crossed the line is
	// always kept in full.
	CostBudgetMicros int64
	// SubagentMaxDepth caps nesting (§2.7).
	SubagentMaxDepth int
	// SubagentMaxConcurrent caps concurrent subagents per run (§2.7).
	SubagentMaxConcurrent int
	// SubagentMaxSteps is the step ceiling per subagent run (§2.7).
	SubagentMaxSteps int
	// SubagentResultCapChars caps a subagent result handed to the parent.
	SubagentResultCapChars int
	// RecordPayloads records prompts, state, step text and tool payloads into
	// the operational store (§2.9). Turn it off when those carry anything
	// that should not sit in an operational database.
	RecordPayloads bool
	// PayloadCapChars caps each recorded value.
	PayloadCapChars int
	// ContextCeilingTokens is the universal context ceiling (§2.6).
	ContextCeilingTokens int
	// ContextOutputReserveTokens are reserved for the completion when compacting.
	ContextOutputReserveTokens int
	// CompactionTrigger: compact when the history estimate exceeds this share
	// of the budget (§2.6).
	CompactionTrigger float64
	// ContextTailShare is the share of the budget kept verbatim as the tail.
	ContextTailShare float64
	// CompactionModel is the registry key of the cheap model used to write
	// the context summary (§2.6).
	CompactionModel string
	// PromptCaching stamps cache breakpoints on the stable prompt prefix
	// (§2.6). Providers without prompt caching ignore the stamp.
	PromptCaching bool
	// NativeWindows are per-model native windows below the ceiling (§2.6).
	// A ContextWindow declared via ResolveModel wins over this table.
	NativeWindows map[string]int
	// RunLockLease is the lease for the per-thread run lock. Must exceed the
	// longest possible run segment (§2.8, §3.4).
	RunLockLease time.Duration
	// BillingPreCheck rejects a run before it starts (§4). Nil means no
	// check. The check can publish on the thread, so the refusal is visible
	// to every client: the platform also publishes RUN_REFUSED with the error.
	BillingPreCheck func(ctx context.Context, check BillingCheck) error
	// ProviderOptions are applied to EVERY run (§3.1). An agent spec
	// overrides this, and a run input overrides both, per provider namespace.
	ProviderOptions ProviderOptions
}

AgentConfig tunes the platform. Build one with DefaultConfig and change what you need.

func DefaultConfig

func DefaultConfig() AgentConfig

DefaultConfig returns the defaults the TypeScript package ships with.

func ResolveConfig

func ResolveConfig(partial *AgentConfig) (AgentConfig, error)

ResolveConfig validates a config. A nil config means the defaults.

type AgentEvent

type AgentEvent struct {
	ThreadID  string          `json:"threadId"`
	Seq       int64           `json:"seq"`
	Type      string          `json:"type"`
	Payload   json.RawMessage `json:"payload"`
	CreatedAt time.Time       `json:"createdAt"`
}

AgentEvent is an append-only event log entry: the replay source for SSE (re)connects and the durable record of INPUT_REQUIRED (HITL) requests. Seq is assigned by the engine via Kv.Incr before append (§3.4). Seq 0 marks a bus-only notice that is never persisted.

func (AgentEvent) PayloadInto

func (e AgentEvent) PayloadInto(v any) error

PayloadInto decodes the event payload into v.

type AgentKind

type AgentKind string

AgentKind is the generation flavor of a handle / spawned subagent (§4).

const (
	KindStreamText   AgentKind = "stream-text"
	KindGenerateText AgentKind = "generate-text"
)

type AgentRunState

type AgentRunState map[string]any

AgentRunState is whatever a caller needs carried through a run: tenant, user, request id, feature flags (§2.10). The platform never reads it; it only guarantees that everything acting on behalf of a run can see it.

In TypeScript this is an augmentable interface. In Go it is a map; read your own keys back with a small helper of your own.

type Attachment

type Attachment struct {
	URL       string `json:"url"`
	MediaType string `json:"mediaType,omitempty"`
}

Attachment is one image on a user turn: a URL the provider can fetch, or a data: URL.

type BillingCheck

type BillingCheck struct {
	ThreadID string
	State    AgentRunState
	// PublishEvent publishes a durable event on the thread; Notice for a
	// bus-only one.
	PublishEvent func(ctx context.Context, typ string, payload any, notice bool) (AgentEvent, error)
}

BillingCheck is what BillingPreCheck receives: the thread about to run, the run's state (§2.10), and a way to publish on the thread (a credit warning, a reset date) before the refusal reaches the caller.

type BoundEvents

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

BoundEvents is EventStore with the StorageContext bound.

func (BoundEvents) Append

func (b BoundEvents) Append(ctx context.Context, threadID string, e AgentEvent) error

func (BoundEvents) Latest

func (b BoundEvents) Latest(ctx context.Context, threadID, typ string) (*AgentEvent, error)

func (BoundEvents) ListByType

func (b BoundEvents) ListByType(ctx context.Context, threadID, typ string) ([]AgentEvent, error)

func (BoundEvents) ListSince

func (b BoundEvents) ListSince(ctx context.Context, threadID string, sinceSeq int64) ([]AgentEvent, error)

type BoundMessages

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

BoundMessages is MessageStore with the StorageContext bound.

func (BoundMessages) Append

func (b BoundMessages) Append(ctx context.Context, threadID string, m NewMessage) (*MessageDTO, error)

func (BoundMessages) DeleteFrom

func (b BoundMessages) DeleteFrom(ctx context.Context, threadID, messageID string) (int, error)

func (BoundMessages) List

func (b BoundMessages) List(ctx context.Context, threadID string, scope *MessageScope) ([]MessageDTO, error)

type BoundStorage

type BoundStorage struct {
	Threads  BoundThreads
	Messages BoundMessages
	Events   BoundEvents
	Usage    BoundUsage
	// Ctx is the context every call carries.
	Ctx StorageContext
}

BoundStorage is the Storage shape core works against: the caller's implementation with this run's context already attached. Core keeps calling `Messages.Append(ctx, threadID, msg)` and the implementation still receives the state (§2.10).

func BindStorage

func BindStorage(storage Storage, sc StorageContext) BoundStorage

BindStorage attaches a run's context to every storage method once.

type BoundThreads

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

BoundThreads is ThreadStore with the StorageContext bound.

func (BoundThreads) ClaimState

func (b BoundThreads) ClaimState(ctx context.Context, threadID string, from, to ExecutionState) (bool, error)

func (BoundThreads) Create

func (b BoundThreads) Create(ctx context.Context, init ThreadInit) (*ThreadDTO, error)

func (BoundThreads) Delete

func (b BoundThreads) Delete(ctx context.Context, threadID string) error

func (BoundThreads) Get

func (b BoundThreads) Get(ctx context.Context, threadID string) (*ThreadDTO, error)

func (BoundThreads) List

func (b BoundThreads) List(ctx context.Context) ([]ThreadDTO, error)

func (BoundThreads) SetState

func (b BoundThreads) SetState(ctx context.Context, threadID string, state ExecutionState) error

type BoundUsage

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

BoundUsage is UsageStore with the StorageContext bound.

func (BoundUsage) Record

func (b BoundUsage) Record(ctx context.Context, threadID string, u NewUsage) error

func (BoundUsage) Total

func (b BoundUsage) Total(ctx context.Context, threadID string, filter UsageFilter) (UsageTotals, error)

Total sums the thread's calls. Pass UsageFilter{RunID: id} for one run.

type ContextUsage

type ContextUsage struct {
	UsedTokens      int `json:"usedTokens"`
	BudgetTokens    int `json:"budgetTokens"`
	CompactAtTokens int `json:"compactAtTokens"`
	Messages        int `json:"messages"`
}

ContextUsage is how full the next run's prompt would be (§2.6). Token counts are the same rough estimate the engine itself compacts on.

type Cost

type Cost struct {
	// Micros is millionths of one Currency unit: 1_000_000 is one dollar
	// when Currency is "USD". Integers, because money summed as float64
	// drifts.
	Micros int64 `json:"micros"`
	// Currency is an ISO-4217 code, "USD" for the shipped table pricer.
	Currency string `json:"currency"`
	// Source is where the number came from: "receipt" when the provider
	// computed it, "table" from a price list, "estimate" for anything a
	// pricer worked out itself. It rides along so a bill can be audited.
	Source string `json:"source"`
}

Cost is the money one model call cost.

type DeleteThreadResult

type DeleteThreadResult struct {
	Accepted bool   `json:"accepted"`
	Error    string `json:"error,omitempty"`
}

DeleteThreadResult is what DeleteThread answers.

type EnqueueOptions

type EnqueueOptions struct {
	// Delay holds the job before delivering it: the HITL expiry (§2.5) and a
	// job blocked by an older run's lock (§2.8).
	//
	// An adapter that cannot delay may deliver immediately (both callers
	// treat an early arrival as a no-op) but it must NOT fail, or a park
	// would fail the run that scheduled it.
	Delay time.Duration
}

EnqueueOptions tunes one dispatch.

type EventBus

type EventBus interface {
	Publish(ctx context.Context, threadID string, event AgentEvent) error
	// Subscribe returns an unsubscribe function. The handler may be called
	// from any goroutine. The reference adapters run the §2.5 heartbeat while
	// any subscriber is attached.
	Subscribe(ctx context.Context, threadID string, handler func(AgentEvent)) (func() error, error)
}

EventBus is the pub/sub port: live fan-out + death notices (§2.2, §2.5).

Delivery is at-most-once. The §2.5 death-notice/heartbeat/watchdog pattern exists precisely because pub/sub drops. Stronger buses may simplify the heartbeat but reclamation stays (§3.4).

type EventStore

type EventStore interface {
	Append(ctx context.Context, threadID string, e AgentEvent, sc StorageContext) error
	// ListSince returns all events after the cursor, ascending by seq (§2.2).
	ListSince(ctx context.Context, threadID string, sinceSeq int64, sc StorageContext) ([]AgentEvent, error)
	// Latest returns the most recent event of a type, or nil, nil.
	Latest(ctx context.Context, threadID, typ string, sc StorageContext) (*AgentEvent, error)
	// ListByType returns every event of a type, ascending by seq.
	ListByType(ctx context.Context, threadID, typ string, sc StorageContext) ([]AgentEvent, error)
}

EventStore is the events section of Storage.

type ExecutionState

type ExecutionState string

ExecutionState is the lifecycle of a thread. Durable truth lives in Storage.Threads; the kv copy (`agent:state:{threadId}`) is a hot cache the engine polls (§2.1, §3.4).

const (
	StateIdle            ExecutionState = "IDLE"
	StateRunning         ExecutionState = "RUNNING"
	StateWaitingForInput ExecutionState = "WAITING_FOR_INPUT"
	StateCancelled       ExecutionState = "CANCELLED"
	StateCompleted       ExecutionState = "COMPLETED"
	StateFailed          ExecutionState = "FAILED"
)

type GenerateTextAgentSpec

type GenerateTextAgentSpec struct {
	Name             string
	Model            string
	Subagents        *SubagentsConfig
	TokenBudget      int
	CostBudgetMicros int64
	ProviderOptions  ProviderOptions
	System           string
	SystemFn         SystemFunc
	PrepareStep      PrepareStepFunc
	Tools            []Tool
	Options          []goai.Option
	OnSettle         SettleFunc
	OnFinish         func(info RunFinishInfo)
}

GenerateTextAgentSpec describes a generate-text agent (§3.1).

type Kv

type Kv interface {
	// Get returns the value and true, or "" and false when the key is missing.
	Get(ctx context.Context, key string) (string, bool, error)
	// Set returns true iff the value was written. With OnlyIfNotExists it
	// returns false when the key already existed.
	Set(ctx context.Context, key, value string, opts SetOptions) (bool, error)
	Del(ctx context.Context, key string) error
	Incr(ctx context.Context, key string) (int64, error)
}

Kv is the hot key-value port: thread state cache, HITL handoff keys, seq & attempt counters, per-thread run locks (§3.2). Backed by Redis in the reference adapters; any KV works.

type MessageDTO

type MessageDTO struct {
	ID       string `json:"id"`
	ThreadID string `json:"threadId"`
	// AgentID is the producing agent; empty = the main agent (§2.7).
	AgentID   string          `json:"agentId"`
	Role      MessageRole     `json:"role"`
	Content   json.RawMessage `json:"content"`
	CreatedAt time.Time       `json:"createdAt"`
}

MessageDTO is one persisted turn.

Content is the message body as JSON, in the same shapes the TypeScript package stores (see core/messages.go): a JSON string for plain text, an array of parts for assistant and tool turns, or a CONTEXT_SUMMARY envelope (§2.6). Keeping the shape identical means a Go worker and a TypeScript worker can share one database.

func (MessageDTO) MarshalJSON

func (m MessageDTO) MarshalJSON() ([]byte, error)

MarshalJSON writes an empty AgentID as null, which is what the TypeScript package (and the React client) use for the main agent.

func (*MessageDTO) UnmarshalJSON

func (m *MessageDTO) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both null and a string for agentId.

type MessageRole

type MessageRole string

MessageRole is who produced a message.

const (
	RoleUser      MessageRole = "user"
	RoleAssistant MessageRole = "assistant"
	RoleSystem    MessageRole = "system"
	RoleTool      MessageRole = "tool"
)

type MessageScope

type MessageScope struct {
	AgentID string
}

MessageScope decides WHOSE turns List returns (§2.7):

  • nil: every row on the thread, for UI hydration (§2.2)
  • MainAgent (AgentID ""): the main agent's stream. Compaction (§2.6) and the edit lookup (§5.1) must use this.
  • AgentScope("sub_1"): that nested run's own stream.

func AgentScope

func AgentScope(agentID string) *MessageScope

AgentScope scopes a message listing to one nested run's stream.

type MessageStore

type MessageStore interface {
	Append(ctx context.Context, threadID string, m NewMessage, sc StorageContext) (*MessageDTO, error)
	// List returns turns oldest first, filtered by scope (see MessageScope).
	List(ctx context.Context, threadID string, scope *MessageScope, sc StorageContext) ([]MessageDTO, error)
	// DeleteFrom deletes messageID and every message after it, in the same
	// order List returns (§5.1 edit + resend). Returns how many rows went; 0
	// when the id is not in this thread.
	DeleteFrom(ctx context.Context, threadID, messageID string, sc StorageContext) (int, error)
}

MessageStore is the messages section of Storage.

type NestedDescriptor

type NestedDescriptor struct {
	AgentID string `json:"agentId"`
	Name    string `json:"name"`
	Model   string `json:"model"`
	Depth   int    `json:"depth"`
}

NestedDescriptor identifies a nested run well enough to re-enter its loop (§2.7). Persisted in the INPUT_REQUIRED payload.

type NewAdminThread

type NewAdminThread struct {
	ID          string
	State       ExecutionState
	Model       string
	StartedWith *ThreadStart
}

NewAdminThread is a thread transition to record. StartedWith is written on first sight only: a later upsert never replaces what started the thread.

type NewMessage

type NewMessage struct {
	AgentID string
	Role    MessageRole
	Content json.RawMessage
}

NewMessage is a turn about to be appended.

type NewRunRecord

type NewRunRecord struct {
	ID              string
	ThreadID        string
	Agent           string
	Model           string
	Prompt          string
	TokenBudget     *int
	RunState        AgentRunState
	ProviderOptions ProviderOptions
	// Depth defaults to 0, a dispatched run.
	Depth       int
	ParentRunID string
}

NewRunRecord opens a run record.

type NewStepRecord

type NewStepRecord = StepRecord

NewStepRecord is a step about to be recorded. A zero At means now.

type NewUsage

type NewUsage struct {
	// RunID is the DISPATCHED run this call belongs to (§2.9). A nested run's
	// calls carry their parent's run id, so one run's bill is one query.
	RunID string `json:"runId,omitempty"`
	// AgentID is whose stream made the call (§2.7): empty is the main run,
	// otherwise the nested run's id.
	AgentID string `json:"agentId,omitempty"`
	// AgentName is the registered handle for the main run, the delegation's
	// name for a nested one. What a bill line should say.
	AgentName string    `json:"agentName,omitempty"`
	Kind      UsageKind `json:"kind"`
	// Step is the 1-based iteration inside its loop; 0 for a compaction.
	Step int `json:"step"`

	// Model is the registry key the call was made with, e.g.
	// "claude-sonnet-4@high" — what a price list is usually keyed by.
	Model string `json:"model,omitempty"`
	// ModelID is the wire id the provider reported back, which can differ
	// from the key that asked for it (an alias, a dated snapshot).
	ModelID string `json:"modelId,omitempty"`

	InputTokens           int `json:"inputTokens"`
	CacheReadInputTokens  int `json:"cacheReadInputTokens"`
	CacheWriteInputTokens int `json:"cacheWriteInputTokens"`
	OutputTokens          int `json:"outputTokens"`
	// ReasoningTokens are thinking tokens. Most providers already count
	// these inside OutputTokens, so price them at zero unless yours bills
	// them separately (see the pricing package).
	ReasoningTokens int `json:"reasoningTokens"`

	Outcome UsageOutcome `json:"outcome"`
	// Estimated is true when no finish chunk arrived and the counters are the
	// platform's own estimate over what it does know: the prompt it sent and
	// the text that did stream, measured the same way compaction measures
	// context fill.
	Estimated bool `json:"estimated,omitempty"`

	// ProviderMetadata is whatever the provider attached to the finish: a
	// gateway receipt, a generation id, anything a Pricer wants to read.
	ProviderMetadata map[string]any `json:"providerMetadata,omitempty"`

	// Cost is filled by the Pricer before the row is stored. Nil means the
	// call went unpriced and any total over it is a floor.
	Cost *Cost `json:"cost,omitempty"`
}

NewUsage is ONE model call, recorded by the engine after every call: a step of the main run, a step of a nested run, a compaction pass, streamed or not, finished or cut short.

It carries everything a Pricer needs to put a price on the call, so pricing never has to reach back into the run to find out what happened.

func (NewUsage) TotalTokens

func (u NewUsage) TotalTokens() int

TotalTokens is input + cache reads + output: the counter the token budget is measured against, and the one UsageTotals carries.

Cache WRITES and reasoning tokens are deliberately outside it. Cache writes are a separate line on the provider's bill, and reasoning tokens are usually already inside OutputTokens; adding either here would move a budget that callers have already tuned.

func (NewUsage) Totals

func (u NewUsage) Totals() UsageTotals

Totals is this one call as a UsageTotals, cost included.

type PrepareStepFunc

type PrepareStepFunc func(ctx context.Context, threadID string, state AgentRunState, messages []provider.Message) ([]provider.Message, error)

PrepareStepFunc edits the prompt for one step, just before it is sent (§3.1): messages is the durable history the platform assembled (compacted, repaired, cache-stamped) and the return value is what the model sees. It is the place for context that must NOT be persisted — a screenshot the model should look at once, an editor snapshot — because anything appended here is gone on the next step unless it is appended again.

type Pricer

type Pricer interface {
	// Price returns nil, nil when it cannot price this call. The row is then
	// stored unpriced, and in a Chain the next pricer gets its turn. An
	// error is logged and treated the same way: an unpriceable call must
	// never fail a run.
	Price(ctx context.Context, usage NewUsage) (*Cost, error)
}

Pricer turns one model call into money (§4). The runtime calls it after every call, before the usage row is stored, so cost is part of the row rather than something a reader has to work out later.

It runs on the run's own path: keep it fast and side-effect free. A price list lookup is the intended shape; a network call is not.

type PricerFunc

type PricerFunc func(ctx context.Context, usage NewUsage) (*Cost, error)

PricerFunc adapts a plain function into a Pricer.

func (PricerFunc) Price

func (f PricerFunc) Price(ctx context.Context, u NewUsage) (*Cost, error)

Price implements Pricer.

type ProviderOptions

type ProviderOptions map[string]any

ProviderOptions are provider-specific options passed through to the provider by goai. Namespaced per provider; the platform never inspects them.

func MergeProviderOptions

func MergeProviderOptions(base, override ProviderOptions) ProviderOptions

MergeProviderOptions is a shallow per-provider merge: override wins over base.

type Queue

type Queue interface {
	Enqueue(ctx context.Context, job RunJob, opts *EnqueueOptions) error
}

Queue is the durable dispatch port (§2.8). Delivery is at-least-once; the engine's state guard and the run lock make double dispatch a no-op.

type ResolvedModel

type ResolvedModel struct {
	Instance      func() provider.LanguageModel
	ContextWindow int
	// ModelID is the wire id this key resolves to, e.g.
	// "claude-sonnet-4-20250514" for the key "claude-sonnet-4@high". It goes
	// onto every usage row, so a price list keyed by wire ids can match one
	// (§4). Empty means the key IS the id.
	ModelID string
}

ResolvedModel is a model identity after resolution: the real provider instance (created lazily per run) and the declared context window, which feeds the §2.6 compaction budget math.

func (ResolvedModel) WireID

func (m ResolvedModel) WireID(key string) string

WireID is the model id to record for a registry key: what ResolveModel declared, or the key itself when it declared nothing.

type RespondInput

type RespondInput struct {
	ThreadID   string
	ToolCallID string
	Approved   bool
	Payload    any
	// State is for the storage calls answering makes (§2.10). The RESUMED
	// run rebuilds its own state from the park's ticket.
	State AgentRunState
}

RespondInput answers a parked approval (§2.5).

type RespondResult

type RespondResult struct {
	Delivered bool   `json:"delivered"`
	Error     string `json:"error,omitempty"`
}

RespondResult is what Respond answers.

type ResumeInfo

type ResumeInfo struct {
	Agent            string          `json:"agent"`
	Model            string          `json:"model"`
	RunID            string          `json:"runId,omitempty"`
	TokenBudget      int             `json:"tokenBudget,omitempty"`
	CostBudgetMicros int64           `json:"costBudgetMicros,omitempty"`
	ProviderOptions  ProviderOptions `json:"providerOptions,omitempty"`
	State            AgentRunState   `json:"state,omitempty"`
	MaxSteps         int             `json:"maxSteps,omitempty"`
}

ResumeInfo is everything needed to resume a parked HITL run segment (§2.5). Persisted inside the INPUT_REQUIRED event payload.

type RunFilter

type RunFilter struct {
	// State: any of these; empty means all.
	State    []ExecutionState
	Agent    string
	ThreadID string
	Since    *time.Time
	Until    *time.Time
	// Limit: newest first. Implementations cap this; core passes a bounded value.
	Limit int
}

RunFilter narrows a run listing.

type RunFinishInfo

type RunFinishInfo struct {
	ThreadID   string
	RunID      string
	State      ExecutionState
	StopReason string
	TokensUsed int
	// Attribution is what THIS segment spent. A run that parked and resumed
	// finishes once, so this is the last segment, not the whole run.
	Attribution UsageTotals
	Steps       int
	// Cancelled is a user stop (§2.1).
	Cancelled bool
	// Error is why the run failed, when it did.
	Error string
	// Usage is the whole run's tokens AND money: every segment and every
	// nested run, read back with Total(threadID, UsageFilter{RunID: runID}).
	// Its Lines are the bill, one per agent and model, so a settle hook
	// charges in one pass without keeping its own tally (§4). Zero-valued
	// when the storage read failed; Unpriced above zero means some calls went
	// unpriced and CostMicros is a floor.
	Usage UsageTotals
	// UsageErr is set when the platform could not read the run's rows back.
	// Usage is then zero-valued, and a hook that bills from it should refuse
	// to settle rather than charge nothing: return the error from OnSettle
	// and the run fails instead of going free.
	UsageErr error
}

RunFinishInfo is handed to a spec's OnFinish after the platform finalized the run.

type RunInput

type RunInput struct {
	// ThreadID is empty to create a fresh thread first (§3.2).
	ThreadID string
	Prompt   string
	// State is carried through this whole run (§2.10): every storage call,
	// every tool, every nested run. Persisted on the dispatch.
	State AgentRunState
	// EditMessageID: edit + resend (§5.1). Replace this user message with
	// Prompt and drop every message after it, then answer again.
	EditMessageID string
	// Model overrides the spec default; resolved via ResolveModel.
	Model string
	// TokenBudget overrides the spec / config default (§2.1 safety cap).
	TokenBudget int
	// CostBudgetMicros overrides the spec / config money cap (§4), in
	// millionths of the pricer's currency: 250_000 stops the run after
	// roughly $0.25. Needs a Pricer; without one nothing is ever priced and
	// the cap can never be reached.
	CostBudgetMicros int64
	// ProviderOptions merge over the spec default, per provider namespace.
	ProviderOptions ProviderOptions
	// RunID lets the caller name the run (§2.1). Empty mints one. A caller
	// that keys its own records (a workspace, a billing line) by run id can
	// open them before dispatch and know the worker will see the same id.
	// Reusing an id is refused, not silently re-run.
	RunID string
	// MaxSteps caps this run's round trips below the config's MaxSteps. Zero
	// keeps the config value; a larger value is clamped to it.
	MaxSteps int
	// Attachments are images the user sent with the prompt. They are stored
	// as image parts on the user message and reach the model natively.
	Attachments []Attachment
}

RunInput starts a run.

type RunJob

type RunJob struct {
	ThreadID string `json:"threadId"`
	Model    string `json:"model"`
	Agent    string `json:"agent,omitempty"`
	// RunID identifies THIS dispatch (§2.1). A thread has one live run at a
	// time and `agent:run:{threadId}` holds its id; a job whose id no longer
	// matches has been replaced and must not execute.
	RunID string `json:"runId,omitempty"`
	// EnqueuedAt is epoch milliseconds at enqueue (§2.9).
	EnqueuedAt int64 `json:"enqueuedAt,omitempty"`
	// State is the run's state (§2.10), so a worker rehydrates exactly what
	// the caller attached.
	State       AgentRunState `json:"state,omitempty"`
	TokenBudget int           `json:"tokenBudget,omitempty"`
	// CostBudgetMicros is the money cap for this run (§4), carried so the
	// worker enforces the same cap the caller asked for.
	CostBudgetMicros int64           `json:"costBudgetMicros,omitempty"`
	ProviderOptions  ProviderOptions `json:"providerOptions,omitempty"`
	// MaxSteps is the run's own step cap, when the caller set one (§2.1).
	MaxSteps int `json:"maxSteps,omitempty"`
}

RunJob is the dispatch ticket for the queue (§2.8). At-least-once; consumers must be idempotent. Agent resolves via AgentCore.GetAgent; when missing, the default handle executes. The JSON field names match the TypeScript package so a queue can carry jobs for either.

type RunPatch

type RunPatch struct {
	State             *ExecutionState
	StopReason        *string
	Error             *string
	EndedAt           *time.Time
	DurationMs        *int64
	QueuedMs          *int64
	Steps             *int
	InputTokens       *int
	CachedInputTokens *int
	OutputTokens      *int
	TotalTokens       *int
	Attempts          *int
	Result            json.RawMessage
}

RunPatch is a partial update of a run record. A nil field is left alone.

type RunRecord

type RunRecord struct {
	// ID is the run id (§2.1) for a dispatched run; the nested run's id
	// otherwise, which is also the AgentID its messages and events carry.
	ID       string `json:"id"`
	ThreadID string `json:"threadId"`
	// ParentRunID is the run that spawned this one; empty for a dispatched run.
	ParentRunID string `json:"parentRunId,omitempty"`
	// Depth is 0 for the main agent, 1+ for nested.
	Depth int `json:"depth"`
	// Agent is the registered handle for a dispatched run; the delegation's
	// name for a nested one.
	Agent string         `json:"agent"`
	Model string         `json:"model"`
	State ExecutionState `json:"state"`
	// StopReason is 'completed' | 'cancelled' | 'token_budget' | 'max_steps',
	// set at finalize.
	StopReason string `json:"stopReason,omitempty"`
	// Error is why it failed, when it did.
	Error     string     `json:"error,omitempty"`
	StartedAt time.Time  `json:"startedAt"`
	EndedAt   *time.Time `json:"endedAt,omitempty"`
	// DurationMs is EndedAt - StartedAt, kept so a listing never recomputes
	// it. A parked run legitimately spans however long the human took (§2.5).
	DurationMs *int64 `json:"durationMs,omitempty"`
	// QueuedMs is the time between enqueue and a worker starting work (§2.8).
	QueuedMs *int64 `json:"queuedMs,omitempty"`
	// Steps is loop iterations completed, summed across every segment.
	Steps             int `json:"steps"`
	InputTokens       int `json:"inputTokens"`
	CachedInputTokens int `json:"cachedInputTokens"`
	OutputTokens      int `json:"outputTokens"`
	TotalTokens       int `json:"totalTokens"`
	// Attempts is the §2.8 redrive attempts consumed.
	Attempts int `json:"attempts"`
	// Prompt, TokenBudget and RunState are what the run was dispatched with
	// (§2.9). Present only when RecordPayloads is on. A nested run's prompt
	// is its brief.
	Prompt      string        `json:"prompt,omitempty"`
	TokenBudget *int          `json:"tokenBudget,omitempty"`
	RunState    AgentRunState `json:"runState,omitempty"`
	// ProviderOptions the run was dispatched with (§3.1), merged across
	// config, spec and input. Present only when RecordPayloads is on.
	ProviderOptions ProviderOptions `json:"providerOptions,omitempty"`
	// Result is a nested run's capped result, handed back to its parent (§2.7).
	Result json.RawMessage `json:"result,omitempty"`
}

RunRecord is the durable record of ONE agent run (§2.9): when it started, how it ended, what it cost. Keyed by the run id the platform already mints to fence stale workers (§2.1). A thread accumulates many of these over its life; Thread.State only ever describes the latest one.

type RunResult

type RunResult struct {
	Accepted bool           `json:"accepted"`
	ThreadID string         `json:"threadId"`
	RunID    string         `json:"runId,omitempty"`
	State    ExecutionState `json:"state,omitempty"`
	Error    string         `json:"error,omitempty"`
}

RunResult is what Run answers. Accepted false carries a reason in Error.

type RunStore

type RunStore interface {
	Start(ctx context.Context, r NewRunRecord) (*RunRecord, error)
	Patch(ctx context.Context, runID string, p RunPatch) error
	// Get returns nil, nil when the run is unknown.
	Get(ctx context.Context, runID string) (*RunRecord, error)
	// ListByThread returns every run on a thread, newest first, nested runs
	// included.
	ListByThread(ctx context.Context, threadID string) ([]RunRecord, error)
	List(ctx context.Context, f RunFilter) ([]RunRecord, error)
	CountByState(ctx context.Context) (map[ExecutionState]int, error)
}

RunStore holds run records.

type RuntimeOptions

type RuntimeOptions struct {
	Storage Storage
	// Admin is where operational history goes (§2.9). Nil picks one from the
	// environment: Postgres when AGENTIC_KIT_ADMIN_DATABASE_URL is set, SQLite
	// on disk otherwise (both need a database/sql driver registered).
	Admin AdminStore
	Bus   EventBus
	Queue Queue
	Kv    Kv
	// ResolveModel turns a registry key into a provider instance and a
	// context window.
	ResolveModel func(modelName string) (ResolvedModel, error)
	// Pricer prices every model call (§4). Nil records tokens only, and
	// every UsageTotals comes back with Unpriced above zero. See the
	// pricing package for the three that ship: a price table, a provider
	// receipt reader, and a chain of both.
	Pricer Pricer
	// Log is where the platform reports what it could not do without
	// failing the run. Nil uses slog.Default().
	Log *slog.Logger
	// Config is nil for the defaults.
	Config *AgentConfig
}

RuntimeOptions is what SetupAgentCore takes.

type RuntimePorts

type RuntimePorts struct {
	Storage BoundStorage
	Admin   AdminStore
	Bus     EventBus
	Queue   Queue
	Kv      Kv
	// ResolveModel is user-provided model resolution (§3.3): models can live
	// in any shape on the consumer side; the platform only sees ResolvedModel.
	ResolveModel func(modelName string) (ResolvedModel, error)
	// Pricer puts a price on every model call before its usage row is
	// stored (§4). Nil stores every row unpriced.
	Pricer Pricer
	// Log is where the platform reports what it could not do without
	// failing the run, such as a usage row it failed to store.
	Log    *slog.Logger
	Config AgentConfig
}

RuntimePorts is the ports bundle: everything in core receives this and nothing else.

Storage is the caller's implementation with THIS run's context already bound (§2.10). Admin is the platform's own operational store (§2.9).

type SetOptions

type SetOptions struct {
	// Expiry is the key's TTL; zero means no expiry.
	Expiry time.Duration
	// OnlyIfNotExists is SET NX: the atomic primitive behind the per-thread
	// run lock (§3.4).
	OnlyIfNotExists bool
}

SetOptions tunes Kv.Set.

type SettleFunc

type SettleFunc func(ctx context.Context, info RunFinishInfo) error

SettleFunc runs after a run's last step and BEFORE its terminal STATE_CHANGE is written (§5.6): the place to commit what the run produced so every client sees it settled the moment the state flips. An error fails the run. A user stop reaches it with a cancelled ctx and Cancelled set; storage work in the hook should use context.WithoutCancel.

It may run more than once for one run: a worker that dies inside it is redelivered. Keep it idempotent on RunID.

type StepRecord

type StepRecord struct {
	RunID string `json:"runId"`
	// ThreadID is denormalised so a thread's whole timeline is one query.
	ThreadID string `json:"threadId"`
	// AgentID is which stream ran it; empty is the main agent (§2.7).
	AgentID           string `json:"agentId"`
	Index             int    `json:"index"`
	DurationMs        int64  `json:"durationMs"`
	FinishReason      string `json:"finishReason"`
	InputTokens       int    `json:"inputTokens"`
	CachedInputTokens int    `json:"cachedInputTokens"`
	OutputTokens      int    `json:"outputTokens"`
	TotalTokens       int    `json:"totalTokens"`
	// Tools the step executed, by name.
	Tools []string `json:"tools"`
	// Text is what the step said, capped. Only with RecordPayloads.
	Text string `json:"text,omitempty"`
	// ToolCalls are the tools it ran, with arguments and results, each capped.
	// Note: tool arguments and results are operational data now. If yours
	// carry anything you would not want there, set RecordPayloads false.
	ToolCalls []StepToolCall `json:"toolCalls,omitempty"`
	At        time.Time      `json:"at"`
}

StepRecord is one completed loop iteration (§2.9).

type StepStore

type StepStore interface {
	Record(ctx context.Context, s NewStepRecord) error
	// ListByRun returns a run's steps in order.
	ListByRun(ctx context.Context, runID string) ([]StepRecord, error)
	// ListByThread returns every step on a thread, oldest first.
	ListByThread(ctx context.Context, threadID string) ([]StepRecord, error)
}

StepStore holds one row per completed loop iteration.

type StepToolCall

type StepToolCall struct {
	ToolName string          `json:"toolName"`
	Args     json.RawMessage `json:"args"`
	Result   json.RawMessage `json:"result"`
}

StepToolCall is one tool a step ran, with capped arguments and result.

type StopResult

type StopResult struct {
	Accepted bool   `json:"accepted"`
	Error    string `json:"error,omitempty"`
}

StopResult is what Stop answers.

type Storage

type Storage interface {
	Threads() ThreadStore
	Messages() MessageStore
	Events() EventStore
	Usage() UsageStore
}

Storage is the persistence port for a caller's OWN data (§3.2): threads, messages, events, usage. DTOs cross the boundary; ORM types never leak into core. Implement it once for Postgres, MongoDB, DynamoDB, or use a shipped adapter.

Operational history (run records, timings, step markers) is NOT here. The platform owns and stores that itself (§2.9); callers only read it back through the runtime's Admin API.

Every method receives the run's StorageContext as its last argument, so an implementation can scope a query to a tenant, stamp a row with who caused it, or route to a different database entirely (§2.10).

type StorageContext

type StorageContext struct {
	State AgentRunState
	// RunID is the run this call serves. Empty for reads outside a run.
	RunID string
}

StorageContext is passed to every domain storage call so an implementation can scope a query, stamp a row, or route to a tenant's database (§2.10).

type StreamTextAgentSpec

type StreamTextAgentSpec struct {
	// Name is the unique handle key and the queue dispatch key (§5).
	Name string
	// Model is the registry key for this agent's model.
	Model string
	// Subagents opts in to delegation (§2.7). Nil is off; an empty config
	// takes the defaults.
	Subagents *SubagentsConfig
	// TokenBudget is the default per-run budget (input + output). Zero is
	// unbounded apart from MaxSteps.
	TokenBudget int
	// CostBudgetMicros is the default per-run money cap (§4), in millionths
	// of the pricer's currency. Zero is unbounded. Needs a Pricer: an
	// unpriced call spends no money and so can never exhaust it.
	CostBudgetMicros int64
	// ProviderOptions are this agent's defaults; the run input wins.
	ProviderOptions ProviderOptions
	// System is the static persona.
	System string
	// SystemFn builds the persona per step, with the run's state (§3.1). It
	// wins over System when set.
	SystemFn SystemFunc
	// PrepareStep edits the prompt per step, for ephemeral context. See
	// PrepareStepFunc.
	PrepareStep PrepareStepFunc
	Tools       []Tool
	// Options are extra goai options (temperature, hooks, retries, ...).
	// Platform-owned options are applied after these and win.
	Options []goai.Option
	// OnChunk fires per stream chunk, after the platform persisted it.
	OnChunk func(chunk provider.StreamChunk)
	// OnSettle runs after the last step and before the terminal state is
	// written; an error fails the run. See SettleFunc.
	OnSettle SettleFunc
	// OnFinish fires once, after the platform finalized the run.
	OnFinish func(info RunFinishInfo)
}

StreamTextAgentSpec describes a stream-text agent (§3.1). The platform owns the model, messages, prompt, MaxSteps and stop handling; everything else about generation is yours.

type SubagentProfile

type SubagentProfile struct {
	// Description is shown to the model beside the name, so it can choose.
	Description string
	// System is the child's static persona; SystemFn wins when set.
	System   string
	SystemFn SystemFunc
	// PrepareStep edits the child's prompt per step; see PrepareStepFunc.
	PrepareStep PrepareStepFunc
	// Model is the registry key; empty falls back to the config's Model,
	// then the parent's.
	Model string
	// Tools are the child's own set, HITL-wrapped like the parent's. They
	// replace the shared Tools above.
	Tools []Tool
	// MaxSteps caps the child's round trips; zero keeps SubagentMaxSteps.
	MaxSteps int
}

SubagentProfile is one named specialist a run may delegate to.

type SubagentsConfig

type SubagentsConfig struct {
	// Kind is the generation flavor for spawned subagents. Default: stream-text.
	Kind AgentKind
	// Model is the registry key used when a delegation call omits one.
	Model string
	// Tools are merged into every spawned subagent's toolset (HITL-wrapped
	// identically to the parent's tools).
	Tools []Tool
	// Profiles are named specialists (§2.7). When set, spawnSubagent must
	// name one of them: the child takes the profile's persona, model, tools
	// and step cap instead of the shared defaults above. The model still
	// writes the brief; the profile says who reads it.
	Profiles map[string]SubagentProfile
}

SubagentsConfig is the opt-in subagent delegation config (§2.7): the platform constructs the run-scoped spawnSubagent tool itself.

type SystemFunc

type SystemFunc func(ctx context.Context, threadID string, state AgentRunState) (string, error)

SystemFunc builds the system prompt for one step, with the run's state in hand (§3.1). Called once per step, so a prompt can read the project it is acting on. Keep the stable part first: a cached prefix is only a prefix while it does not move.

type ThreadDTO

type ThreadDTO struct {
	ID        string         `json:"id"`
	State     ExecutionState `json:"state"`
	Model     string         `json:"model"`
	CreatedAt time.Time      `json:"createdAt"`
	UpdatedAt time.Time      `json:"updatedAt"`
}

ThreadDTO is one conversation thread.

type ThreadInit

type ThreadInit struct {
	// Model defaults to "gpt-4o" when empty.
	Model string
}

ThreadInit is what a new thread starts with.

type ThreadSnapshot

type ThreadSnapshot struct {
	Thread   ThreadDTO    `json:"thread"`
	Messages []MessageDTO `json:"messages"`
	// Runs are the runs on this thread (§2.7), so a reconnecting client
	// rebuilds its subagent panel.
	Runs []RunRecord `json:"runs"`
	// LastEventSeq is the cursor for starting live replay.
	LastEventSeq int64 `json:"lastEventSeq"`
	// ActiveEvents are only the unfinished run's events.
	ActiveEvents []AgentEvent `json:"activeEvents"`
}

ThreadSnapshot is the durable state used to hydrate a client before it starts live event replay.

type ThreadStart

type ThreadStart struct {
	RunID           string          `json:"runId"`
	Agent           string          `json:"agent"`
	Model           string          `json:"model"`
	At              time.Time       `json:"at"`
	Prompt          string          `json:"prompt,omitempty"`
	TokenBudget     *int            `json:"tokenBudget,omitempty"`
	State           AgentRunState   `json:"state,omitempty"`
	ProviderOptions ProviderOptions `json:"providerOptions,omitempty"`
}

ThreadStart is what started a thread (§2.9): the first dispatched run's parameters, recorded once and never overwritten, so a listing can say who asked for what without opening the thread. Prompt, State and ProviderOptions are present only when RecordPayloads is on.

type ThreadStore

type ThreadStore interface {
	// Get returns nil, nil when the thread does not exist.
	Get(ctx context.Context, threadID string, sc StorageContext) (*ThreadDTO, error)
	Create(ctx context.Context, init ThreadInit, sc StorageContext) (*ThreadDTO, error)
	// List returns threads most recent first.
	List(ctx context.Context, sc StorageContext) ([]ThreadDTO, error)
	SetState(ctx context.Context, threadID string, state ExecutionState, sc StorageContext) error
	// Delete removes the thread AND everything that follows it: messages,
	// events, usage rows. Returns an error if the thread does not exist.
	Delete(ctx context.Context, threadID string, sc StorageContext) error
	// ClaimState is a compare-and-set: true iff THIS caller performed the
	// transition. Must be atomic: a single conditional UPDATE or equivalent
	// (§2.5, §2.8).
	ClaimState(ctx context.Context, threadID string, from, to ExecutionState, sc StorageContext) (bool, error)
}

ThreadStore is the threads section of Storage.

type ThreadUsage

type ThreadUsage struct {
	Tokens  UsageTotals  `json:"tokens"`
	Context ContextUsage `json:"context"`
	Model   string       `json:"model"`
}

ThreadUsage is what a thread has spent and how full its context is.

type Tool

type Tool struct {
	goai.Tool
	RequiresConfirmation bool
}

Tool is a goai tool plus the platform's own flags. RequiresConfirmation marks a destructive tool: the engine parks it behind an approval (§2.5) instead of executing it. Use WrapTool for a plain goai tool.

func WrapTool

func WrapTool(t goai.Tool) Tool

WrapTool lifts a plain goai tool into the platform's Tool.

func WrapTools

func WrapTools(ts ...goai.Tool) []Tool

WrapTools lifts several goai tools.

type UsageAggregator

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

UsageAggregator sums usage rows into the shape Total must return: the four counters, the money, and one Line per agent and model.

A storage adapter that can group in the database should do that instead. This is for the ones that cannot, and for anyone writing their own adapter: feed every matching row through Add and Totals gives back exactly what the port promises, lines in first-seen order.

func (*UsageAggregator) Add

func (a *UsageAggregator) Add(u NewUsage)

Add books one call.

func (*UsageAggregator) Totals

func (a *UsageAggregator) Totals() UsageTotals

Totals is everything added so far.

type UsageFilter

type UsageFilter struct {
	// RunID limits the read to one dispatched run, nested runs included.
	// Empty reads the whole thread.
	RunID string
}

UsageFilter narrows a usage read (§4).

type UsageKind

type UsageKind string

UsageKind says which part of the platform made the call.

const (
	// KindStep is a step of an agent loop, main run or nested (§2.1, §2.7).
	KindStep UsageKind = "step"
	// KindCompaction is the summary the platform writes to keep the prompt
	// inside the model's window (§2.6). Nobody asked for it, so it is worth
	// being able to see what it costs on its own.
	KindCompaction UsageKind = "compaction"
)

type UsageLine

type UsageLine struct {
	// AgentID is empty for the main run, the nested run's id otherwise.
	AgentID   string `json:"agentId,omitempty"`
	AgentName string `json:"agentName,omitempty"`
	// Model is the registry key; ModelID the wire id the provider reported.
	Model                 string `json:"model,omitempty"`
	ModelID               string `json:"modelId,omitempty"`
	InputTokens           int    `json:"inputTokens"`
	CacheReadInputTokens  int    `json:"cacheReadInputTokens"`
	CacheWriteInputTokens int    `json:"cacheWriteInputTokens"`
	OutputTokens          int    `json:"outputTokens"`
	ReasoningTokens       int    `json:"reasoningTokens"`
	// Calls is how many model calls this line covers.
	Calls int `json:"calls"`
	// Estimated is how many of those had estimated tokens, because they were
	// cut off before the provider reported real ones.
	Estimated  int   `json:"estimated"`
	CostMicros int64 `json:"costMicros"`
}

UsageLine is one agent's spend on one model, summed over its calls (§4). This is the bill line a credit system charges for.

type UsageLineMerger

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

UsageLineMerger rebuilds UsageTotals from grouped rows that a SQL adapter read GROUP BY agent, model AND currency. Grouping by currency is what keeps a sum honest; merging here is what keeps one agent's spend on one model a single line. Money is summed in the first currency seen; a group priced in another currency counts as unpriced instead of being added to it.

func (*UsageLineMerger) Add

func (m *UsageLineMerger) Add(l UsageLine, currency string, totalTokens, unpriced int)

Add books one grouped row: its line, the currency its cost is in, its summed total tokens and how many of its calls were unpriced.

func (*UsageLineMerger) Totals

func (m *UsageLineMerger) Totals() UsageTotals

Totals is everything added so far.

type UsageOutcome

type UsageOutcome string

UsageOutcome is how the model call that produced a usage row ended.

const (
	// UsageFinished: the call ran to its finish and the provider reported
	// the counters itself.
	UsageFinished UsageOutcome = "finished"
	// UsageAborted: a user stop cut the call mid-stream, so no finish ever
	// arrived and the tokens are estimated.
	UsageAborted UsageOutcome = "aborted"
	// UsageErrored: the provider failed mid-call. Whatever it had already
	// streamed was still billed, so the row is kept.
	UsageErrored UsageOutcome = "error"
)

type UsageStore

type UsageStore interface {
	Record(ctx context.Context, threadID string, u NewUsage, sc StorageContext) error
	// Total sums recorded calls: tokens and money (§4). An empty filter sums
	// the whole thread; UsageFilter{RunID: id} sums one dispatched run,
	// nested runs included, which is what a settle hook bills from.
	//
	// The result also carries Lines: the same spend grouped by agent and
	// model, so one call serves the thread header, the settle hook and the
	// admin reads alike. A thread with no usage rows returns zeroes.
	// Unpriced counts the calls with no cost on them, so a reader can tell
	// "nothing was spent" apart from "nothing was priced".
	Total(ctx context.Context, threadID string, filter UsageFilter, sc StorageContext) (UsageTotals, error)
}

UsageStore is the usage section of Storage: one row per model call (§4).

The platform writes a row after EVERY call it makes on a thread, priced by the runtime's Pricer before it gets here. An implementation stores the row as given; it never prices anything itself.

type UsageTotals

type UsageTotals struct {
	// InputTokens are fresh (uncached) prompt tokens.
	InputTokens int `json:"inputTokens"`
	// CachedInputTokens are prompt tokens served from the provider's cache (§2.6).
	CachedInputTokens int `json:"cachedInputTokens"`
	OutputTokens      int `json:"outputTokens"`
	// TotalTokens is input + cached + output.
	TotalTokens int `json:"totalTokens"`
	// CostMicros is the summed cost, in millionths of one Currency unit.
	// 1_000_000 is one dollar when Currency is "USD".
	CostMicros int64 `json:"costMicros"`
	// Currency is the unit CostMicros is in, empty when nothing was priced.
	// One deployment should price in ONE currency: these are summed, not
	// converted.
	Currency string `json:"currency,omitempty"`
	// Unpriced is how many calls had no cost, because no pricer answered for
	// them. Above zero, CostMicros is a floor and not the whole bill.
	Unpriced int `json:"unpriced"`
	// Lines is the same spend grouped by agent and model: one line per pair,
	// which is the shape a bill wants. Summing the lines gives the totals
	// above.
	Lines []UsageLine `json:"lines,omitempty"`
}

UsageTotals is cumulative token AND money attribution across every run on a thread (§4). Tokens are what the provider reported; the money is what the Pricer put on each row as it was stored.

func (*UsageTotals) Add

func (u *UsageTotals) Add(o UsageTotals)

Add sums another set of totals into this one. The currency is taken from whichever side has one; mixing two is a pricing misconfiguration, not something to convert here.

Jump to

Keyboard shortcuts

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