core

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 19 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 core holds the platform's behaviors. Everything here works against the ports bundle and nothing else: no driver, no provider SDK beyond goai.

Index

Constants

View Source
const ContextSummaryType = "CONTEXT_SUMMARY"

ContextSummaryType marks a compaction summary envelope (§2.6).

View Source
const ContextTokenCeiling = 265_000

ContextTokenCeiling is the universal context ceiling across all models (§2.6).

View Source
const DefaultModel = "gpt-4o"

DefaultModel is used when neither the run input nor the spec names one.

View Source
const HITLParked = "__hitl_parked__"

HITLParked is the key of the result a parked `RequiresConfirmation` tool returns (§2.5). The engine scans a step's tool results for this marker to end the run segment; it is never persisted as a tool result. The resumed segment appends the user's verdict (or the timeout denial) instead.

View Source
const HITLTTL = 15 * time.Minute

HITLTTL is the default time a parked request stays answerable (§2.5).

Variables

View Source
var ReservedEventTypes = map[string]bool{
	"CHUNK": true, "STATE_CHANGE": true, "STEP_COMMITTED": true, "STEP_FINISHED": true,
	"INPUT_REQUIRED": true, "INPUT_EXPIRED": true, "HITL_RESPONSE": true,
	"MESSAGE_APPENDED": true, "MESSAGES_DROPPED": true, "CONTEXT_COMPACTED": true,
	"SUBAGENT_STARTED": true, "SUBAGENT_CHUNK": true, "SUBAGENT_COMPLETED": true, "SUBAGENT_FAILED": true,
	"TEXT_RESULT": true, "THREAD_DELETED": true, "HEARTBEAT": true,
	"RUN_REFUSED": true, "TOKEN_BUDGET_EXHAUSTED": true,
}

ReservedEventTypes are the event types the platform itself emits. An app cannot publish these: a client's reducer trusts them to mean what the engine meant.

View Source
var SSEHeaders = map[string]string{
	"Content-Type":      "text/event-stream; charset=utf-8",
	"Cache-Control":     "no-cache, no-transform",
	"Connection":        "keep-alive",
	"X-Accel-Buffering": "no",
}

SSEHeaders are the headers an SSE response needs. X-Accel-Buffering is for nginx, which otherwise buffers the stream.

Functions

func AgentTool

func AgentTool[In any](name, description string, execute func(ctx context.Context, input In, tc ToolContext) (string, error)) ports.Tool

AgentTool is goai.NewTool with the platform's ToolContext handed to the handler: the run state (§2.10) and PublishEvent.

lookupInvoice := agentenkit.AgentTool("lookupInvoice", "Find one invoice",
	func(ctx context.Context, in struct{ InvoiceID string `json:"invoiceId"` }, tc agentenkit.ToolContext) (string, error) {
		return db.FindInvoice(ctx, in.InvoiceID, tc.State["orgId"])
	})

The result is an ordinary platform Tool: it composes with MarkRequiresConfirmation and can be passed anywhere a Tool can.

func AttemptsKey

func AttemptsKey(threadID string) string

AttemptsKey counts §2.8 failure retries.

func ChunkPayload

func ChunkPayload(c provider.StreamChunk) map[string]any

ChunkPayload renders a goai stream chunk in the AI SDK part shape the TypeScript package publishes as CHUNK. A client written against one runtime keeps working against the other.

func ClaimRun

func ClaimRun(ctx context.Context, deps ports.RuntimePorts, threadID string) (string, error)

ClaimRun claims the thread for a brand new run and returns its id (§2.1). Always called BEFORE the state key is written.

func ClaimRunAs

func ClaimRunAs(ctx context.Context, deps ports.RuntimePorts, threadID, runID string) (string, error)

ClaimRunAs is ClaimRun with a caller-chosen id (§2.1). The caller has already checked the id is unused.

func CompactContext

func CompactContext(ctx context.Context, deps ports.RuntimePorts, threadID, model string) ([]ports.MessageDTO, error)

CompactContext returns a history guaranteed to fit the model's budget. Compaction is durable: the summary is persisted as a message, so every client and every reconnect replay (§2.2) reconstructs the same context.

func ContentFromMessage

func ContentFromMessage(m provider.Message) json.RawMessage

ContentFromMessage converts a goai message into stored content.

func ContextBudget

func ContextBudget(deps ports.RuntimePorts, model string) int

ContextBudget is min(native window, ceiling). The model's declared ContextWindow (via ResolveModel, §3.3) wins over the fallback tables.

func ContextSummaryContent

func ContextSummaryContent(text string) json.RawMessage

ContextSummaryContent encodes a compaction summary envelope.

func ContextUsage

func ContextUsage(ctx context.Context, deps ports.RuntimePorts, threadID, model string) (ports.ContextUsage, error)

ContextUsage is the read-only view of the §2.6 budget math: what CompactContext would see on the next run, without summarizing anything.

func ContextWithApproval

func ContextWithApproval(ctx context.Context, a Approval) context.Context

ContextWithApproval marks a tool call as the resumption of an approved park.

func ContextWithPublisher

func ContextWithPublisher(ctx context.Context, p EventPublisher) context.Context

ContextWithPublisher attaches a thread-bound EventPublisher to a context.

func ContextWithRunID

func ContextWithRunID(ctx context.Context, runID string) context.Context

ContextWithRunID names the run a context serves. Execute stamps it on the model-call context, so a model wrapper (a cost recorder, a rate limiter) can tell which run it is working for.

func ContextWithRunState

func ContextWithRunState(ctx context.Context, state ports.AgentRunState) context.Context

ContextWithRunState attaches the run's state to a context.

func ContextWithToolCallID

func ContextWithToolCallID(ctx context.Context, id string) context.Context

ContextWithToolCallID names the call a resumed tool is answering; goai stamps its own id on live calls.

func CountTokens

func CountTokens(u provider.Usage) int

CountTokens is the total tokens used: input + cached + output.

func CurrentRunID

func CurrentRunID(ctx context.Context, deps ports.RuntimePorts, threadID string) (string, error)

CurrentRunID is the run that owns the thread right now, or "" on a thread that predates run ids. Resuming a parked run (§2.5) REUSES this: a resume is the same run continuing, so it must never bump the id.

func DeleteThread

func DeleteThread(ctx context.Context, deps ports.RuntimePorts, threadID string) (ports.DeleteThreadResult, error)

DeleteThread is the §3.2 deletion behavior: one call removes the thread and everything that follows it (messages, events, usage rows) plus the thread's hot kv keys.

Guards:

  • RUNNING is refused: a live worker is mid-segment and would keep writing behind the delete. Stop first, then delete.
  • WAITING_FOR_INPUT deletes cleanly: a park holds NO process (§2.5), and a late resume dispatch is a no-op against the missing thread.

func EstimateMessages

func EstimateMessages(messages []provider.Message) int

EstimateMessages is estimateTokens over a prompt. The platform uses it in the two places no real count exists: how full the context is (§2.6), and the prompt of a call that was cut off before the provider reported one (§4). One rule for both, so the two can never disagree.

func ExecuteWithPolicy

func ExecuteWithPolicy(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, input ExecuteInput, policy *Policy) error

ExecuteWithPolicy is the §2.8 failure policy: transient errors redrive through the queue; exhausted attempts finalize FAILED (hot cache + durable). A user stop is never retried, and a successful run resets the attempt counter.

It returns nil once the outcome has been handled, whether the run ran, was redriven, or was finalized FAILED. It returns an error only when the policy itself could not be applied (a port failed).

func FillTokens

func FillTokens(n *ports.NewUsage, u provider.Usage)

FillTokens copies one goai usage report onto a usage row, cache writes and reasoning included. Those two are not part of TotalTokens (see ports.NewUsage.TotalTokens), but a pricer needs them: cache writes are a separate line on the provider's bill.

func Finalize

func Finalize(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, threadID string, f FinalizeInput) error

Finalize finalizes a finished run (§5.6): attribute the segment's tokens (§4), then flip state on both homes and publish. Message persistence already happened per step inside the loop.

A budget break is NOT a user stop: the run completes with stopReason 'token_budget' and the usage it actually spent.

func HitlKey

func HitlKey(toolCallID string) string

HitlKey is the handoff key an answer is written to.

func IsParked

func IsParked(output string) (toolCallID string, ok bool)

IsParked reports whether a tool output is the sentinel a parked RequiresConfirmation tool returns (§2.5), and which call it parks.

func ListRuns

func ListRuns(ctx context.Context, deps ports.RuntimePorts, filter ports.RunFilter) ([]ports.RunRecord, error)

ListRuns lists runs with a bounded default limit.

func ListSteps

func ListSteps(ctx context.Context, deps ports.RuntimePorts, runID string) ([]ports.StepRecord, error)

ListSteps is a run's steps, in order (§2.9).

func Logger

func Logger(deps ports.RuntimePorts) *slog.Logger

Logger is the platform's logger, defaulted.

func MarkPromptCaching

func MarkPromptCaching(messages []provider.Message) []provider.Message

MarkPromptCaching marks the stable prefix of a prompt for provider-side caching: the system message (if any) plus the last message of the history.

func MarkRequiresConfirmation

func MarkRequiresConfirmation(t ports.Tool) ports.Tool

MarkRequiresConfirmation marks a tool the engine treats as destructive: parked behind ParkForApproval (§2.5) instead of executing directly.

func MarshalPayload

func MarshalPayload(payload any) json.RawMessage

MarshalPayload encodes an event payload. A nil payload becomes JSON null.

func MessageFromDTO

func MessageFromDTO(m ports.MessageDTO) provider.Message

MessageFromDTO converts a stored turn into a goai message.

func MessagesFromDTOs

func MessagesFromDTOs(rows []ports.MessageDTO) []provider.Message

MessagesFromDTOs converts a stored history into goai messages.

func NewID

func NewID() string

NewID mints a random UUID v4.

func ParkForApproval

func ParkForApproval(ctx context.Context, deps ports.RuntimePorts, i ParkInput) error

ParkForApproval is the §2.5 suspension as a durable state transition. NO process waits. It flips WAITING_FOR_INPUT on both homes and appends INPUT_REQUIRED to the replayable event log (with the resume ticket). The engine then ends the run segment; Respond (or the expiry job below) resumes it via the queue.

The park also schedules its OWN expiry: one delayed dispatch of the same run, timed for just after the TTL. Without it the deadline only exists while somebody happens to be watching the thread. The delayed job holds no process; the queue holds it, exactly like the original dispatch (§2.8).

It carries the PARKED run's id, so the answer and the expiry are two deliveries of one run: whichever resolves the park first wins, and the run lock makes the other a no-op.

func ParkedResult

func ParkedResult(toolCallID string) string

ParkedResult is the sentinel a wrapped tool returns.

func PartsContent

func PartsContent(parts []ContentPart) json.RawMessage

PartsContent encodes a parts array as stored content.

func Publish

func Publish(ctx context.Context, deps ports.RuntimePorts, threadID, typ string, payload any) (ports.AgentEvent, error)

Publish persists to the replayable event log, then fans out live to all subscribers (§2.2). Seq comes from Kv.Incr, monotonic per thread (§3.4).

func PublishEvent

func PublishEvent(ctx context.Context, deps ports.RuntimePorts, threadID, typ string, payload any, opts PublishOptions) (ports.AgentEvent, error)

PublishEvent publishes an event of your own on a thread, through the same pipeline the platform's events take: the durable log and the live bus (§2.2). A client sees it in its event stream exactly like a built-in one. Platform event types are refused.

func PublishNotice

func PublishNotice(ctx context.Context, deps ports.RuntimePorts, threadID, typ string, payload any) error

PublishNotice publishes a bus-only notice (never persisted), e.g. HITL death notices (§2.5).

func ReclaimGraceAfter

func ReclaimGraceAfter(deps ports.RuntimePorts) time.Duration

ReclaimGraceAfter is the HITL TTL plus a small grace, so an in-flight answer always lands first and reclamation only ever sees true orphans.

func ReclaimIfOrphaned

func ReclaimIfOrphaned(ctx context.Context, deps ports.RuntimePorts, threadID string) (bool, error)

ReclaimIfOrphaned is §2.5 orphan reclamation, the FALLBACK path.

A park schedules its own expiry on the queue (see ParkForApproval), so the deadline holds whether or not anyone is watching. This covers what a timer cannot: threads parked before that existed, and queue adapters that drop a delay. Callers are first-touch checks in Run and Respond.

It does not heal inline. It re-dispatches the run and lets the engine resolve the park, so there is exactly ONE definition of what an expired approval becomes, and a thread holding several open approvals (§2.7) is resolved as a set. Re-dispatching the same run twice is safe: the run lock and the engine's readiness check make the duplicate a no-op (§2.8).

Returns true iff a re-dispatch was enqueued.

func RecordCall

func RecordCall(ctx context.Context, deps ports.RuntimePorts, threadID string, u ports.NewUsage) ports.NewUsage

RecordCall prices ONE model call and stores its usage row (§4). Called after every call the platform makes: a step of the main run, a step of a nested run, a compaction pass, streamed or not, finished or cut short.

Pricing happens here, before the row is stored, so cost sits on the row beside the tokens and no reader has to work it out again. A pricer that fails, or has nothing to say, leaves the row unpriced rather than failing the run: a bill that is short a line is recoverable, a run that died over a price list is not.

The write uses a context that a user stop cannot cancel, because the tokens of a stopped run were still spent. Storage failures are logged, not returned: the same reasoning.

func RedriveKey

func RedriveKey(threadID string) string

RedriveKey counts re-dispatches of a job that keeps finding the run lock held by an OLDER run (§2.8). Separate from the attempts key: a blocked job has not failed, it simply has not started yet.

func RepairDanglingToolCalls

func RepairDanglingToolCalls(msgs []provider.Message) []provider.Message

RepairDanglingToolCalls closes every assistant tool call that has no tool result before the next turn, with a synthetic result saying so.

History can carry such a call legitimately: a run that was stopped while parked for approval persisted the call and never its result, or a worker died between the two. Strict providers (OpenAI, Anthropic) reject a prompt with a dangling call outright, which would wedge the thread on every later run. The repair is prompt-side only; nothing is written back.

func RequireConfirmation

func RequireConfirmation(t goai.Tool) ports.Tool

RequireConfirmation is MarkRequiresConfirmation for a plain goai tool.

func Respond

Respond is the §5.4 behavior: heal orphans first (§2.5), then record the answer in the handoff key and resume the run segment via the queue (§2.8). The resumed worker appends the tool result and continues the loop.

func Run

Run is the §5.1 behavior: heal orphans → billing pre-check (§4) → persist the user message → state RUNNING (hot + durable) → enqueue on the dispatch queue (§2.8). It accepts no execution responsibility whatsoever; the queue does the rest, and the job dispatches back to THIS handle.

func RunIDFromContext

func RunIDFromContext(ctx context.Context) string

RunIDFromContext reads the run a context serves: the dispatched run for the main agent, the nested run's own id inside a subagent. Empty outside a run.

func RunIDKey

func RunIDKey(threadID string) string

RunIDKey holds the thread's CURRENT run id (§2.1).

Stop and start-a-new-run both write the state key, so the state key alone can never tell a worker its run is over: a user who stops and then sends another message overwrites CANCELLED with RUNNING before the worker's poll ever reads it. This key only moves forward. A worker whose id no longer matches knows it has been replaced, whatever the state key says.

func RunLockKey

func RunLockKey(threadID string) string

RunLockKey is the per-thread run lock (§3.4).

func RunStateFromContext

func RunStateFromContext(ctx context.Context) ports.AgentRunState

RunStateFromContext reads the run's state inside a tool's Execute (§2.10). Present for every tool of every run, including a nested one and a segment resumed after an approval. Never nil.

func SSEFrame

func SSEFrame(e ports.AgentEvent) string

SSEFrame encodes one event as an SSE frame.

A bus-only notice (seq 0) is sent WITHOUT an id line. EventSource stores any id it sees and sends it back as Last-Event-ID on reconnect, so stamping id: 0 on a heartbeat would rewind the client's cursor to the beginning of the thread and replay everything.

func SeqKey

func SeqKey(threadID string) string

SeqKey is the per-thread event sequence counter (§3.4).

func SetThreadState

func SetThreadState(ctx context.Context, deps ports.RuntimePorts, threadID string, state ports.ExecutionState, model string) error

SetThreadState moves a thread to a new state on BOTH the caller's storage and the platform's own operational view (§2.9).

One choke point on purpose: the admin thread table is what lets a dashboard answer "what is running right now" without reading the caller's database, and it is only true if every transition passes through here. Model is looked up when empty, so callers that already hold the thread can skip a read.

func SpawnSubagentTool

func SpawnSubagentTool(sctx *SubagentCtx) ports.Tool

SpawnSubagentTool builds the run-scoped delegation tool (§2.7).

func StateKey

func StateKey(threadID string) string

StateKey is the hot copy of a thread's state (§2.1, §3.4).

func Stop

func Stop(ctx context.Context, deps ports.RuntimePorts, threadID string) (ports.StopResult, error)

Stop is the whole stop mechanism (§2.1): one button, one behavior. The engine's poller sees CANCELLED on the hot cache and cancels the run; the durable state is the recovery truth (§3.4).

func SystemCacheMessage

func SystemCacheMessage(system string) provider.Message

SystemCacheMessage is a system prompt in the one shape that can carry a cache breakpoint: a message with a stamped part. As goai's WithSystem string it reaches the provider with no metadata channel and never caches, and it is usually the largest, most stable part of the prompt.

func TextContent

func TextContent(s string) json.RawMessage

TextContent encodes plain text as stored content.

func ToolCallIDsIn

func ToolCallIDsIn(content json.RawMessage) []string

ToolCallIDsIn lists the tool-call ids a stored tool message answers.

func ToolResultContent

func ToolResultContent(toolCallID, toolName string, result any) json.RawMessage

ToolResultContent is a tool message carrying one result, the shape the resumed segment appends after an approval (§2.5).

func UserContent

func UserContent(text string, attachments []ports.Attachment) json.RawMessage

UserContent encodes a user turn: plain text alone, or text plus the images attached to it (§5.1).

func ValidateTokenBudget

func ValidateTokenBudget(value int, label string) error

ValidateTokenBudget: the safety cap (§2.1) must be either zero (unbounded apart from MaxSteps) or positive.

func WithHitl

func WithHitl(deps ports.RuntimePorts, threadID string, tools []ports.Tool, hc HitlCtx) []ports.Tool

WithHitl wraps every marked tool so a call parks (§2.5) instead of executing: the request is persisted as INPUT_REQUIRED and the wrapper returns the park sentinel. Nothing blocks. The real tool runs when the park is resolved (see resumePendingHitl), in whichever stream owns it.

Shared by the main agent and every nested run (§2.7): the only difference is the AgentID asking and the Frames waiting on the answer.

func WithPublishEvent

func WithPublishEvent(deps ports.RuntimePorts, threadID string, tools []ports.Tool) []ports.Tool

WithPublishEvent gives every tool an EventPublisher through its context, bound to the thread it runs on: main agent, nested run, or a segment resumed after an approval alike. Read it with ToolContextFrom.

func WithRunState

func WithRunState(tools []ports.Tool, state ports.AgentRunState) []ports.Tool

WithRunState gives every tool the run's state through its context (§2.10). goai calls Execute(ctx, input); this puts the state on that ctx so a tool reads it exactly where it already reads its tool-call id. Applied to the whole toolset, not just the marked ones: a tool that does not need approval still needs to know which tenant it is acting for.

Types

type AdminOverview

type AdminOverview struct {
	Runs RunStats `json:"runs"`
	// Threads by state, from the platform's own view (§2.9).
	Threads map[ports.ExecutionState]int `json:"threads"`
	// RunsByState is every run ever, by state, unbounded by the stats window.
	RunsByState map[ports.ExecutionState]int `json:"runsByState"`
	// Active are runs still in flight, newest first.
	Active []ports.RunRecord `json:"active"`
}

AdminOverview is the top of an operational view.

func Overview

func Overview(ctx context.Context, deps ports.RuntimePorts, since *time.Time) (AdminOverview, error)

Overview assembles the top of an operational view.

type AgentArgs

type AgentArgs struct {
	System      string
	SystemFn    ports.SystemFunc
	PrepareStep ports.PrepareStepFunc
	Tools       []ports.Tool
	Options     []goai.Option
	OnChunk     func(provider.StreamChunk)
	OnSettle    ports.SettleFunc
	OnFinish    func(ports.RunFinishInfo)
}

AgentArgs are the user's generation args: applied first, platform keys last (§3.1).

type Approval

type Approval struct {
	Payload json.RawMessage
}

Approval is what the human sent back with an approval (§2.5): answers to the questions the tool asked, a corrected value, a reason.

func ApprovalFromContext

func ApprovalFromContext(ctx context.Context) *Approval

ApprovalFromContext reads the approval a resumed tool was given, or nil on a first, live call.

type ContentPart

type ContentPart struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
	// Signature is a provider's proof over a reasoning part (Anthropic
	// extended thinking). Kept so the block can be replayed: within a tool
	// loop Anthropic requires the thinking block back, signed.
	Signature string `json:"signature,omitempty"`
	// Data is a redacted reasoning block's encrypted payload.
	Data       string          `json:"data,omitempty"`
	ToolCallID string          `json:"toolCallId,omitempty"`
	ToolName   string          `json:"toolName,omitempty"`
	Args       json.RawMessage `json:"args,omitempty"`
	Result     json.RawMessage `json:"result,omitempty"`
	// Image is an image part's URL (or data: URL), the AI SDK field name.
	Image    string `json:"image,omitempty"`
	MimeType string `json:"mimeType,omitempty"`
}

ContentPart is one element of a stored parts array.

func ParseContent

func ParseContent(content json.RawMessage) []ContentPart

ParseContent decodes stored content into parts. Plain text and the summary envelope come back as one text part.

type EventPublisher

type EventPublisher func(ctx context.Context, typ string, payload any, opts PublishOptions) (ports.AgentEvent, error)

EventPublisher is what a tool calls to publish, already bound to the thread the tool is acting on.

func PublisherFromContext

func PublisherFromContext(ctx context.Context) EventPublisher

PublisherFromContext reads the EventPublisher a tool was given, or nil outside a run.

func ThreadPublisher

func ThreadPublisher(deps ports.RuntimePorts, threadID string) EventPublisher

ThreadPublisher binds PublishEvent to one thread.

type EventStream

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

EventStream is every event on a thread, replay first and then live, as one sequence. Read Events() until it closes, then check Err().

func FollowEvents

func FollowEvents(ctx context.Context, deps ports.RuntimePorts, threadID string, opts FollowOptions) (*EventStream, error)

FollowEvents streams a thread's events, replay then live.

The ordering here is the whole point, and it is easy to get wrong in a route handler:

  1. Subscribe before replaying. An event published between the replay finishing and the tail starting is otherwise lost for ever.
  2. Never emit at or below the cursor. The client would render it twice.
  3. seq == 0 is a bus-only notice (heartbeats, death notices). Always forward it, never let it move the cursor.

func (*EventStream) Err

func (s *EventStream) Err() error

Err reports why the stream stopped, once Events() is closed. Nil for a plain cancellation.

func (*EventStream) Events

func (s *EventStream) Events() <-chan ports.AgentEvent

Events is the channel of admitted events. It closes when the context is cancelled or the replay failed.

type ExecuteFunc

type ExecuteFunc func(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, input ExecuteInput) (ExecuteOutcome, error)

ExecuteFunc is the signature of Execute, an injection seam for tests.

type ExecuteInput

type ExecuteInput struct {
	ThreadID string
	Model    string
	// RunID is this dispatch's run id (§2.1). A job without one keeps the
	// old behavior: no staleness check, and no redrive on a lock conflict.
	RunID string
	// EnqueuedAt is epoch ms at enqueue, for the queue-wait measurement (§2.9).
	EnqueuedAt int64
	// State is the run's state (§2.10), carried so a redrive keeps it.
	State       ports.AgentRunState
	TokenBudget int
	// CostBudgetMicros is the run's money cap (§4), carried on the dispatch
	// so the worker enforces what the caller asked for.
	CostBudgetMicros int64
	ProviderOptions  ports.ProviderOptions
	// MaxSteps is the run's own step cap; zero keeps the config's (§2.1).
	MaxSteps int
}

ExecuteInput is what the worker hands the engine.

type ExecuteOutcome

type ExecuteOutcome string

ExecuteOutcome says what Execute did.

const (
	// OutcomeExecuted: this worker ran the segment (or it was a legitimate no-op).
	OutcomeExecuted ExecuteOutcome = "executed"
	// OutcomeLockConflict: someone else holds the thread's run lock; nothing ran.
	OutcomeLockConflict ExecuteOutcome = "lock-conflict"
	// OutcomeStale: a NEWER run owns the thread; this job must do nothing.
	OutcomeStale ExecuteOutcome = "stale"
)

func Execute

Execute is the engine (§2.1, §5.6). Worker-side only: runs are dispatched via the queue (§2.8) and may outlive any HTTP response.

Execution is a platform-owned loop of single-round-trip steps: after EVERY step the produced messages are persisted, so a worker that dies mid-run resumes from the last step, and every continuation decision is made between steps, never inside goai.

Concurrency: acquires the per-thread run lock (SET NX + lease) before any work. Two workers can never run one thread, and a crashed worker's lock expires instead of blocking forever (§3.4).

type FinalizeInput

type FinalizeInput struct {
	State ports.ExecutionState
	// StopReason is 'completed' | 'token_budget' | 'max_steps' | 'cancelled'.
	StopReason  string
	TokensUsed  int
	Attribution TokenAttribution
	// OneShotText: generate-text flavor only, published as one TEXT_RESULT.
	OneShotText *string
	// RunID is the run this finalize speaks for (§2.1). State is written only
	// while that run is still the thread's current one.
	RunID string
	// Steps is the loop iterations this segment completed (§2.9).
	Steps int
	// Error is why it failed, when it did (§2.9).
	Error string
}

FinalizeInput is how a run ended.

type FollowOptions

type FollowOptions struct {
	// Since resumes after this seq. 0 replays the thread from the start. It
	// comes from the client's cursor: Last-Event-ID for SSE.
	Since int64
}

FollowOptions tunes FollowEvents. The context passed to FollowEvents is the abort signal: cancel it, or the subscription outlives the client.

type Handle

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

Handle is an executor bound to a generation flavor and to the user's generation arguments (§3). Returned by the Create*Agent factories.

func NewGenerateTextAgent

func NewGenerateTextAgent(scope ScopeFn, spec ports.GenerateTextAgentSpec) *Handle

NewGenerateTextAgent registers a generate-text handle.

func NewStreamTextAgent

func NewStreamTextAgent(scope ScopeFn, spec ports.StreamTextAgentSpec) *Handle

NewStreamTextAgent registers a stream-text handle.

func (*Handle) Agent

func (h *Handle) Agent() *RegisteredAgent

Agent exposes the registry entry.

func (*Handle) Execute

func (h *Handle) Execute(ctx context.Context, input ExecuteInput) (ExecuteOutcome, error)

Execute is worker-side only (§5.6). Returns OutcomeLockConflict when another worker owns the thread's run lock (nothing was executed) and OutcomeStale when a newer run has replaced this one (§2.1, §2.8).

func (*Handle) ExecuteWithPolicy

func (h *Handle) ExecuteWithPolicy(ctx context.Context, input ExecuteInput, policy *Policy) error

ExecuteWithPolicy is Execute + the §2.8 failure policy.

func (*Handle) Kind

func (h *Handle) Kind() ports.AgentKind

Kind is the generation flavor.

func (*Handle) Name

func (h *Handle) Name() string

Name is the handle's registry key.

func (*Handle) Run

func (h *Handle) Run(ctx context.Context, input ports.RunInput) (ports.RunResult, error)

Run persists the user message → state RUNNING → enqueues a job dispatched back to THIS handle.

func (*Handle) Stop

func (h *Handle) Stop(ctx context.Context, threadID string, state ports.AgentRunState) (ports.StopResult, error)

Stop is the platform stop (§2.1); works regardless of which agent's run is active.

type HitlCtx

type HitlCtx struct {
	Resume  ports.ResumeInfo
	AgentID string
	Frames  []HitlFrame
	Nested  *ports.NestedDescriptor
}

HitlCtx is what WithHitl needs to know about the stream it wraps.

type HitlFrame

type HitlFrame struct {
	AgentID    string `json:"agentId"`
	ToolCallID string `json:"toolCallId"`
	// Nested says how to re-enter the owner's loop when this frame unwinds.
	// Absent for the main agent, whose loop the engine re-enters itself.
	Nested *ports.NestedDescriptor `json:"nested,omitempty"`
}

HitlFrame is one tool call left waiting on an approval further down (§2.7). A park by the main agent has none; a park inside a nested run has one per level, the innermost waiter first. AgentID names the stream the waiting call lives in; empty for the main agent.

func (HitlFrame) MarshalJSON

func (f HitlFrame) MarshalJSON() ([]byte, error)

MarshalJSON writes the main agent's empty AgentID as null, matching the TypeScript package's persisted payloads.

type HitlResponse

type HitlResponse struct {
	Approved bool `json:"approved"`
	Payload  any  `json:"payload,omitempty"`
}

HitlResponse is what /respond writes to the handoff key.

type LoopInput

type LoopInput struct {
	// AgentID is whose stream this loop persists to (§2.7). Empty is the
	// main agent.
	AgentID string
	// RunID is the run these steps belong to (§2.9).
	RunID string
	Kind  ports.AgentKind
	Model provider.LanguageModel
	// Messages is the seeded context: compacted history for the main agent,
	// the brief plus its own persisted turns for a nested run.
	Messages []provider.Message
	Tools    []ports.Tool
	MaxSteps int
	// GenCtx is the context the model call runs under. It is cancelled by a
	// user stop (§2.1). Storage calls use the loop's own ctx, so a stopped run
	// can still be finalized.
	GenCtx context.Context
	// Aborted reports whether the platform cancelled GenCtx on purpose.
	Aborted         func() bool
	ProviderOptions ports.ProviderOptions
	// TokenBudget is the cumulative cap for the whole run, checked against
	// the shared ledger.
	TokenBudget int
	// CostBudgetMicros is the money cap for the whole run (§4), checked
	// against the same shared ledger and between the same steps.
	CostBudgetMicros int64
	// BillingRunID is the DISPATCHED run every call here is billed to (§4).
	// A nested loop's RunID is its own; this stays the parent's, so one
	// run's whole bill, delegated work included, is a single query.
	BillingRunID string
	// ModelKey is the registry key the model was resolved from — what a
	// price list is usually keyed by.
	ModelKey string
	// ModelID is the wire id that key resolved to (ResolvedModel.WireID),
	// for a price list keyed by wire ids instead.
	ModelID string
	// AgentName is the name that goes on the bill line: the registered
	// handle for the main run, the delegation's name for a nested one.
	AgentName string
	OnChunk   func(provider.StreamChunk)
	// System is the persona for a nested run; empty keeps the spec's.
	System string
	// SystemFn builds the persona per step (§3.1); it wins over System and
	// over the spec's.
	SystemFn ports.SystemFunc
	// PrepareStep edits the prompt per step; what it adds is never persisted.
	PrepareStep ports.PrepareStepFunc
	// State is the run's state, handed to SystemFn (§2.10).
	State             ports.AgentRunState
	CacheSystemPrompt bool
}

LoopInput seeds a loop.

type LoopOutcome

type LoopOutcome struct {
	Text         string
	FinishReason provider.FinishReason
	// Attribution is what THIS loop spent; the caller records it against its
	// own AgentID.
	Attribution TokenAttribution
	TokensUsed  int
	// Parked: a RequiresConfirmation tool parked and the segment ends (§2.5).
	Parked           bool
	ParkedToolCallID string
	// Aborted: the platform cancelled the run mid-loop, a user stop (§2.1).
	Aborted bool
	// Steps is the iterations this loop completed (§2.9).
	Steps int
	// CostExhausted: the run hit its money cap and stopped between steps (§4).
	CostExhausted bool
}

LoopOutcome is how a loop ended.

func RunLoop

func RunLoop(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, threadID string, input LoopInput, ledger *RunLedger) (*LoopOutcome, error)

RunLoop is the platform-owned loop (§2.1, §5.6), run by the main agent and by every nested run alike (§2.7).

One single-round-trip step per iteration. After EVERY step the produced messages are persisted under this loop's AgentID, so a worker that dies mid-run resumes from the last step, and so a parked nested run can be re-entered later instead of restarted. Every continuation decision (tool results ready, budget spent, step ceiling, HITL park, user stop) is made here between steps, never inside goai.

func RunNestedAgent

func RunNestedAgent(genCtx context.Context, sctx *SubagentCtx, d ports.NestedDescriptor, instructions *string, frames []HitlFrame) (*LoopOutcome, error)

RunNestedAgent runs, or RE-ENTERS, a nested agent (§2.7).

Its turns live in the thread's message log under its own AgentID, so a child that parked is resumed from exactly where it stopped rather than replayed from its brief. Replaying an LLM call is not a safe substitute: the model can take a different path and never make the call the human approved, and it re-pays for everything before the park.

genCtx is the context the child's model calls run under (cancelled by a user stop); storage calls use the spawner's IOCtx.

type ParkInput

type ParkInput struct {
	ThreadID   string
	ToolCallID string
	ToolName   string
	Args       json.RawMessage
	AgentID    string
	// Frames are the calls waiting on this answer, innermost first (§2.7).
	Frames []HitlFrame
	// Nested is the run that raised this park; nil when the main agent did.
	Nested *ports.NestedDescriptor
	// Resume is the dispatch ticket persisted in the INPUT_REQUIRED payload.
	Resume ports.ResumeInfo
}

ParkInput describes a park.

type PendingHitl

type PendingHitl struct {
	ToolCallID string
	ToolName   string
	AgentID    string
	Arguments  json.RawMessage
	// Frames are the calls waiting on this answer, innermost first (§2.7).
	Frames []HitlFrame
	// Nested is the run that raised it; nil for a main-agent park.
	Nested *ports.NestedDescriptor
	// RequestedAt is when INPUT_REQUIRED was published: the TTL clock (§2.5).
	RequestedAt time.Time
	// Resume is the dispatch ticket, when the park recorded one.
	Resume *ports.ResumeInfo
}

PendingHitl is the pending request behind a WAITING_FOR_INPUT thread, hydrated from the durable event log (§2.5).

func LoadOpenHitls

func LoadOpenHitls(ctx context.Context, deps ports.RuntimePorts, threadID string) ([]PendingHitl, error)

LoadOpenHitls lists every approval on the thread that is still open (§2.7).

Derived from durable state, never cached: a request is settled once a tool result carries its ToolCallID, in whichever stream owns it, or an INPUT_EXPIRED event names it. Both are already written on the settling path.

func LoadPendingHitl

func LoadPendingHitl(ctx context.Context, deps ports.RuntimePorts, threadID string) (*PendingHitl, error)

LoadPendingHitl reads the most recent pending request.

type Percentiles

type Percentiles struct {
	P50 int64 `json:"p50"`
	P95 int64 `json:"p95"`
	Max int64 `json:"max"`
}

Percentiles summarise a set of durations.

type Policy

type Policy struct {
	MaxAttempts int
	Exec        ExecuteFunc
}

Policy tunes ExecuteWithPolicy. Zero MaxAttempts means the config's; nil Exec means Execute.

type PublishOptions

type PublishOptions struct {
	// Notice sends the event over the bus only (seq 0), never to the log: a
	// progress tick, a typing indicator, anything nobody needs to see twice.
	// The default writes it to the thread's log, so a reconnecting client
	// replays it.
	Notice bool
}

PublishOptions tunes PublishEvent.

type RegisteredAgent

type RegisteredAgent struct {
	Name string
	Kind ports.AgentKind
	Spec SpecDefaults
	Args AgentArgs
	Sem  *Semaphore
}

RegisteredAgent is the registry entry behind a handle: the bound generation flavor, the spec-level defaults, and the user's generation args.

type RunDetail

type RunDetail struct {
	Run   ports.RunRecord    `json:"run"`
	Steps []ports.StepRecord `json:"steps"`
	// Subagents are the nested runs spawned beneath it (§2.7).
	Subagents []ports.RunRecord `json:"subagents"`
	// Events are the run's events with CHUNKs stripped: the readable spine.
	Events []ports.AgentEvent `json:"events"`
	// Usage is what this run spent, nested runs included (§4): tokens, money,
	// and a line per agent and model. Read from the usage rows, so it is the
	// same number a bill is built from.
	Usage ports.UsageTotals `json:"usage"`
}

RunDetail is everything about one run, assembled for a timeline view.

func GetRun

func GetRun(ctx context.Context, deps ports.RuntimePorts, runID string) (*RunDetail, error)

GetRun assembles one run for a timeline view. Nil when unknown.

type RunLedger

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

RunLedger is the tokens a run has spent, main agent and nested runs together (§2.7). Shared so a child's spend counts against the run's safety cap the moment it happens.

func (*RunLedger) Add

func (l *RunLedger) Add(n int)

Add books tokens onto the ledger.

func (*RunLedger) TokensUsed

func (l *RunLedger) TokensUsed() int

TokensUsed reads the ledger.

type RunStats

type RunStats struct {
	Total        int                          `json:"total"`
	ByState      map[ports.ExecutionState]int `json:"byState"`
	ByStopReason map[string]int               `json:"byStopReason"`
	Tokens       ports.UsageTotals            `json:"tokens"`
	// Duration is wall time from enqueue to finish, over runs that ended. A
	// parked run legitimately includes however long the human took (§2.5).
	Duration *Percentiles `json:"duration"`
	// Queued is time spent waiting for a worker: the backlog signal (§2.8).
	Queued *Percentiles `json:"queued"`
	Failed int          `json:"failed"`
}

RunStats summarise a window of runs (§2.9).

func RunStatsFor

func RunStatsFor(ctx context.Context, deps ports.RuntimePorts, r StatsRange) (RunStats, error)

RunStatsFor computes stats over a window. Percentiles are computed here rather than pushed into the store, so a store only ever writes filters it can express in one indexed query.

func Summarise

func Summarise(runs []ports.RunRecord) RunStats

Summarise rolls a set of runs into stats.

type SSEOptions

type SSEOptions struct {
	FollowOptions
	// RetryMs is emitted once, up front: how long a browser waits before
	// reconnecting. Zero omits it.
	RetryMs int
}

SSEOptions tunes ToSSEStream.

type SSEStream

type SSEStream struct {
	Headers map[string]string
	// contains filtered or unexported fields
}

SSEStream is the event sequence, encoded as Server-Sent Events. It is a WriterTo and an http.Handler rather than a Response, because half the ecosystem has its own response type.

func ToSSEStream

func ToSSEStream(events *EventStream, opts SSEOptions) *SSEStream

ToSSEStream wraps an EventStream for SSE.

func (*SSEStream) Err

func (s *SSEStream) Err() error

Err reports why the underlying stream stopped.

func (*SSEStream) ServeHTTP

func (s *SSEStream) ServeHTTP(w http.ResponseWriter, _ *http.Request)

ServeHTTP sets the SSE headers and writes the stream. Create the stream with the request's context so a hang-up unsubscribes.

func (*SSEStream) WriteTo

func (s *SSEStream) WriteTo(w io.Writer) (int64, error)

WriteTo writes frames until the stream ends, flushing after each one when w is an http.Flusher.

type ScopeFn

type ScopeFn func(state ports.AgentRunState, runID string) ports.RuntimePorts

ScopeFn resolves the ports for one call, binding that call's state to storage (§2.10). A handle outlives many runs, so it cannot hold fixed ports.

type Semaphore

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

Semaphore is a run-scoped concurrency cap: sibling subagents queue instead of running away (§2.7).

func NewSemaphore

func NewSemaphore(limit int) *Semaphore

NewSemaphore makes a semaphore with limit slots.

func (*Semaphore) Acquire

func (s *Semaphore) Acquire(ctx context.Context) (release func(), err error)

Acquire takes a slot, waiting for one. The release is idempotent.

type SpecDefaults

type SpecDefaults struct {
	Model            string
	Subagents        *ports.SubagentsConfig
	TokenBudget      int
	CostBudgetMicros int64
	ProviderOptions  ports.ProviderOptions
}

SpecDefaults are the spec-level defaults the engine reads.

type StatsRange

type StatsRange struct {
	Since *time.Time
	Until *time.Time
	Limit int
}

StatsRange bounds a stats query.

type StepCall

type StepCall struct {
	Kind            ports.AgentKind
	Model           provider.LanguageModel
	Messages        []provider.Message
	Tools           []ports.Tool
	ProviderOptions ports.ProviderOptions
	OnChunk         func(provider.StreamChunk)
	// System overrides the spec's persona: a nested run brings its own and
	// must not inherit the parent's (§2.7). Empty keeps the spec's.
	System string
	// CacheSystemPrompt moves the system prompt into Messages as a stamped
	// message so it can carry a cache breakpoint (§2.6).
	CacheSystemPrompt bool
}

StepCall is what ExecuteStep needs.

type StepResult

type StepResult struct {
	Text         string
	FinishReason provider.FinishReason
	Usage        provider.Usage
	// ResponseMessages are the assistant + tool messages this step produced,
	// appended to the conversation (in memory AND storage) before the next step.
	ResponseMessages []provider.Message
	ToolCalls        []provider.ToolCall
	ToolResults      []provider.ToolResult
	// ProviderMetadata is what the provider attached to the finish, one entry
	// per provider namespace, plus two reserved keys: "responseId" and
	// "responseHeaders". Gateways put a call's real cost in a header, so a
	// receipt pricer reads it from there (§4).
	ProviderMetadata map[string]any
	// StreamedText is what actually reached the client before the call ended.
	// Set even when the call failed or was stopped mid-stream, so the tokens
	// of a cut-off call can still be estimated and billed.
	StreamedText string
	// Finished is false when no finish ever arrived: the stream was cut off
	// by a stop or a provider failure, and the counters are not the
	// provider's own.
	Finished bool
}

StepResult is one platform-owned step (§2.1, §5.6): a single round-trip. goai executes the step's tool calls and reports a structured result; whether to continue is the loop's decision, never goai's.

func ExecuteStep

func ExecuteStep(ctx context.Context, agent *RegisteredAgent, call StepCall) (*StepResult, error)

ExecuteStep runs ONE round-trip. goai only runs a step's tools inside its own loop, and that loop needs MaxSteps > 1, so the step asks for two and stops before the second: the tools of step one run, and the loop here decides what happens next.

Ownership rule (§3.1): the user's options are applied FIRST, the platform's LAST, so goai can never be handed a different model, prompt or step ceiling than the platform decided on.

type SubagentCtx

type SubagentCtx struct {
	// IOCtx is the parent's storage context: not cancelled by a user stop, so
	// a stopped child can still close its record.
	IOCtx    context.Context
	ThreadID string
	Depth    int // 0 = called from the main agent
	Sem      *Semaphore
	Ports    ports.RuntimePorts
	// Sub is the delegation config carried from the parent's spec.
	Sub ports.SubagentsConfig
	// Agent is the registered agent whose generation args every nested run
	// inherits (§3.1); its System and Tools are overridden per child.
	Agent  *RegisteredAgent
	Ledger *RunLedger
	// Resume is the dispatch ticket persisted with any park raised beneath here.
	Resume ports.ResumeInfo
	// AgentID is the stream this spawner writes to; empty for the main agent.
	AgentID string
	// Frames are calls already waiting on an approval above this level.
	Frames []HitlFrame
	// Descriptor is this spawner's own; nil when it is the main agent.
	Descriptor  *ports.NestedDescriptor
	TokenBudget int
	// CostBudgetMicros is the run's money cap, shared with the parent (§4).
	CostBudgetMicros int64
	// BillingRunID is the DISPATCHED run every call beneath here is billed
	// to, so one run's bill is one query however deep the delegation went.
	BillingRunID    string
	ProviderOptions ports.ProviderOptions
	// Aborted reports a user stop (§2.1).
	Aborted func() bool
	// State is the run's state, handed down unchanged (§2.10).
	State ports.AgentRunState
}

SubagentCtx is everything a nested run needs from the run that spawned it (§2.7). The thread, lock, run id, abort and token ledger are the parent's; the message stream, step ceiling and toolset are the child's own.

type ThreadDetail

type ThreadDetail struct {
	Thread ThreadSummary      `json:"thread"`
	Runs   []ports.RunRecord  `json:"runs"`
	Steps  []ports.StepRecord `json:"steps"`
}

ThreadDetail is a thread opened up: its runs, and every step across them.

func GetThread

func GetThread(ctx context.Context, deps ports.RuntimePorts, threadID string) (*ThreadDetail, error)

GetThread opens one thread up: its runs and every step across them (§2.9). Nil when nothing was ever recorded for it.

type ThreadSummary

type ThreadSummary struct {
	ID          string               `json:"id"`
	State       ports.ExecutionState `json:"state"`
	Model       string               `json:"model"`
	FirstSeenAt time.Time            `json:"firstSeenAt"`
	UpdatedAt   time.Time            `json:"updatedAt"`
	// Runs on this thread, nested ones included.
	Runs   int               `json:"runs"`
	Steps  int               `json:"steps"`
	Tokens ports.UsageTotals `json:"tokens"`
	// DurationMs is summed run durations. Not wall time: nested runs overlap
	// their parent.
	DurationMs int64 `json:"durationMs"`
	// Prompt is what started it: the first dispatched run's prompt.
	Prompt string `json:"prompt,omitempty"`
	// StartedWith is the parameters that started it, as recorded on first
	// sight (§2.9); falls back to the earliest dispatched run in the window.
	StartedWith *ports.ThreadStart `json:"startedWith,omitempty"`
}

ThreadSummary is a thread with its runs rolled up (§2.9).

func ListThreads

func ListThreads(ctx context.Context, deps ports.RuntimePorts, filter ports.AdminThreadFilter) ([]ThreadSummary, error)

ListThreads lists threads with their runs rolled up, newest activity first (§2.9). One pass over the window's runs rather than a query per thread.

type TokenAttribution

type TokenAttribution = ports.UsageTotals

TokenAttribution is the four canonical counters (§4). Same shape as UsageTotals.

func AttributeTokens

func AttributeTokens(u provider.Usage) TokenAttribution

AttributeTokens turns one goai usage report into the four canonical counters.

goai already normalises the providers' disagreements about what "input tokens" means: for OpenAI-family models it subtracts the cached tokens from InputTokens, and Anthropic reports cache reads beside the input count. So InputTokens is always the fresh count and CacheReadTokens the cached one. TotalTokens is computed as input + cached + output so it means the same thing for every provider.

type ToolContext

type ToolContext struct {
	// State is whatever the caller attached to this run. Never nil.
	State ports.AgentRunState
	// ToolCallID identifies this call.
	ToolCallID string
	// PublishEvent publishes an event of your own on the thread the tool is
	// acting on: a progress label, a preview URL, anything a client should
	// react to. Durable by default, so a reconnecting client replays it;
	// PublishOptions{Notice: true} sends a bus-only notice. See the
	// "Custom events" guide.
	PublishEvent EventPublisher
	// Approval is present only when this call is the resumption of an
	// approved park (§2.5): whatever the human sent back with the approval.
	// Nil on a first, live call.
	Approval *Approval
}

ToolContext is what a tool's handler receives beside goai's own context: the run's state (§2.10) and a way to publish events on the thread.

func ToolContextFrom

func ToolContextFrom(ctx context.Context) ToolContext

ToolContextFrom rebuilds the ToolContext from a tool's context, for tools built with goai.NewTool by hand rather than AgentTool.

Jump to

Keyboard shortcuts

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