ports

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 11 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

View Source
const (
	// RefusedActiveRun: the thread already has a run.
	RefusedActiveRun = "active_run"
	// RefusedQueueFull: the queue is at its depth cap; try again shortly.
	RefusedQueueFull = "queue_full"
	// RefusedBilling: the BillingPreCheck said no.
	RefusedBilling = "billing"
)

Why a run was refused, for a host that answers differently to each.

View Source
const (
	EventRunStarted         = "RUN_STARTED"
	EventTextMessageStart   = "TEXT_MESSAGE_START"
	EventTextMessageContent = "TEXT_MESSAGE_CONTENT"
	EventTextMessageEnd     = "TEXT_MESSAGE_END"
	EventReasoningStart     = "REASONING_START"
	EventReasoningContent   = "REASONING_CONTENT"
	EventReasoningEnd       = "REASONING_END"
	EventToolCallStart      = "TOOL_CALL_START"
	EventToolCallArgs       = "TOOL_CALL_ARGS"
	EventToolCallEnd        = "TOOL_CALL_END"
	EventToolCallResult     = "TOOL_CALL_RESULT"
	EventSource             = "SOURCE"
	EventStepFinished       = "STEP_FINISHED"
	EventMessageAppended    = "MESSAGE_APPENDED"
	EventInputRequired      = "INPUT_REQUIRED"
	EventSubagentStarted    = "SUBAGENT_STARTED"
	EventSubagentEvent      = "SUBAGENT_EVENT"
	EventSubagentFinished   = "SUBAGENT_FINISHED"
	EventCustom             = "CUSTOM"
	EventRunFinished        = "RUN_FINISHED"
	EventRunError           = "RUN_ERROR"
)

Event types.

View Source
const DefaultCommandTimeout = 120 * time.Second

DefaultCommandTimeout is how long a command may run when the caller does not say.

View Source
const MaxCommandOutputBytes = 4 * 1024 * 1024

MaxCommandOutputBytes is the most output kept from one command, per stream. Past it the rest is dropped and the result says Truncated, so a command that prints without end cannot fill the app's memory.

View Source
const PriorityLow = -10

PriorityLow is the priority of the platform's own housekeeping: park expiries, reclaims and lock redrives. A user's message is never queued behind them.

View Source
const TimedOutExitCode = 124

TimedOutExitCode is the exit code of a command stopped at its time limit, as timeout(1) gives it.

View Source
const ToolUsePrefix = "tool:"

ToolUsePrefix starts the Model of a usage row, and so of its UsageLine, for one use of a paid tool service: "tool:web_search". A tool's own model calls carry the model's key instead.

Variables

View Source
var (
	// ErrQueueFull is what Enqueue returns when a depth cap is set and the
	// queue has reached it. Only a fresh dispatch is ever refused; retries,
	// redrives, resumes and expiries always go in, or a run already under way
	// would be stranded.
	ErrQueueFull = errors.New("agentenkit: queue is full")
	// ErrPayloadTooLarge is a job whose encoded payload is over the adapter's
	// cap.
	ErrPayloadTooLarge = errors.New("agentenkit: job payload too large")
	// ErrDuplicateJob is an enqueue whose Key is already waiting or running.
	ErrDuplicateJob = errors.New("agentenkit: a job with this key is already queued")
	// ErrUnsupported is an adapter's answer to an operation it cannot do,
	// such as counting on a queue with no read side.
	ErrUnsupported = errors.New("agentenkit: not supported by this adapter")
)
View Source
var (
	// ErrSandboxGone: the sandbox no longer exists. It timed out, was
	// destroyed, or its provider lost it.
	ErrSandboxGone = errors.New("sandbox is gone")
	// ErrSandboxFileNotFound: there is no file or folder at this path.
	ErrSandboxFileNotFound = errors.New("no such file or folder")
	// ErrSandboxUnsupported: the adapter cannot do this.
	ErrSandboxUnsupported = errors.New("not supported")
)
View Source
var ErrStreamClosed = errors.New("run stream is closed")

ErrStreamClosed reports an append to a stream that is already closed.

View Source
var ErrStreamGone = errors.New("run stream is gone")

ErrStreamGone reports a stream that does not exist: never opened, past its grace window, or deleted. A reader takes a fresh snapshot of the thread instead.

View Source
var MainAgent = &MessageScope{}

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

Functions

func EncodeStreamEvent added in v0.4.0

func EncodeStreamEvent(e StreamEvent) ([]byte, error)

EncodeStreamEvent is an event's JSON: "type" first, then its fields, the same bytes the TS runtime writes for it.

func IsStreamEnd added in v0.4.0

func IsStreamEnd(e StreamEvent) bool

IsStreamEnd reports whether e ends a stream.

func IsToolUse added in v0.6.0

func IsToolUse(model string) bool

IsToolUse says whether a usage row's or line's Model is one use of a paid tool service (a search, a page read, sandbox time) rather than a model call. A bill prices such a line per use, and must not look it up as a model.

func ParseStreamID added in v0.4.0

func ParseStreamID(streamID string) (runID string, segment int, ok bool)

ParseStreamID returns the run id and segment in a stream id, and false for one not made by StreamIDOf.

func Ptr

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

Ptr is a small helper for building a RunPatch.

func SandboxFileNotFound added in v0.5.0

func SandboxFileNotFound(path string) error

SandboxFileNotFound is the error for a path with nothing at it.

func SandboxGone added in v0.5.0

func SandboxGone(sandboxID, why string) error

SandboxGone is the error for a sandbox that no longer exists.

func SandboxUnsupported added in v0.5.0

func SandboxUnsupported(provider, what string) error

SandboxUnsupported is the error for what an adapter cannot do.

func StreamIDOf added in v0.4.0

func StreamIDOf(runID string, segment int) string

StreamIDOf is a run segment's stream id: "<runID>:<segment>". A park closes a segment's stream and the resume opens the next, so a closed stream never opens again.

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)
	// Get returns one thread, or nil, nil when it was never seen.
	Get(ctx context.Context, threadID string) (*AdminThread, error)
	// Delete removes a thread with its runs and steps: what a deleted
	// thread leaves behind in operational history (§3.2). An unknown thread
	// is not an error.
	Delete(ctx context.Context, threadID string) 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
	// RunRetryBackoff is the delay before the first retry of a failed run
	// (§2.8). Each further retry waits twice as long, up to
	// RunRetryBackoffMax, with a little jitter so a fleet does not retry in
	// step. Zero retries at once.
	RunRetryBackoff time.Duration
	// RunRetryBackoffMax caps the retry delay. Zero means no cap.
	RunRetryBackoffMax time.Duration
	// StepTimeout bounds one model round trip, tools included. A step past
	// it fails like any other failed step and the run takes the retry
	// policy. Zero is no bound.
	StepTimeout time.Duration
	// SegmentTimeout bounds one worker segment: from pickup to finish or
	// park. A segment past it settles the run FAILED with a reason the
	// client can show, instead of holding the worker slot. Zero is no bound.
	SegmentTimeout time.Duration
	// MaxQueueWait is the longest a job may sit in the queue and still run.
	// A job picked up later than this is settled FAILED with the reason,
	// instead of executing work nobody is waiting for. Zero is no bound.
	MaxQueueWait time.Duration
	// MaxQueueDepth refuses a new run, before anything is written, once this
	// many jobs are ready and waiting (Queue.Stats). The refusal names
	// RefusedQueueFull so a host can answer 503 with a Retry-After. Zero is
	// no bound. A queue adapter may enforce its own cap on top.
	MaxQueueDepth int
	// StreamGrace is how long a run stream is kept after its segment ends.
	// A tab that reconnects within it resumes inside the stream; one that
	// comes later gets a snapshot, which has the final text in the messages.
	StreamGrace time.Duration
	// StreamTTL is how long a stream lives if nothing ever closes it: the
	// last guard when the worker and the sweep both failed.
	StreamTTL time.Duration
	// StreamFlush is how long stream events wait to be appended together. A
	// step end, a tool result, a park and a close go out at once. Zero sends
	// every event as it comes.
	StreamFlush time.Duration
	// StreamFlushEvents appends at once when this many stream events wait.
	StreamFlushEvents int
	// 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
	// BuiltinToolResultCapChars is the most characters a built-in tool hands
	// the model in one result: a page's text, a reader's answer. Past it the
	// text is cut and the result says truncated, so one huge page cannot fill
	// the context window or the database. Default 20,000.
	BuiltinToolResultCapChars int
	// SandboxIdleTTL: a thread's sandbox ends after it has sat unused this
	// long, and the next call makes a fresh one. Default 30 minutes.
	SandboxIdleTTL time.Duration
	// SandboxMaxLifetime: a thread's sandbox ends this long after it was
	// made, however much it is used: the backstop on what one sandbox can
	// cost. Default 24 hours.
	SandboxMaxLifetime time.Duration
	// 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 (§2.8, §3.4). The
	// worker renews it every third of the lease while its segment runs, so
	// it only has to outlast a renewal gap plus a crash: an expired lock
	// means a dead worker and nothing else.
	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 merges a config over the defaults and validates it. A nil config means the defaults.

A field left at its zero value takes the default when zero can never be a working value for it (a step cap, a lease, a poll, a window): a partial config such as &AgentConfig{MaxSteps: 5} keeps every other default rather than turning them all to zero. A field where zero is a real choice (no retry backoff, no timeout, no budget) keeps what was given. The two booleans, RecordPayloads and PromptCaching, cannot tell "false" from "left out": start from DefaultConfig to keep them on.

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"`
	// RunID is the run the entry belongs to, when it belongs to one.
	RunID string `json:"runId,omitempty"`
}

AgentEvent is an event on a thread: an entry in the thread record, or a live notice. Seq is the record's order, minted by the store on insert (EventStore.Append). Seq 0 marks a notice, which is never stored.

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
	// RunID is set at pickup; empty at dispatch, where the run has no id yet.
	RunID string
	State AgentRunState
	// Stage is when the check runs. See BillingStage.
	Stage BillingStage
	// Budget is the cap the job carries. At pickup the check may lower
	// either field and the segment runs with the lowered cap; raising is
	// ignored. Nil at dispatch.
	Budget *RunBudget
	// PublishEvent publishes an event on the thread: live only, or also
	// kept in the thread record when durable.
	PublishEvent func(ctx context.Context, typ string, payload any, durable 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 BillingStage added in v0.3.0

type BillingStage string

BillingStage says when a BillingCheck runs.

const (
	// BillingAtDispatch runs inside Run, before anything is written. A
	// refusal here means the run never exists.
	BillingAtDispatch BillingStage = "dispatch"
	// BillingAtPickup runs when a worker takes the job, however long it
	// waited: a first dispatch, a retry, or a resume after an approval. A
	// refusal here fails the run. The check may also lower the run's caps
	// through Budget.
	BillingAtPickup BillingStage = "pickup"
)

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 NewThreadEvent) (AgentEvent, error)

func (BoundEvents) Latest

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

func (BoundEvents) List added in v0.4.0

func (b BoundEvents) List(ctx context.Context, threadID string, f ThreadEventFilter) ([]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)

func (BoundEvents) Pruner added in v0.4.0

func (b BoundEvents) Pruner() *BoundPruner

Pruner is the store's EventPruner with the StorageContext bound, or nil when it cannot prune.

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 BoundPruner added in v0.7.0

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

BoundPruner is EventPruner with the StorageContext bound.

func (*BoundPruner) Prune added in v0.7.0

func (b *BoundPruner) Prune(ctx context.Context, types []string, limit int, dryRun bool) (map[string]int64, 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

func (BoundThreads) Transition added in v0.4.0

func (b BoundThreads) Transition(ctx context.Context, threadID string, t ThreadTransition) (bool, 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 BuiltinToolPorts added in v0.5.0

type BuiltinToolPorts struct {
	Search  Search
	Fetcher Fetcher
	// Sandbox is where commands run and files live: one sandbox per thread.
	Sandbox SandboxProvider
}

BuiltinToolPorts are the adapters the built-in tools use. A tool whose port is missing cannot be asked for: BuiltinTools returns an error at startup rather than a run failing later.

type CommandResult added in v0.5.0

type CommandResult struct {
	Stdout     string `json:"stdout"`
	Stderr     string `json:"stderr"`
	ExitCode   int    `json:"exitCode"`
	DurationMs int64  `json:"durationMs"`
	// TimedOut is true when the command was stopped at its time limit.
	TimedOut bool `json:"timedOut,omitempty"`
	// Truncated is true when output past MaxCommandOutputBytes was dropped.
	Truncated bool `json:"truncated,omitempty"`
}

CommandResult is what a command did.

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 CreateSandboxOptions added in v0.5.0

type CreateSandboxOptions struct {
	// Timeout is how long the sandbox lives unless SetTimeout pushes it
	// back. It then shuts itself down, even when the app that made it is
	// gone.
	Timeout  time.Duration
	Metadata SandboxMetadata
	// Envs are environment variables every command sees.
	Envs map[string]string
	// Template (E2B) or Image (Docker); adapters have their own default.
	Template  string
	Image     string
	Network   *SandboxNetwork
	Resources SandboxResources
	// Extra holds provider-only settings, passed through as they are.
	Extra map[string]any
}

CreateSandboxOptions shapes one new sandbox.

type CurrencyCost added in v0.4.0

type CurrencyCost struct {
	Currency   string `json:"currency"`
	CostMicros int64  `json:"costMicros"`
	// Calls is how many calls were priced in this currency.
	Calls int `json:"calls"`
}

CurrencyCost is the money spent in one currency (§4).

type CustomEvent added in v0.4.0

type CustomEvent struct {
	Name  string          `json:"name"`
	Value json.RawMessage `json:"value"`
}

CustomEvent is an app's own event, sent with PublishEvent.

func (*CustomEvent) StreamEventType added in v0.4.0

func (*CustomEvent) StreamEventType() string

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), a
	// job blocked by an older run's lock (§2.8) and a failed run's retry
	// backoff.
	//
	// An adapter that cannot delay may deliver immediately (every caller
	// treats 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
	// Key dedupes. At most one live row per key: a second enqueue with the
	// same key is refused with ErrDuplicateJob, and Cancel drops the waiting
	// row for a key. Empty means no dedupe.
	Key string
	// Priority orders ready rows: higher first, then oldest first. Zero is a
	// normal dispatch; the platform's housekeeping uses PriorityLow.
	Priority int
}

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 EventPruner added in v0.4.0

type EventPruner interface {
	Prune(ctx context.Context, types []string, limit int, dryRun bool, sc StorageContext) (map[string]int64, error)
}

EventPruner is what an EventStore may add to back PruneEvents: one batch of it. Prune deletes up to limit entries of these types, on every thread the store holds for sc, and says how many of each went. With dryRun it deletes nothing and counts every entry of these types instead. A store with a database per tenant opens the one sc names, as for any other call.

type EventStore

type EventStore interface {
	// Append stores an entry and mints its seq: the thread's next, one
	// higher than any it holds. Two appends on one thread never get the
	// same seq.
	Append(ctx context.Context, threadID string, e NewThreadEvent, sc StorageContext) (AgentEvent, error)
	// List returns entries by filter, ascending by seq.
	List(ctx context.Context, threadID string, f ThreadEventFilter, sc StorageContext) ([]AgentEvent, error)
	// ListSince returns all entries after the cursor, ascending by seq.
	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 thread record: the few events that must outlive a run (parks and their answers, refusals, budget stops, compaction, each segment's start and end, and an app's own events published durable). A run's live events go to its run stream, never here, so this grows with runs, not with tokens.

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"
	// StateQueued is a run accepted and waiting for a worker (§2.8). It
	// becomes RUNNING the moment a worker picks the job up.
	StateQueued          ExecutionState = "QUEUED"
	StateRunning         ExecutionState = "RUNNING"
	StateWaitingForInput ExecutionState = "WAITING_FOR_INPUT"
	StateCancelled       ExecutionState = "CANCELLED"
	StateCompleted       ExecutionState = "COMPLETED"
	StateFailed          ExecutionState = "FAILED"
)

type FetchOptions added in v0.5.0

type FetchOptions struct {
	// MaxBytes stops reading the page after this many bytes.
	MaxBytes int
	// Format is "markdown" or "text".
	Format string
}

FetchOptions shapes one page read.

type FetchedPage added in v0.5.0

type FetchedPage struct {
	// URL is where the page ended up, after redirects.
	URL     string
	Title   string
	Content string
	// Truncated is true when the page was cut at MaxBytes.
	Truncated bool
}

FetchedPage is one page, read.

type Fetcher added in v0.5.0

type Fetcher interface {
	Name() string
	Fetch(ctx context.Context, url string, opts FetchOptions) (FetchedPage, error)
}

Fetcher reads one web page as clean text: our PageReader, Jina Reader…

type FileEntry added in v0.5.0

type FileEntry struct {
	Name string `json:"name"`
	Type string `json:"type"`
	Size *int64 `json:"size,omitempty"`
}

FileEntry is one entry in a folder. Type is "file" or "directory"; Size is set for files.

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 InputRequiredEvent added in v0.4.0

type InputRequiredEvent struct {
	ToolCallID  string          `json:"toolCallId"`
	ToolName    string          `json:"toolName"`
	AgentID     *string         `json:"agentId"`
	Arguments   json.RawMessage `json:"arguments"`
	InputSchema json.RawMessage `json:"inputSchema"`
	// Frames is the unwind chain for a nested park; empty for the main agent.
	Frames json.RawMessage `json:"frames"`
	Nested json.RawMessage `json:"nested,omitempty"`
	// Resume is the dispatch ticket the answer resumes with.
	Resume    json.RawMessage `json:"resume,omitempty"`
	Reason    string          `json:"reason"`
	ExpiresAt string          `json:"expiresAt,omitempty"`
}

InputRequiredEvent says a tool is waiting for a person. Also kept in the thread record.

func (*InputRequiredEvent) StreamEventType added in v0.4.0

func (*InputRequiredEvent) StreamEventType() string

type JobKind added in v0.3.0

type JobKind string

JobKind says why a job was enqueued. A fresh user run is the default; the platform's own follow-ups name themselves so a queue can log them, order them and cap only the kind that brings new work in.

const (
	// JobDispatch is a fresh run from Run: the only kind a depth cap refuses.
	JobDispatch JobKind = ""
	// JobRetry is the same run trying again after a failure (§2.8).
	JobRetry JobKind = "retry"
	// JobRedrive is a job that found the run lock held by an older run.
	JobRedrive JobKind = "redrive"
	// JobResume continues a parked run after an answer (§2.5).
	JobResume JobKind = "resume"
	// JobExpiry is a park's own deadline (§2.5).
	JobExpiry JobKind = "expiry"
	// JobReclaim re-dispatches an orphaned thread (§2.5).
	JobReclaim JobKind = "reclaim"
)

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)
	// SetIfValue writes value with the given expiry only while the key
	// currently holds expected. Returns false when it holds anything else,
	// or nothing. Zero expiry means no expiry.
	SetIfValue(ctx context.Context, key, expected, value string, expiry time.Duration) (bool, error)
	Del(ctx context.Context, key string) error
	// DelIfValue deletes the key only while it holds expected. Returns true
	// iff it did.
	DelIfValue(ctx context.Context, key, expected string) (bool, error)
	Incr(ctx context.Context, key string) (int64, error)
	// IncrWithExpiry is Incr that also gives a NEW counter the expiry, so a
	// counter nobody clears still ages out. An existing counter keeps the
	// expiry it has.
	IncrWithExpiry(ctx context.Context, key string, expiry time.Duration) (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.

The two compare-and-act calls are what make a lease safe to renew and release: a worker only ever extends or frees a lock that still carries its own value, never one another worker took after its lapsed.

type MessageAppendedEvent added in v0.4.0

type MessageAppendedEvent struct {
	Message StreamMessage `json:"message"`
	// ClientMessageID is the sender's own name for the message, echoed back.
	ClientMessageID string `json:"clientMessageId,omitempty"`
}

func (*MessageAppendedEvent) StreamEventType added in v0.4.0

func (*MessageAppendedEvent) StreamEventType() string

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
	// State the record opens in. Empty means RUNNING, which is what a nested
	// run is from its first step; a dispatched run opens QUEUED.
	State ExecutionState
	// EnqueuedAt is set on a dispatched run: when it was put on the queue.
	EnqueuedAt *time.Time
	// CostBudgetMicros and MaxSteps are the dispatched caps (§4, §2.1).
	CostBudgetMicros int64
	MaxSteps         int
}

NewRunRecord opens a run record.

type NewStepRecord

type NewStepRecord = StepRecord

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

type NewThreadEvent added in v0.4.0

type NewThreadEvent struct {
	Type    string
	Payload json.RawMessage
	RunID   string
	// CreatedAt is when it happened; now when zero.
	CreatedAt time.Time
}

NewThreadEvent is an entry for the thread record, before the store gives it its seq.

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
	// Cancel drops every waiting job enqueued under key. A key nothing is
	// waiting under is not an error. Best-effort by contract: a delivered
	// row is a correct no-op anyway.
	Cancel(ctx context.Context, key string) error
	// Find returns the earliest waiting or running job for a run, or nil
	// when the queue holds none.
	Find(ctx context.Context, runID string) (*QueuedJob, error)
	// Stats counts what waits, runs and died.
	Stats(ctx context.Context) (QueueStats, 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.

Beside Enqueue the port carries the little an engine and a host need to see the queue: a way to withdraw a job by key, a way to find a run's job, and counts. An adapter that has no read side answers ErrUnsupported to Find and Stats; callers treat that as "unknown", never as a failure.

type QueueStats added in v0.3.0

type QueueStats struct {
	// Ready is jobs a worker could take right now.
	Ready int `json:"ready"`
	// Delayed is jobs held for a future run time: park expiries, retry
	// backoffs. Not backlog.
	Delayed int `json:"delayed"`
	// InFlight is jobs a worker holds a lease on.
	InFlight int `json:"inFlight"`
	// Dead is jobs the queue gave up on and kept for an operator.
	Dead int `json:"dead"`
	// OldestReadyMs is how long the oldest ready job has been waiting. The
	// number that says a queue is stuck rather than merely busy.
	OldestReadyMs int64 `json:"oldestReadyMs"`
	// Paused is true while the consumer is told not to claim.
	Paused bool `json:"paused"`
	// LastClaimAt is when this process last took a job; nil when it never has.
	LastClaimAt *time.Time `json:"lastClaimAt,omitempty"`
	// ClaimErrors is how many claims in a row have failed in this process.
	ClaimErrors int `json:"claimErrors"`
}

QueueStats is what a queue can say about itself. Every count is scoped to the consumer's own namespace.

type QueuedJob added in v0.3.0

type QueuedJob struct {
	ID          string     `json:"id"`
	RunID       string     `json:"runId"`
	ThreadID    string     `json:"threadId"`
	Kind        JobKind    `json:"kind"`
	Attempts    int        `json:"attempts"`
	RunAt       time.Time  `json:"runAt"`
	LockedUntil *time.Time `json:"lockedUntil,omitempty"`
	// Position is how many ready jobs are ahead of it; -1 when the adapter
	// cannot say.
	Position int `json:"position"`
}

QueuedJob is one row as the queue sees it, for a host that asks where a run's job is.

type ReasoningContentEvent added in v0.4.0

type ReasoningContentEvent struct {
	MessageID string `json:"messageId"`
	Delta     string `json:"delta"`
}

func (*ReasoningContentEvent) StreamEventType added in v0.4.0

func (*ReasoningContentEvent) StreamEventType() string

type ReasoningEndEvent added in v0.4.0

type ReasoningEndEvent struct {
	MessageID string `json:"messageId"`
}

func (*ReasoningEndEvent) StreamEventType added in v0.4.0

func (*ReasoningEndEvent) StreamEventType() string

type ReasoningStartEvent added in v0.4.0

type ReasoningStartEvent struct {
	MessageID string `json:"messageId"`
}

func (*ReasoningStartEvent) StreamEventType added in v0.4.0

func (*ReasoningStartEvent) StreamEventType() string

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"`
	// DispatchedAt is epoch milliseconds of the run's first dispatch, so a
	// resume keeps the run's place in line.
	DispatchedAt     int64           `json:"dispatchedAt,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 RunBudget added in v0.3.0

type RunBudget struct {
	// CostBudgetMicros is the money cap (§4); zero is unbounded.
	CostBudgetMicros int64
	// MaxSteps is the step cap; zero keeps the config's.
	MaxSteps int
}

RunBudget is the money and step cap a segment runs with.

type RunCommandOptions added in v0.5.0

type RunCommandOptions struct {
	// Cwd is where the command runs. A relative path is taken from the
	// sandbox's work folder, which is also the default.
	Cwd string
	Env map[string]string
	// Timeout stops the command after this long: the result then has
	// TimedOut and exit code 124, with the output it printed so far. Zero
	// is DefaultCommandTimeout. Cancelling ctx also stops it, and returns
	// ctx's error.
	Timeout time.Duration
	// Background starts the command and returns at once, leaving it
	// running (a dev server, say). Its output is not kept.
	Background bool
	// OnStdout and OnStderr get output as it comes, decoded as UTF-8.
	OnStdout func(chunk string)
	OnStderr func(chunk string)
}

RunCommandOptions shapes one command.

type RunCursor added in v0.4.0

type RunCursor struct {
	StartedAt time.Time
	ID        string
}

RunCursor is a place in a run listing (see RunFilter.Before).

func CursorOf added in v0.4.0

func CursorOf(r RunRecord) *RunCursor

CursorOf is the cursor just after a run in a listing.

type RunDeltas added in v0.4.0

type RunDeltas struct {
	Steps             int
	InputTokens       int
	CachedInputTokens int
	OutputTokens      int
	TotalTokens       int
}

RunDeltas are amounts to add to a run's counters (see RunStore.Increment).

type RunErrorEvent added in v0.4.0

type RunErrorEvent struct {
	// Status is "error", or "lost" when the worker died and the sweep closed
	// its stream.
	Status string `json:"status"`
	Error  string `json:"error"`
}

RunErrorEvent says the run's segment ended badly. Always the last item of a stream.

func (*RunErrorEvent) StreamEventType added in v0.4.0

func (*RunErrorEvent) StreamEventType() string

type RunFilter

type RunFilter struct {
	// State: any of these; empty means all.
	State    []ExecutionState
	Agent    string
	ThreadID string
	Since    *time.Time
	Until    *time.Time
	// ThreadIDs keeps only runs on these threads. Empty means every thread.
	ThreadIDs []string
	// Unsettled keeps only runs that have ended and whose settle has not
	// run (§5.6): what the late-settle sweep looks for.
	Unsettled bool
	// Depth keeps only runs at this depth: 0 is a dispatched run. Nil is
	// every depth.
	Depth *int
	// Before pages through a listing: only runs that sort after this one,
	// newest first by start time and then by id. Pass the last run of the
	// previous page.
	Before *RunCursor
	// 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 RunFinishedEvent added in v0.4.0

type RunFinishedEvent struct {
	// Status is "finished", "parked" or "stopped".
	Status       string       `json:"status"`
	Usage        *StreamUsage `json:"usage,omitempty"`
	Costs        []StreamCost `json:"costs,omitempty"`
	FinishReason string       `json:"finishReason,omitempty"`
	// Text is the final text of a one-shot agent.
	Text string `json:"text,omitempty"`
}

RunFinishedEvent says the run's segment ended normally. Always the last item of a stream.

func (*RunFinishedEvent) StreamEventType added in v0.4.0

func (*RunFinishedEvent) StreamEventType() string

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
	// PartitionKey is the caller's tenant, written on the dispatch ticket so
	// a queue that spreads its claims across partitions can keep one tenant's
	// backlog from starving the others. Opaque to the platform; empty means
	// one shared lane.
	PartitionKey string
	// ClientMessageID is the sending client's own name for the user turn.
	// It comes back on the turn's MESSAGE_APPENDED, so the client that sent
	// it can swap its optimistic copy for the real one by id, never by
	// matching text. Opaque to the platform, and not stored.
	ClientMessageID string
}

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"`
	// DispatchID names THIS enqueue of the run: a fresh dispatch, a retry, a
	// resume each get their own. A queue that delivers one job twice
	// delivers the same DispatchID, which is how the run lock tells a
	// duplicate apart from another delivery of the same run (§3.4). Stamped
	// by the platform when it enqueues; empty on jobs written before it.
	DispatchID string `json:"dispatchId,omitempty"`
	// EnqueuedAt is epoch milliseconds at THIS enqueue (§2.9): the queue
	// wait a worker measures on pickup.
	EnqueuedAt int64 `json:"enqueuedAt,omitempty"`
	// DispatchedAt is epoch milliseconds of the run's first dispatch. A
	// retry, redrive or resume carries it on, so the run keeps its place in
	// line instead of going to the back. Zero means "now".
	DispatchedAt int64 `json:"dispatchedAt,omitempty"`
	// Kind says why the job exists: a fresh dispatch, a retry, a resume, a
	// park expiry. See JobKind.
	Kind JobKind `json:"kind,omitempty"`
	// PartitionKey is the caller's tenant, opaque to the platform. A queue
	// that can spread its claims across partitions serves one tenant's
	// backlog without starving the others. Empty means one shared lane.
	PartitionKey string `json:"partitionKey,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
	// StartedAt moves the start to the moment a worker picked the run up.
	StartedAt         *time.Time
	EndedAt           *time.Time
	DurationMs        *int64
	QueuedMs          *int64
	SettledAt         *time.Time
	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"`
	// EnqueuedAt is when the run was accepted and put on the queue (§2.8).
	// Nil on a nested run, which is never queued.
	EnqueuedAt *time.Time `json:"enqueuedAt,omitempty"`
	// StartedAt is when a worker first picked the run up. Until then it is
	// the enqueue time, so a listing sorted on it stays stable.
	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 the latest enqueue and a worker starting
	// on it (§2.8): the first dispatch's wait, then a retry's or a resume's.
	QueuedMs *int64 `json:"queuedMs,omitempty"`
	// SettledAt is when the spec's OnSettle ran for this run (§5.6). A run
	// settles exactly once: a worker that ends it, or a stop that ends it
	// while no worker holds it. Unset until then.
	SettledAt *time.Time `json:"settledAt,omitempty"`
	// SettlingAt is when a settle claimed the run and started its hook. It
	// is cleared when the settle ends; one left behind for long is a settler
	// that died, and the next settle takes the run over.
	SettlingAt *time.Time `json:"settlingAt,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"`
	// CostBudgetMicros and MaxSteps are the caps the run was dispatched with
	// (§4, §2.1), kept so a run re-dispatched from its record keeps them.
	CostBudgetMicros int64 `json:"costBudgetMicros,omitempty"`
	MaxSteps         int   `json:"maxSteps,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"`
	Reason   string         `json:"reason,omitempty"`
}

RunResult is what Run answers. Accepted false carries a reason in Error and, for the refusals a host acts on, a code in Reason.

type RunStartedEvent added in v0.4.0

type RunStartedEvent struct {
	ThreadID string `json:"threadId"`
	RunID    string `json:"runId"`
	StreamID string `json:"streamId"`
	// Segment is 1 for the first pickup, 2 for the resume after a park, and
	// so on.
	Segment int `json:"segment"`
}

RunStartedEvent opens every stream.

func (*RunStartedEvent) StreamEventType added in v0.4.0

func (*RunStartedEvent) StreamEventType() string

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)
	// Increment adds to a run's counters in one write (SET steps = steps +
	// n), so two segments that close together both count. An unknown run
	// is not an error.
	Increment(ctx context.Context, runID string, d RunDeltas) error
	// Totals counts and sums every run the filter matches, grouped in the
	// store: exact however many runs there are. Limit and Before are
	// ignored.
	Totals(ctx context.Context, f RunFilter) (RunTotals, error)
	// ClaimSettle claims the right to run a run's settle hook (§5.6), in one
	// conditional write: it wins only while the run is not settled and no
	// other claim on it is newer than staleBefore. A claim older than that
	// belongs to a settler that died, and is taken over. Returns false when
	// the run is unknown, settled, or claimed by someone else.
	ClaimSettle(ctx context.Context, runID, token string, staleBefore time.Time) (bool, error)
	// EndSettle ends a claim made with token. settled marks the run settled
	// for good; otherwise the claim is dropped so a later settle can run
	// the hook again. A claim that was taken over is left alone.
	EndSettle(ctx context.Context, runID, token string, settled bool) error
}

RunStore holds run records.

type RunStreams added in v0.4.0

type RunStreams interface {
	// Open opens a stream. Opening one that exists is a no-op. ttl deletes
	// it even if it is never closed.
	Open(ctx context.Context, streamID string, meta StreamMeta, ttl time.Duration) error
	// Append appends in order and returns one offset per event. It fails
	// with ErrStreamClosed once closed and ErrStreamGone when the stream
	// does not exist.
	Append(ctx context.Context, streamID string, events []StreamEvent) ([]string, error)
	// Read yields the items after `after` ("" is from the start), then live
	// ones as they come. It ends after the end item, or when ctx is done
	// (quietly, with no error). It yields ErrStreamGone when the stream does
	// not exist, or goes while read.
	Read(ctx context.Context, streamID, after string) iter.Seq2[StreamItem, error]
	// Snapshot returns the items after `after` now, without waiting. Nil,
	// nil when the stream does not exist.
	Snapshot(ctx context.Context, streamID, after string) (*StreamSnapshot, error)
	// Close writes the end item and starts the grace window: the stream is
	// deleted grace later. Closing a closed stream is a no-op; closing one
	// that does not exist fails with ErrStreamGone.
	Close(ctx context.Context, streamID string, end StreamEnd, grace time.Duration) error
	// Delete removes a stream now (thread delete). A missing one is a no-op.
	Delete(ctx context.Context, streamID string) error
}

RunStreams holds short-lived logs, one per run segment. Delivery lives here, not state: a stream is closed when its segment ends and deleted after a grace window. What must outlive the run is in the messages and the thread record.

Every adapter keeps these rules:

  • Offsets are opaque strings. Only the store compares them; a client echoes the last one back and nothing else.
  • Offsets strictly increase within a stream. One writer per stream: the run lock already makes sure of that.
  • Close writes the end as the last item, so a reader that sees it stops, and one that comes late still gets it.
  • A missed wake-up only delays a reader, never drops an event.

type RunTotals added in v0.4.0

type RunTotals struct {
	Runs         int                    `json:"runs"`
	ByState      map[ExecutionState]int `json:"byState"`
	ByStopReason map[string]int         `json:"byStopReason"`
	Steps        int                    `json:"steps"`
	// Tokens are summed from the run records: tokens only, no money.
	InputTokens       int `json:"inputTokens"`
	CachedInputTokens int `json:"cachedInputTokens"`
	OutputTokens      int `json:"outputTokens"`
	TotalTokens       int `json:"totalTokens"`
}

RunTotals is what RunStore.Totals counts over a set of runs.

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
	// Streams holds short-lived logs, one per run segment: where a run's
	// live events go. Nil keeps them in memory, which only this process can
	// read: fine for one process, not for web servers and workers that run
	// apart.
	Streams RunStreams
	// 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
	// Tools are the adapters behind the built-in tools: a search engine for
	// web_search, a page reader for web_fetch, a sandbox provider for the
	// tools that run commands. Only the tools you ask BuiltinTools for need
	// theirs.
	Tools BuiltinToolPorts
}

RuntimeOptions is what SetupAgentCore takes.

type RuntimePorts

type RuntimePorts struct {
	Storage BoundStorage
	Admin   AdminStore
	Bus     EventBus
	Queue   Queue
	Kv      Kv
	// Streams holds the run streams, one per segment; nil writes none.
	Streams RunStreams
	// 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
	// Tools are the adapters behind the built-in tools.
	Tools BuiltinToolPorts
}

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 Sandbox added in v0.5.0

type Sandbox interface {
	ID() string
	Provider() string
	Filesystem() SandboxFileSystem
	RunCommand(ctx context.Context, command string, opts RunCommandOptions) (CommandResult, error)
	// GetURL returns a URL for a port the sandbox serves on, or an error
	// matching ErrSandboxUnsupported where the adapter cannot give one.
	// Protocol is "http" or "https"; empty is the adapter's default.
	GetURL(ctx context.Context, port int, protocol string) (string, error)
	GetInfo(ctx context.Context) (SandboxInfo, error)
	// SetTimeout is not in ComputeSDK: the sandbox now shuts itself down d
	// from now. The runtime calls it as a thread uses its sandbox, so one
	// left idle ends by itself. It returns an error matching
	// ErrSandboxUnsupported where the provider cannot change it.
	SetTimeout(ctx context.Context, d time.Duration) error
	// Destroy ends the sandbox and its files. Fine when it is already gone.
	Destroy(ctx context.Context) error
}

Sandbox is one sandbox.

type SandboxFileSystem added in v0.5.0

type SandboxFileSystem interface {
	// ReadFile returns an error matching ErrSandboxFileNotFound when there
	// is no such file.
	ReadFile(ctx context.Context, path string) (string, error)
	// ReadFileBytes is not in ComputeSDK: charts and images are bytes.
	ReadFileBytes(ctx context.Context, path string) ([]byte, error)
	// WriteFile makes the parent folders it needs, and replaces a file
	// already there.
	WriteFile(ctx context.Context, path string, content []byte) error
	// ReadDir returns the folder's entries, sorted by name, or an error
	// matching ErrSandboxFileNotFound when there is no such folder.
	ReadDir(ctx context.Context, path string) ([]FileEntry, error)
	// Mkdir makes the folder and its parents; fine when it is there already.
	Mkdir(ctx context.Context, path string) error
	Exists(ctx context.Context, path string) (bool, error)
	// Remove removes a file, or a folder with everything in it; fine when
	// it is not there.
	Remove(ctx context.Context, path string) error
}

SandboxFileSystem is the sandbox's files. A relative path is taken from the work folder.

type SandboxInfo added in v0.5.0

type SandboxInfo struct {
	ID       string
	Provider string
	// Status is "running", "stopped" or "error".
	Status    string
	CreatedAt time.Time
	// ExpiresAt is when it will shut itself down, when the provider says;
	// zero otherwise.
	ExpiresAt time.Time
	// Workdir is the folder commands start in and relative paths are taken
	// from.
	Workdir  string
	Metadata map[string]string
}

SandboxInfo describes a sandbox.

type SandboxMetadata added in v0.5.0

type SandboxMetadata struct {
	ThreadID string
	RunID    string
	State    AgentRunState
}

SandboxMetadata says what a sandbox is for. Adapters keep ThreadID and RunID as labels or metadata where the provider has them; a multi-tenant adapter can read State to pick a template or key per tenant (§2.10).

type SandboxNetwork added in v0.5.0

type SandboxNetwork struct {
	// Mode is "none", "all" or "allow". Empty is "none".
	Mode  string
	Allow []string
}

SandboxNetwork is what a sandbox may reach: "none" (the default), "all", or only the hosts in Allow.

type SandboxProvider added in v0.5.0

type SandboxProvider interface {
	// Name is the adapter's name: "docker", "e2b", "local".
	Name() string
	Create(ctx context.Context, opts CreateSandboxOptions) (Sandbox, error)
	// Connect finds a sandbox made earlier, by this process or another. It
	// returns an error matching ErrSandboxGone when it no longer exists.
	Connect(ctx context.Context, sandboxID string) (Sandbox, error)
}

SandboxProvider makes sandboxes and finds them again. One per app, set as RuntimeOptions.Tools.Sandbox.

type SandboxResources added in v0.5.0

type SandboxResources struct {
	CPU       float64
	MemoryMiB int
	DiskMiB   int
}

SandboxResources asks for a size; zero leaves the adapter's default.

type Search interface {
	// Name is the adapter's name, as usage rows and prices know it: "brave".
	Name() string
	Search(ctx context.Context, query string, opts SearchOptions) ([]SearchHit, error)
}

Search is a web search engine: Brave, Jina, Tavily…

type SearchHit added in v0.5.0

type SearchHit struct {
	Title string `json:"title"`
	URL   string `json:"url"`
	// Snippet is a short piece of the page that matched: what the model
	// reads to decide whether to open it.
	Snippet string `json:"snippet"`
	// PublishedAt is an ISO date, when the engine knows it.
	PublishedAt string `json:"publishedAt,omitempty"`
}

SearchHit is one search result.

type SearchOptions added in v0.5.0

type SearchOptions struct {
	// MaxResults is 1 to 10.
	MaxResults int
	// AllowedDomains keeps only results from these domains (and their
	// subdomains).
	AllowedDomains []string
	// BlockedDomains drops results from these domains (and their
	// subdomains).
	BlockedDomains []string
	Recency        SearchRecency
}

SearchOptions shapes one search.

type SearchRecency added in v0.5.0

type SearchRecency string

SearchRecency is how far back a search may look: "day", "week", "month" or "year".

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 Cancelled set, on a ctx that is not cancelled, so the hook's own writes land; tell a stop apart by Cancelled, never by ctx.Err().

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

type SnapshotStream added in v0.4.0

type SnapshotStream struct {
	StreamID string `json:"streamId"`
	RunID    string `json:"runId"`
	// Items are what the messages do not have yet: each agent's events
	// after its last finished step. A finished step is in the messages
	// already, and showing its deltas too would put its text on screen
	// twice.
	Items []StreamItem `json:"items"`
	// End is the stream's end, when it has one.
	End StreamEnd `json:"-"`
	// Offset is where a live read picks up: the last offset the stream
	// held, cut items included. Empty for a stream with nothing in it.
	Offset string `json:"offset"`
}

SnapshotStream is the run stream a snapshot carries: the segment in flight, or one that ended a moment ago, so a tab that loads just as a run ends still sees its end.

func (SnapshotStream) MarshalJSON added in v0.4.0

func (s SnapshotStream) MarshalJSON() ([]byte, error)

MarshalJSON writes End as its event JSON, or null, and Offset as null when empty, as the TS runtime does.

type SourceEvent added in v0.4.0

type SourceEvent struct {
	Source json.RawMessage `json:"source"`
}

SourceEvent is a source the model cited. Not in AG-UI: the encoder sends it as CUSTOM.

func (*SourceEvent) StreamEventType added in v0.4.0

func (*SourceEvent) StreamEventType() string

type StepFinishedEvent added in v0.4.0

type StepFinishedEvent struct {
	// Step is 1-based, per agent.
	Step int `json:"step"`
	// AgentID is nil for the main agent, the nested run's id otherwise.
	AgentID      *string     `json:"agentId"`
	FinishReason string      `json:"finishReason"`
	Usage        StreamUsage `json:"usage"`
}

StepFinishedEvent says one model call is done and its messages are saved.

func (*StepFinishedEvent) StreamEventType added in v0.4.0

func (*StepFinishedEvent) StreamEventType() string

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 StreamCost added in v0.4.0

type StreamCost struct {
	Currency string `json:"currency"`
	Micros   int64  `json:"micros"`
}

StreamCost is money spent in one currency, in millionths of a unit.

type StreamEnd added in v0.4.0

type StreamEnd interface {
	StreamEvent
	// contains filtered or unexported methods
}

StreamEnd is how a stream ends: *RunFinishedEvent or *RunErrorEvent.

type StreamEvent added in v0.4.0

type StreamEvent interface {
	StreamEventType() string
}

StreamEvent is one event a run stream carries. The concrete types below are the whole set; their JSON is the same as the TS runtime's, "type" first. The shapes follow AG-UI, so an AG-UI encoder only renames a few fields.

func DecodeStreamEvent added in v0.4.0

func DecodeStreamEvent(data []byte) (StreamEvent, error)

DecodeStreamEvent reads an event written by EncodeStreamEvent (or the TS runtime). An "offset" field, if any, is ignored.

type StreamItem added in v0.4.0

type StreamItem struct {
	Offset string
	Event  StreamEvent
}

StreamItem is an event as a stream holds it: with the offset the store gave it. Its JSON is the event's with "offset" added.

func (StreamItem) MarshalJSON added in v0.4.0

func (i StreamItem) MarshalJSON() ([]byte, error)

MarshalJSON writes the event's JSON with "offset" added.

func (*StreamItem) UnmarshalJSON added in v0.4.0

func (i *StreamItem) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an item written by MarshalJSON.

type StreamMessage added in v0.4.0

type StreamMessage struct {
	ID        string          `json:"id"`
	Role      string          `json:"role"`
	Content   json.RawMessage `json:"content"`
	AgentID   *string         `json:"agentId"`
	CreatedAt string          `json:"createdAt"`
}

StreamMessage is a saved message as MESSAGE_APPENDED carries it.

type StreamMeta added in v0.4.0

type StreamMeta struct {
	ThreadID string `json:"threadId"`
	RunID    string `json:"runId"`
}

StreamMeta is who a stream belongs to.

type StreamSnapshot added in v0.4.0

type StreamSnapshot struct {
	Meta  StreamMeta   `json:"meta"`
	Items []StreamItem `json:"items"`
	// End is the end item when the stream is closed; it is also the last of
	// Items.
	End StreamEnd `json:"end"`
}

StreamSnapshot is a stream as it stands now.

func (StreamSnapshot) MarshalJSON added in v0.4.0

func (s StreamSnapshot) MarshalJSON() ([]byte, error)

MarshalJSON writes End as its event JSON, or null.

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 StreamUsage added in v0.4.0

type StreamUsage struct {
	InputTokens       int64 `json:"inputTokens"`
	CachedInputTokens int64 `json:"cachedInputTokens"`
	OutputTokens      int64 `json:"outputTokens"`
	TotalTokens       int64 `json:"totalTokens"`
}

StreamUsage is the tokens a step or a run used.

type SubagentEventEvent added in v0.4.0

type SubagentEventEvent struct {
	SubagentID string
	Event      StreamEvent
}

SubagentEventEvent is one event from a nested run, wrapped.

func (*SubagentEventEvent) MarshalJSON added in v0.4.0

func (w *SubagentEventEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the wrapped event whole.

func (*SubagentEventEvent) StreamEventType added in v0.4.0

func (*SubagentEventEvent) StreamEventType() string

type SubagentFinishedEvent added in v0.4.0

type SubagentFinishedEvent struct {
	SubagentID string `json:"subagentId"`
	// Status is "completed", "failed", or "cancelled" when a user stop
	// reached the child.
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

func (*SubagentFinishedEvent) StreamEventType added in v0.4.0

func (*SubagentFinishedEvent) StreamEventType() string

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 SubagentStartedEvent added in v0.4.0

type SubagentStartedEvent struct {
	SubagentID string `json:"subagentId"`
	Name       string `json:"name"`
	Depth      int    `json:"depth"`
}

func (*SubagentStartedEvent) StreamEventType added in v0.4.0

func (*SubagentStartedEvent) StreamEventType() string

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 TextMessageContentEvent added in v0.4.0

type TextMessageContentEvent struct {
	MessageID string `json:"messageId"`
	Delta     string `json:"delta"`
}

func (*TextMessageContentEvent) StreamEventType added in v0.4.0

func (*TextMessageContentEvent) StreamEventType() string

type TextMessageEndEvent added in v0.4.0

type TextMessageEndEvent struct {
	MessageID string `json:"messageId"`
}

func (*TextMessageEndEvent) StreamEventType added in v0.4.0

func (*TextMessageEndEvent) StreamEventType() string

type TextMessageStartEvent added in v0.4.0

type TextMessageStartEvent struct {
	MessageID string `json:"messageId"`
	Role      string `json:"role"`
}

func (*TextMessageStartEvent) StreamEventType added in v0.4.0

func (*TextMessageStartEvent) StreamEventType() string

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 ThreadEventFilter added in v0.4.0

type ThreadEventFilter struct {
	Types []string
	RunID string
	// After, when set, keeps only entries after this seq.
	After *int64
	// Limit, when above zero, caps how many come back.
	Limit int
}

ThreadEventFilter picks record entries: all of them by default, oldest first.

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 thread record's last seq.
	LastEventSeq int64 `json:"lastEventSeq"`
	// ActiveEvents are the unfinished run's record entries: its open park,
	// a refusal.
	ActiveEvents []AgentEvent `json:"activeEvents"`
	// Stream is the run stream in flight, or one that just ended: what the
	// messages do not have yet, and where a live read picks up.
	Stream *SnapshotStream `json:"stream"`
}

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)
	// Transition is the compare-and-set every run state change goes
	// through: true iff THIS caller moved the thread (see ThreadTransition).
	// It must also record the thread's current run, which the adapter
	// keeps beside the state. Atomic, like ClaimState: one conditional
	// UPDATE or equivalent.
	Transition(ctx context.Context, threadID string, t ThreadTransition, sc StorageContext) (bool, error)
}

ThreadStore is the threads section of Storage.

type ThreadTransition added in v0.4.0

type ThreadTransition struct {
	From []ExecutionState
	To   ExecutionState
	// RunID is the run the caller acts for. The transition lands only while
	// the thread's current run is this one, or the thread has no run
	// recorded yet (a thread from before run ids were stored). Empty means
	// any run.
	RunID string
	// NewRunID makes the thread belong to a new run: set by run admission.
	// Empty keeps the current one.
	NewRunID string
}

ThreadTransition is one compare-and-set on a thread's state (§3.4). It lands only while the thread is in one of From AND still belongs to RunID, so a run that has been stopped or replaced can never move the thread again: its write simply loses.

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 ToolCallArgsEvent added in v0.4.0

type ToolCallArgsEvent struct {
	ToolCallID string `json:"toolCallId"`
	Delta      string `json:"delta"`
}

func (*ToolCallArgsEvent) StreamEventType added in v0.4.0

func (*ToolCallArgsEvent) StreamEventType() string

type ToolCallEndEvent added in v0.4.0

type ToolCallEndEvent struct {
	ToolCallID string          `json:"toolCallId"`
	ToolName   string          `json:"toolName"`
	Args       json.RawMessage `json:"args"`
}

ToolCallEndEvent says the call is complete. Args is the whole, parsed argument object, so a reader that missed the ARGS deltas still has it.

func (*ToolCallEndEvent) StreamEventType added in v0.4.0

func (*ToolCallEndEvent) StreamEventType() string

type ToolCallResultEvent added in v0.4.0

type ToolCallResultEvent struct {
	ToolCallID string          `json:"toolCallId"`
	ToolName   string          `json:"toolName"`
	Result     json.RawMessage `json:"result"`
}

func (*ToolCallResultEvent) StreamEventType added in v0.4.0

func (*ToolCallResultEvent) StreamEventType() string

type ToolCallStartEvent added in v0.4.0

type ToolCallStartEvent struct {
	ToolCallID string `json:"toolCallId"`
	ToolName   string `json:"toolName"`
}

func (*ToolCallStartEvent) StreamEventType added in v0.4.0

func (*ToolCallStartEvent) StreamEventType() string

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 (see UsageLineMerger). 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"
	// KindTool is a built-in tool: one row per use of a paid service (a
	// search, a page read), with Model "tool:<tool name>" and ModelID the
	// adapter, and one per model call a tool makes itself (reading a page
	// with a question).
	KindTool UsageKind = "tool"
)

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"`
	// Currency is the unit CostMicros is in, empty when none of the
	// line's calls was priced.
	Currency              string `json:"currency,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.

The rules, the same in every adapter and in the TS runtime: CostMicros is summed in the first currency seen, and a group priced in another currency counts as unpriced there instead of being added. Costs keeps every currency's own total. A line takes the currency of the first priced group on it; a group priced in a different currency gets a line of its own, and unpriced groups join the first line of their agent and model.

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: the first currency priced,
	// empty when nothing was. Money is never converted, so a call priced in
	// another currency is left out of CostMicros and counted in Unpriced;
	// Costs has every currency's own total.
	Currency string `json:"currency,omitempty"`
	// Unpriced is how many calls CostMicros leaves out: calls no pricer
	// answered for, and calls priced in another currency. Above zero,
	// CostMicros is a floor and not the whole bill.
	Unpriced int `json:"unpriced"`
	// Costs is the money per currency, in the order each was first seen.
	// One run is only ever priced in one currency (a second one is refused
	// when the call is recorded), so a run's bill has at most one entry; a
	// thread whose pricer changed currency between runs can have more.
	Costs []CurrencyCost `json:"costs,omitempty"`
	// Lines is the same spend grouped by agent, model and currency: one
	// line per agent and model, which is the shape a bill wants. Summing
	// the lines of one currency gives that currency's entry in Costs.
	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