core

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 28 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 (
	WireAgentenkit = "agentenkit"
	WireAgUI       = "ag-ui"
)

Wire formats a follow can be sent in: our own frames (the default), or AG-UI events for a client built on that protocol.

View Source
const (
	FrameKindThread   = "thread"
	FrameKindStream   = "stream"
	FrameKindSnapshot = "snapshot"
)

Frame kinds.

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).

View Source
const ReasonApproval = "approval"

ReasonApproval marks a park raised by a RequiresConfirmation tool: a human decides. Any other reason is a tool that parked itself (§2.5): work it started and cannot wait for, resumed by whoever finishes that work.

View Source
const RecentEnd = time.Minute

RecentEnd is how long after its end a stream still rides on the snapshot.

View Source
const SettleClaimTTL = 10 * time.Minute

SettleClaimTTL is how long a settle claim holds (§5.6). A claim older than this belongs to a settler that died, and the next settle takes the run over.

View Source
const ThreadKeyTTL = 30 * 24 * time.Hour

ThreadKeyTTL is how long a thread's hot keys (state, current run, event seq) live after they were last written. The durable row is the truth; these only save a read, so a thread idle past this simply reads storage again, and its seq counter carries on from the stored events (see nextSeq). Without an expiry, every thread ever run keeps three keys in the kv for ever.

Variables

ActiveStates are the states a run is still going in: the ones a stop or a failure can end.

View Source
var BuiltinToolNames = []string{"web_search", "web_fetch", "bash", "code_execution", "text_editor"}

BuiltinToolNames are the built-in tools this runtime has.

View Source
var ErrRunLockLost = errors.New("agentenkit: run lock lost")

LoopInput seeds a loop. ErrRunLockLost ends a loop whose run lock was lost between steps (§3.4).

View Source
var RecordEventTypes = map[string]bool{
	"INPUT_REQUIRED": true, "INPUT_EXPIRED": true, "HITL_RESPONSE": true,
	"RUN_REFUSED": true, "TOKEN_BUDGET_EXHAUSTED": true, "COST_BUDGET_EXHAUSTED": true,
	"CONTEXT_COMPACTED": true, "MESSAGES_DROPPED": true,
	"RUN_STARTED": true, "RUN_ENDED": true,
}

RecordEventTypes are the platform's types that go in the thread record: what must outlive a run (see ports.EventStore). Every other platform type is live only: a notice on the bus, and an event on the run stream when one is open. The TS runtime has the same set.

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, "COST_BUDGET_EXHAUSTED": true,
	"RUN_STARTED": true, "RUN_ENDED": true, "RECORD_CHANGED": true, "SNAPSHOT": 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.

View Source
var StreamOnlyTypes = []string{
	"CHUNK", "SUBAGENT_CHUNK", "STEP_COMMITTED", "STEP_FINISHED", "TEXT_RESULT",
	"SUBAGENT_STARTED", "SUBAGENT_COMPLETED", "SUBAGENT_FAILED",
	"MESSAGE_APPENDED", "STATE_CHANGE", "HEARTBEAT",
}

StreamOnlyTypes are the types older releases kept in the event log that now live only on a run stream or the bus. Nothing reads them from the table any more, so they can go. An app's own types are never among them: there is no telling whether the app wanted one kept. The TS runtime has the same list.

Functions

func AgUIFrameSSE added in v0.4.0

func AgUIFrameSSE(f FollowFrame, cursor *ThreadCursor, st *AgUIState) (string, error)

AgUIFrameSSE is a frame as AG-UI events, one SSE message each; the frame's cursor rides on the first, so a reconnect resumes just as with our own frames.

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(runID string) string

AttemptsKey counts §2.8 failure retries of ONE run. Keyed by the run, so a new run on the thread starts with a full budget by construction and nothing an older run banked can reach it. A legacy job without a run id keys it by the thread instead; see CounterScope.

func BuildBuiltinTools added in v0.5.0

func BuildBuiltinTools(tp ports.BuiltinToolPorts, names []string, opts BuiltinToolOptions) ([]ports.Tool, error)

BuildBuiltinTools returns the built-in tools, ready for an agent's Tools. Each is an ordinary tool with a fixed name, description and input, so any model that can call tools can use it. A name this runtime does not know, or a tool whose port was not set up, is an error here, at startup.

func CallSafely added in v0.4.0

func CallSafely(fn func() error) (err error)

CallSafely runs fn and turns a panic into a *PanicError. A worker calls user code (handlers, hooks, tools) on goroutines of its own; one panic there must fail that job, not end the process and every job beside it.

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

func CloseLostSegment(ctx context.Context, deps ports.RuntimePorts, threadID, runID, reason string)

CloseLostSegment closes a segment's stream that its worker could not: the sweep's end for a run whose worker died. A stream already closed or gone is left as it is.

func CommitParks added in v0.4.0

func CommitParks(ctx context.Context, deps ports.RuntimePorts, box *ParkBox) error

CommitParks writes every park the box holds: WAITING_FOR_INPUT, the INPUT_REQUIRED request and its expiry job (see ParkForApproval). Called once the step that raised them is durable.

func CompactContext

func CompactContext(ctx context.Context, deps ports.RuntimePorts, threadID, model string, opts CompactOptions) ([]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.

The summary records the last message it covers, and the prompt carries the summary and only what came after (see PromptHistory), so a thread compacts once each time it grows past the trigger, not on every run.

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, coversUpTo string) json.RawMessage

ContextSummaryContent encodes a compaction summary envelope. coversUpTo is the id of the last message it summarizes: the prompt carries the summary and only what came after that message (see PromptHistory).

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

func ContextWithToolRun(ctx context.Context, run ToolRun) context.Context

ContextWithToolRun gives a tool call its ToolRun.

func CountTokens

func CountTokens(u provider.Usage) int

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

func CounterScope added in v0.3.0

func CounterScope(threadID, runID string) string

CounterScope is what the retry counters are keyed by: the run id, or the thread id for a legacy dispatch that has none.

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

func CutCommitted(items []ports.StreamItem) []ports.StreamItem

CutCommitted drops each agent's content up to its last finished step (see ports.SnapshotStream.Items).

func CutMiddle added in v0.5.0

func CutMiddle(text string, max int) (string, bool)

CutMiddle keeps the start and the end of text over max units (counted as JavaScript counts a string's length, UTF-16), with a line saying how much was cut from the middle: the start says what ran, the end holds the error. A character is never split. The TS runtime cuts the same.

func DecodeEntities added in v0.5.0

func DecodeEntities(s string) string

DecodeEntities turns the HTML entities the reader knows into text; any other is left as it is.

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:

  • QUEUED and RUNNING are refused: a job is on its way or 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. Its open run record is closed here, so it never counts as in flight again.

func DestroyThreadSandbox added in v0.5.0

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

DestroyThreadSandbox ends the thread's sandbox, when it has one. Part of deleting a thread; it never fails, since the thread is gone either way.

func EnqueueJob added in v0.4.0

func EnqueueJob(ctx context.Context, deps ports.RuntimePorts, job ports.RunJob, opts *ports.EnqueueOptions) error

EnqueueJob is the one way the platform puts a job on the queue: it stamps the job with a fresh DispatchID, so every enqueue is a delivery of its own and only the queue's own redelivery repeats one (§3.4).

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, each retry waiting longer than the last; exhausted attempts finalize FAILED (hot cache + durable). A user stop is never retried, a shutdown never costs an attempt, 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 FailLostRun added in v0.3.0

func FailLostRun(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, threadID, runID, reason string) (bool, error)

FailLostRun fails a run the queue gave up on (§2.8), when it is still the thread's current run and the thread is still waiting on it. Returns false when the run had already moved on. Runs under the run lock like every other terminal write.

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

func FollowFrameSSE(f FollowFrame, cursor *ThreadCursor) string

FollowFrameSSE is the SSE frame for a follow frame. A frame that moves the client's cursor carries it as its id:, so a browser that reconnects sends it back as Last-Event-ID; a notice carries none, and leaves it as it was.

func ForgetSandboxHandles added in v0.5.0

func ForgetSandboxHandles()

ForgetSandboxHandles drops every handle this process holds, as a fresh worker would start. For tests.

func FormatCursor added in v0.4.0

func FormatCursor(c ThreadCursor) string

FormatCursor is a cursor's wire form.

func HitlDoneKey added in v0.4.0

func HitlDoneKey(toolCallID string) string

HitlDoneKey keeps an approved tool's output until its result is saved (§2.5), so a retry lands the same output instead of running the tool again.

func HitlKey

func HitlKey(toolCallID string) string

HitlKey is the handoff key an answer is written to.

func IsActive added in v0.3.0

func IsActive(state ports.ExecutionState) bool

IsActive reports whether a thread state means a run is under way: waiting for a worker, running, or parked on a human (§2.1).

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

func IsPermanentError(err error) bool

IsPermanentError is true when err, or an error it wraps, is a provider error that retrying cannot fix. OpenAI says "no credits" with 429, the same status as a rate limit that does pass; only the body ("insufficient_quota") tells them apart. Anything else, including a rate limit, a server error, a dropped connection or a stream cut short, is worth another try.

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

func MediaTypeOf(path string) string

MediaTypeOf is the media type of a file a program made, from its name.

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 ParkForInput added in v0.2.1

func ParkForInput(req ParkRequest) error

ParkForInput is what a tool returns to park itself:

return "", agentenkit.ParkForInput(agentenkit.ParkRequest{Reason: "job", Payload: started, TTL: 30 * time.Minute})

The engine turns it into a durable park. A resumed call sees ApprovalFromContext(ctx) set and must return a result; a resumed call that parks again is reported to the model as a tool error.

func ParkedResult

func ParkedResult(toolCallID string) string

ParkedResult is the sentinel a wrapped tool returns.

func ParseLockValue added in v0.4.0

func ParseLockValue(v string) (runID, dispatchID string)

ParseLockValue splits a run lock value into the run and the delivery that hold it. A bare run id has no dispatch.

func PartsContent

func PartsContent(parts []ContentPart) json.RawMessage

PartsContent encodes a parts array as stored content.

func PromptHistory added in v0.4.0

func PromptHistory(history []ports.MessageDTO) []ports.MessageDTO

PromptHistory is the part of a stored history that goes to the model (§2.6): the latest compaction summary, then only the messages after the last one it covers. Everything before is in the summary already, and sending it again would undo the compaction. A summary written before the cover mark existed covers nothing known, so every summary is left out and the whole history goes; the next compaction writes a proper one.

func Publish

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

Publish publishes a platform event (§2.2). A record type is stored first (the store mints its seq) and then sent; any other type is sent as a notice. Either way it reaches the run stream this process has open on the thread.

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 (§2.2): the live bus, the run stream during a run (as CUSTOM), and the thread record when it is durable. A client sees it in its event stream exactly like a built-in one. Platform event types are refused.

func PublishFor added in v0.4.0

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

PublishFor is Publish for an entry that belongs to runID; empty takes the run the payload names.

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, and the stuck-run sweep.

It also covers a run the queue lost: a thread QUEUED or RUNNING whose run lock nobody holds and whose job the queue no longer has. A worker that died leaves exactly that behind once its lock lapses, and so does a job dropped as dead. The run is re-dispatched and resumes from its last persisted step, unless its record already ended, in which case the thread is moved to match the record.

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 or the thread was healed.

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.

A run's own calls go through its RunLedger.Record instead, which also holds the run to one currency and books the spend against its caps.

func RecordToolUsage added in v0.5.0

func RecordToolUsage(ctx context.Context, run ToolRun, u ports.NewUsage) ports.NewUsage

RecordToolUsage books one row of a tool's spend: on the run's ledger when there is one, so it counts against the run's caps, else stored on its own.

func RedriveKey

func RedriveKey(runID 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. Keyed by the run, like AttemptsKey.

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. It also drops every tool result whose call is not in the history before it (an orphan: its call was cut away, or the result was written first).

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

func Run(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, input ports.RunInput) (result ports.RunResult, runErr error)

Run is the §5.1 behavior: heal orphans → billing pre-check (§4) → persist the user message → state QUEUED (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. The worker that picks the job up moves the thread to RUNNING.

func RunBash added in v0.5.0

func RunBash(ctx context.Context, opts BashOptions, args map[string]any, run ToolRun) (string, error)

RunBash is the bash tool's work.

func RunCodeExecution added in v0.5.0

func RunCodeExecution(ctx context.Context, opts CodeExecutionOptions, args map[string]any, run ToolRun) (string, error)

RunCodeExecution is the code_execution tool's work.

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

func RunTextEditor(ctx context.Context, opts TextEditorOptions, args map[string]any, run ToolRun) (string, error)

RunTextEditor is the text_editor tool's work.

func RunWebFetch added in v0.5.0

func RunWebFetch(ctx context.Context, fetcher ports.Fetcher, opts WebFetchOptions, args map[string]any, run ToolRun) (string, error)

RunWebFetch is the web_fetch tool's work.

func RunWebSearch added in v0.5.0

func RunWebSearch(ctx context.Context, search ports.Search, opts WebSearchOptions, args map[string]any, run ToolRun) (string, error)

RunWebSearch is the web_search tool's work.

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

func SandboxKey(threadID string) string

SandboxKey is where the kv keeps a thread's sandbox.

func SegmentKey added in v0.4.0

func SegmentKey(runID string) string

SegmentKey is the segment counter: each pickup of a run takes the next number, so a retry or a resume gets a stream of its own.

func SeqKey

func SeqKey(threadID string) string

SeqKey is the per-thread event counter older releases kept in the kv. The thread record now mints its own seq; only a thread delete still clears it.

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 SettleLate added in v0.3.0

func SettleLate(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, threadID, runID string) (bool, error)

SettleLate settles an ended run whose settle never ran (§5.6), under the run lock. Returns false when the run was settled meanwhile or a worker holds it.

func SnapshotStreamOf added in v0.4.0

func SnapshotStreamOf(ctx context.Context, deps ports.RuntimePorts, threadID string) (*ports.SnapshotStream, error)

SnapshotStreamOf is the thread's current run stream, from the thread record: the latest segment that started, while it is open or only just ended. Nil when there is none, or it is gone.

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).

It knows no agents, so a run it ends without a worker is not settled; a handle's Stop, or StopRun with a resolver, is the one to call for that.

func StopRun added in v0.2.3

func StopRun(ctx context.Context, deps ports.RuntimePorts, threadID string, opts StopOptions) (ports.StopResult, error)

StopRun is Stop with the agent resolver a settle needs.

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

func ThreadSnapshotOf(ctx context.Context, deps ports.RuntimePorts, threadID, afterMessageID string) (*ports.ThreadSnapshot, error)

ThreadSnapshotOf is one read for a UI: the thread, its messages, its runs, the unfinished run's record entries and its run stream. Nil when the thread is gone. afterMessageID keeps only the messages after that one: what a tab that already has it is missing (a SNAPSHOT frame). An id the thread does not have keeps them all.

func ToAgUI added in v0.4.0

func ToAgUI(f FollowFrame, st *AgUIState) ([]map[string]any, error)

ToAgUI is a follow frame as AG-UI events. Our stream events already follow AG-UI, so most keep their shape and only a few fields are renamed; what AG-UI has no event for (a park, a subagent, a thread notice, a snapshot) goes out as CUSTOM with our name. The TS runtime sends the same (src/core/agui.ts).

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

func ToolUseRow(tool, adapter string, uses int, seconds ...float64) ports.NewUsage

ToolUseRow is a usage row for one use of a paid tool service: no tokens, the tool and the adapter named where a price table looks.

Seconds, when given, is the sandbox time the call took, for a per-second price.

func Transition added in v0.4.0

func Transition(ctx context.Context, deps ports.RuntimePorts, threadID string, c StateChange) (bool, error)

Transition is the one way a run moves its thread's state (§3.4). It is a compare-and-set on the durable row, on the state AND the run that owns the thread, and only the caller that wins it writes the hot cache and the admin view. So a stop is never overwritten by a finish, and a stopped or replaced run can never move the thread again: its change simply loses. Returns whether this caller made the change. Publishing the STATE_CHANGE is left to the caller, whose payload differs per change.

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 tool so a call can park (§2.5) instead of blocking. A marked tool parks BEFORE it runs: the request is persisted as INPUT_REQUIRED and the wrapper returns the park sentinel; the real tool runs when a human answers (see resumePendingHitl), in whichever stream owns it. Any other tool may park ITSELF by returning ParkForInput after starting work it cannot wait for; the same machinery resumes it with the responder's payload. Nothing blocks either way.

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.

func WithSandbox added in v0.5.0

func WithSandbox[T any](ctx context.Context, fn func(ThreadSandbox) (T, error)) (T, error)

WithSandbox runs fn on the thread's sandbox. When the sandbox turns out to be gone part way (it ended on its own), a fresh one is made and fn runs once more, told Lost.

func WithThreadSandbox added in v0.5.0

func WithThreadSandbox[T any](ctx context.Context, run ToolRun, fn func(ThreadSandbox) (T, error)) (T, error)

WithThreadSandbox is WithSandbox for a ToolRun in hand.

func WithToolRun added in v0.5.0

func WithToolRun(tools []ports.Tool, run ToolRun) []ports.Tool

WithToolRun gives every tool its ToolRun through its context, the way WithRunState gives it the state.

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"`
	// ActiveTotal is every run queued, running or waiting on a human, from
	// RunsByState: the number to show, where Active is a bounded sample.
	ActiveTotal int `json:"activeTotal"`
	// Active are runs still in flight, newest first, at most ActiveLimit.
	Active []ports.RunRecord `json:"active"`
	// ActiveLimit is the cap on Active; when ActiveTotal is above it the
	// list is a sample.
	ActiveLimit int `json:"activeLimit"`
	// Queue is what the queue says about itself: ready, delayed, in flight,
	// dead, the oldest wait. Nil when the queue adapter cannot count.
	Queue *ports.QueueStats `json:"queue,omitempty"`
}

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

type AgUIState struct {
	ThreadID string
	// contains filtered or unexported fields
}

AgUIState is what the AG-UI encoder remembers across frames: the tool calls whose arguments already went out as deltas.

func NewAgUIState added in v0.4.0

func NewAgUIState(threadID string) *AgUIState

NewAgUIState starts the encoder's memory for one follow.

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

type ApprovalRule func(ctx context.Context, input map[string]any) (bool, error)

ApprovalRule decides whether a call waits for a person to approve it first, from the call's input. An approved call runs when the approval comes back; a denied one tells the model it was denied. Nil keeps the tool's default.

var AskAlways ApprovalRule = func(context.Context, map[string]any) (bool, error) { return true, nil }

AskAlways makes every call wait for approval.

var AskNever ApprovalRule = func(context.Context, map[string]any) (bool, error) { return false, nil }

AskNever runs every call without approval.

type BashOptions added in v0.5.0

type BashOptions struct {
	// Timeout is how long one command may run. Default 120 s.
	Timeout time.Duration
	// MaxUses is the commands allowed in one run. 0: no limit.
	MaxUses int
	// Approval defaults to AskAlways: every command waits for approval.
	Approval ApprovalRule
}

BashOptions are the app's settings for bash.

type BuiltinToolDefinition added in v0.5.0

type BuiltinToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	InputSchema json.RawMessage `json:"inputSchema"`
}

BuiltinToolDefinition is one built-in tool as the model sees it.

func BuiltinToolDefinitionOf added in v0.5.0

func BuiltinToolDefinitionOf(name string) (BuiltinToolDefinition, error)

BuiltinToolDefinitionOf reads one tool's definition.

type BuiltinToolOptions added in v0.5.0

type BuiltinToolOptions struct {
	WebSearch     WebSearchOptions
	WebFetch      WebFetchOptions
	Bash          BashOptions
	CodeExecution CodeExecutionOptions
	TextEditor    TextEditorOptions
}

BuiltinToolOptions are the app's settings for the built-in tools.

type CodeExecutionOptions added in v0.5.0

type CodeExecutionOptions struct {
	// Timeout is how long one program may run. Default 60 s.
	Timeout time.Duration
	MaxUses int
	// Approval defaults to AskNever: it runs sealed in the sandbox.
	Approval ApprovalRule
}

CodeExecutionOptions are the app's settings for code_execution.

type CompactOptions added in v0.4.0

type CompactOptions struct {
	// RunID is the run the compaction call is billed to (§4), so it counts
	// in the run's bill and against its cost cap.
	RunID string
	// GenCtx is the context the summary call runs under: a stop cancels it.
	// Nil means ctx.
	GenCtx context.Context
	// Ledger is the run's ledger, so the summary call counts against the
	// run's caps like any other call. Nil records the row on its own.
	Ledger *RunLedger
}

CompactOptions is what a compaction needs to know about the run it serves.

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.
  4. Never skip a seq. The bus is at-most-once and does not promise order: an event can be dropped, or arrive after the one published behind it. An event that jumps past the next seq first has the gap read back from storage, in order.

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
	// DispatchID is the job's delivery id (see ports.RunJob). Empty means a
	// call that did not come off the queue; the lock then makes one up.
	DispatchID string
	// EnqueuedAt is epoch ms at enqueue, for the queue-wait measurement (§2.9).
	EnqueuedAt int64
	// DispatchedAt is epoch ms of the run's first dispatch (§2.8), carried
	// onto every retry so the run keeps its place in line.
	DispatchedAt int64
	// Kind says why this job exists. See ports.JobKind.
	Kind ports.JobKind
	// PartitionKey is the caller's tenant on the ticket, carried onto retries.
	PartitionKey string
	// 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"
	// OutcomeLockLost: this worker held the lock and could not keep it
	// renewed; the segment ended early and the job should come back once
	// the lock is free. Every step it finished is already persisted.
	OutcomeLockLost ExecuteOutcome = "lock-lost"
)

func Execute

func Execute(ctx context.Context, deps ports.RuntimePorts, agent *RegisteredAgent, input ExecuteInput) (outcome ExecuteOutcome, retErr error)

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 and renews it while the segment runs, so a held lock always means a live worker. Two workers can never run one thread, and a crashed worker's lock expires within a lease instead of blocking forever (§3.4).

type FinalizeInput

type FinalizeInput struct {
	State ports.ExecutionState
	// StopReason is 'completed' | 'token_budget' | 'max_steps' | 'cancelled' | 'timeout'.
	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 FollowFrame added in v0.4.0

type FollowFrame struct {
	Kind     string
	Event    *ports.AgentEvent
	StreamID string
	Item     *ports.StreamItem
	Snapshot *ports.ThreadSnapshot
}

FollowFrame is one frame of a thread's follow: a thread event (a record entry, or a notice), an item from its run stream, or a SNAPSHOT when the stream the client was reading is gone. Its JSON is the TS runtime's.

func (FollowFrame) MarshalJSON added in v0.4.0

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

MarshalJSON writes the frame as {"kind": ..., ...}.

func (*FollowFrame) UnmarshalJSON added in v0.4.0

func (f *FollowFrame) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a frame written by MarshalJSON (or the TS runtime).

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

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

FollowSSE is a thread's follow, 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 ToFollowSSE added in v0.4.0

func ToFollowSSE(frames *FrameStream, cursor *ThreadCursor, retryMs int) *FollowSSE

ToFollowSSE wraps a FrameStream for SSE; cursor is where the client was.

func (*FollowSSE) AsAgUI added in v0.4.0

func (s *FollowSSE) AsAgUI(threadID string) *FollowSSE

AsAgUI sends the follow as AG-UI events (opt-in) for a thread.

func (*FollowSSE) Err added in v0.4.0

func (s *FollowSSE) Err() error

Err reports why the underlying follow stopped.

func (*FollowSSE) ServeHTTP added in v0.4.0

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

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

func (*FollowSSE) WriteTo added in v0.4.0

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

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

type FollowThreadOptions added in v0.4.0

type FollowThreadOptions struct {
	// Cursor is where the client is. Nil follows from now: the record from
	// the start, and the run stream in flight from what the messages lack.
	Cursor *ThreadCursor
	// LastMessageID is the last message the client has, so a SNAPSHOT
	// carries only newer ones.
	LastMessageID string
}

FollowThreadOptions tunes FollowThread.

type FrameStream added in v0.4.0

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

FrameStream is a thread's follow. Read Frames() until it closes, then check Err().

func FollowThread added in v0.4.0

func FollowThread(ctx context.Context, deps ports.RuntimePorts, threadID string, opts FollowThreadOptions) (*FrameStream, error)

FollowThread is a thread live, as one sequence of frames (§2.2): its record entries and notices (subscribe first, replay after the cursor, never skip a seq; see FollowEvents), and its run streams. The stream the cursor names is read on from its offset; a RUN_STARTED moves the read to the new segment's stream; a stream that is gone becomes one SNAPSHOT frame, after which the follow carries on from the snapshot's stream. Cancel ctx, or the follow outlives the client.

func (*FrameStream) Err added in v0.4.0

func (s *FrameStream) Err() error

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

func (*FrameStream) Frames added in v0.4.0

func (s *FrameStream) Frames() <-chan FollowFrame

Frames is the channel of frames. It closes when the context is cancelled or the follow failed.

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) Registry added in v0.2.3

func (h *Handle) Registry(lookup func(name string) *RegisteredAgent)

Registry lets the handle find the OTHER agents registered beside it, by name. Stop needs it: the run it ends may belong to any of them, and the settle hook that closes that run's books is that agent's (§5.6). Without one, a stop settles only this handle's own runs.

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. A run it ends with no worker holding it is settled here, by the agent that run belongs to (§5.6).

type HitlCtx

type HitlCtx struct {
	Resume  ports.ResumeInfo
	AgentID string
	Frames  []HitlFrame
	Nested  *ports.NestedDescriptor
	// Parks collects the parks raised in this segment, to be committed once
	// the step that raised them is saved (see ParkBox). Nil parks at once.
	Parks *ParkBox
}

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

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

Lease is one holder's grip on a thread's run lock.

func AcquireRunLock added in v0.4.0

func AcquireRunLock(ctx context.Context, deps ports.RuntimePorts, threadID, runID, dispatchID string) (*Lease, error)

AcquireRunLock takes the thread's run lock for a run and one delivery of it. It returns nil, nil when someone else holds the lock.

func (*Lease) Keep added in v0.4.0

func (l *Lease) Keep(onLost func())

Keep renews the lease in the background until Release, the way a queue renews a job lease: an expired lock then means a dead worker and nothing else. onLost runs once, when the lease cannot be kept. That is when the key is gone or holds another holder's value, or when no renewal has landed for two thirds of the lease (the lease is then close to lapsing, and another worker may take it before the next try).

func (*Lease) Lost added in v0.4.0

func (l *Lease) Lost() bool

Lost reports that the lease could not be kept. Another worker may own the thread by now, so the holder must stop writing to it.

func (*Lease) Release added in v0.4.0

func (l *Lease) Release()

Release stops the renewal and frees the lock, only while it is still this holder's. Safe to call more than once.

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
	// CommitParks writes the parks raised during a step, once that step is
	// saved (see ParkBox). Only the main loop sets it: a nested run's parks
	// wait for the main agent's step. Nil commits nothing.
	CommitParks func(ctx context.Context) error
	// Fenced reports that the run lock is gone (§3.4): another worker may
	// own the thread, so this loop must not write another step to it. Nil
	// means never.
	Fenced          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 sees every raw chunk: the host's own callback.
	OnChunk func(provider.StreamChunk)
	// PublishChunk publishes a chunk as an event. Deltas reach it merged
	// (see chunkBatcher), and everything a step streamed is out before the
	// step is committed.
	PublishChunk func(payload map[string]any)
	// 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
}

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
	// Interrupted: the last model call ended without a finish and without a
	// user stop, and no error said why. The caller works out the cause (a
	// lost lock, a segment deadline, a stream the provider cut short); the
	// run must not be taken as finished.
	Interrupted 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 PanicError added in v0.4.0

type PanicError struct {
	Value any
	Stack []byte
}

PanicError is a panic caught by CallSafely. Stack is where it happened.

func (*PanicError) Error added in v0.4.0

func (e *PanicError) Error() string

type ParkBox added in v0.4.0

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

ParkBox holds the parks a segment raised until the step that raised them is saved (§2.5). A tool call parks in the middle of a model step, before the step's messages exist. Writing the park then would let the answer, a failed step or a stop act on a tool call the history does not have yet. So the wrapper only records the park here; the main loop commits the box once its step is saved, and a failed step simply drops it. Nested runs share their parent's box, so a park raised any depth down waits for the main agent's step too.

type ParkInput

type ParkInput struct {
	ThreadID   string
	ToolCallID string
	ToolName   string
	Args       json.RawMessage
	AgentID    string
	// Reason is ReasonApproval, or what a self-parking tool said (§2.5).
	Reason string
	// TTL overrides Config.HITLTTL for this park; zero keeps it.
	TTL time.Duration
	// 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 ParkRequest added in v0.2.1

type ParkRequest struct {
	// Reason names what the run is waiting on ("job", say). It rides the
	// INPUT_REQUIRED event, so a UI can tell it from an approval and skip
	// the card. Empty means ReasonApproval.
	Reason string
	// Payload is published as the request's arguments: the job id, a URL,
	// whatever the responder needs to find the work.
	Payload any
	// TTL is how long the park stays answerable; zero keeps Config.HITLTTL.
	// A job that outlives it resumes as expired, like an unanswered approval.
	TTL time.Duration
}

ParkRequest is a tool's own park (§2.5). The tool has started something it must not wait for in-process (a build, a render, a long job) and asks to be resumed when it is done: the run lock and the worker are released, the request is durable, and Respond(toolCallId, payload) runs the SAME tool call again with the payload on its Approval. Nothing waits meanwhile.

func AsParkRequest added in v0.2.1

func AsParkRequest(err error) (ParkRequest, bool)

AsParkRequest recognises a tool's own park in the error it returned.

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
	// ExpiresAt is the park's own deadline; zero on a park recorded before
	// per-park TTLs, which Deadline reads as RequestedAt + Config.HITLTTL.
	ExpiresAt time.Time
	// Reason is ReasonApproval or the self-parking tool's word (§2.5).
	Reason string
	// Resume is the dispatch ticket, when the park recorded one.
	Resume *ports.ResumeInfo
	// Landed marks a park whose own call already has its result in the
	// history, but whose unwind stopped part way (§2.7): a worker died, or
	// a child failed, between one level and the next. Nothing is left to
	// answer; the unwind carries on from ResumeFrame, the first frame still
	// waiting for its result.
	Landed      bool
	ResumeFrame int
}

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.

func (PendingHitl) Deadline added in v0.2.1

func (p PendingHitl) Deadline(cfg ports.AgentConfig) time.Time

Deadline is when this park stops being answerable.

func (PendingHitl) IsApproval added in v0.2.1

func (p PendingHitl) IsApproval() bool

IsApproval reports whether a human is the responder.

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

type PruneOptions struct {
	// DryRun counts what would go, and deletes nothing.
	DryRun bool
	// BatchSize is rows per batch; each batch is its own short delete.
	// Zero means 10,000.
	BatchSize int
}

PruneOptions tunes PruneEvents.

type PruneReport added in v0.4.0

type PruneReport struct {
	// ByType is rows deleted (or, on a dry run, found) per type.
	ByType  map[string]int64 `json:"byType"`
	Total   int64            `json:"total"`
	Batches int              `json:"batches"`
}

PruneReport says what PruneEvents did.

func PruneEvents added in v0.4.0

func PruneEvents(ctx context.Context, deps ports.RuntimePorts, opts PruneOptions) (PruneReport, error)

PruneEvents deletes the stream-only rows older releases left in the event log (see StreamOnlyTypes), a batch at a time, so a large table never holds one long lock. Safe to stop and run again: each batch stands on its own. Needs a storage whose event store is an EventPruner.

type PublishOptions

type PublishOptions struct {
	// Durable also keeps the event in the thread record, so a tab that
	// opens the thread next week still sees it. Otherwise (the default) it
	// is live only: it goes out on the bus and, during a run, on the run's
	// stream, which a tab that reconnects within the grace window replays.
	Durable bool
}

PublishOptions tunes PublishEvent.

type ReadPage added in v0.5.0

type ReadPage struct {
	Title   string
	Content string
}

ReadPage is a page's title and its main text.

func HTMLToText added in v0.5.0

func HTMLToText(html, baseURL, format string) ReadPage

HTMLToText is a page's title and its main text, as markdown or plain text (format "text").

type RegisteredAgent

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

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 entries in the thread record: each segment's
	// start and end, its parks and their answers, a refusal, a budget stop.
	// The readable spine; its steps are in Steps.
	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 what a run has spent, main agent and nested runs together (§2.7): its tokens, its money and the one currency that money is in. Shared so a child's spend counts against the run's caps the moment it happens.

A run's ledger starts from what the run already spent (SeedRunLedger): its earlier segments, before a park or a retry, count against the same caps. After that it is kept in memory, so the caps are checked without reading every usage row back after every step.

func SeedRunLedger added in v0.4.0

func SeedRunLedger(ctx context.Context, deps ports.RuntimePorts, threadID, runID string) *RunLedger

SeedRunLedger starts a ledger from the run's usage rows (§4). A failed read is logged and the ledger starts from zero: a run is not failed over its caps' bookkeeping.

func (*RunLedger) Add

func (l *RunLedger) Add(n int)

Add books tokens onto the ledger.

func (*RunLedger) Record added in v0.4.0

func (l *RunLedger) Record(ctx context.Context, deps ports.RuntimePorts, threadID string, u ports.NewUsage) ports.NewUsage

Record prices one call, stores its row and books it (§4). A run is priced in one currency: a call priced in another is stored unpriced, with an error logged, rather than mixed into a bill that cannot add it up.

func (*RunLedger) Spent added in v0.4.0

func (l *RunLedger) Spent() (int64, string)

Spent is the money the run has spent, and the currency it is in.

func (*RunLedger) TokensUsed

func (l *RunLedger) TokensUsed() int

TokensUsed reads the ledger.

type RunSlots added in v0.4.0

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

RunSlots is one run's subagent cap (§2.7): SubagentMaxConcurrent children at a time at each depth. It is made per run, so one run's children never wait on another run's. And each depth has slots of its own: a parent holds its slot while its child runs, so if parent and child shared one pool, a full level of parents would each wait for a slot only a finished child can free, and never finish.

func NewRunSlots added in v0.4.0

func NewRunSlots(limit int) *RunSlots

NewRunSlots makes a run's subagent cap: limit children at a time per depth.

func (*RunSlots) Acquire added in v0.4.0

func (r *RunSlots) Acquire(ctx context.Context, depth int) (release func(), err error)

Acquire takes a slot at a depth, waiting for one until ctx is done.

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 pickup 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).
	// A run still waiting counts with the time it has waited so far, so the
	// number rises while a backlog grows, not after it clears.
	Queued *Percentiles `json:"queued"`
	// Waiting is how many runs in the window are still QUEUED.
	Waiting int `json:"waiting"`
	Failed  int `json:"failed"`
	// Sampled is true when the window held more runs than the percentiles
	// were worked out over. The counts and token sums are exact either way;
	// the percentiles are then over the newest runs only.
	Sampled bool `json:"sampled,omitempty"`
}

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

type SegmentStream struct {
	ThreadID string
	RunID    string
	Segment  int
	StreamID string
	// contains filtered or unexported fields
}

func ActiveSegment added in v0.4.0

func ActiveSegment(deps ports.RuntimePorts, threadID string) *SegmentStream

ActiveSegment is the segment this process has open on a thread, or nil.

func OpenSegment added in v0.4.0

func OpenSegment(ctx context.Context, deps ports.RuntimePorts, threadID, runID string) *SegmentStream

OpenSegment opens the segment's stream and says RUN_STARTED on it. Nil when the runtime has no streams, or the open failed (logged): the run goes on without a stream.

func (*SegmentStream) Close added in v0.4.0

func (s *SegmentStream) Close(ctx context.Context, end ports.StreamEnd)

Close ends the stream: what is open is ended, what waits is appended, and the end item goes last. A second close is a no-op.

func (*SegmentStream) Closed added in v0.4.0

func (s *SegmentStream) Closed() bool

Closed reports whether Close ran.

func (*SegmentStream) Flush added in v0.4.0

func (s *SegmentStream) Flush(ctx context.Context)

Flush appends what waits.

func (*SegmentStream) Forward added in v0.4.0

func (s *SegmentStream) Forward(ctx context.Context, typ string, payload json.RawMessage, reserved bool)

Forward turns a published event into stream events. reserved is whether the type is one of the platform's; any other is an app's own, and goes out as CUSTOM.

func (*SegmentStream) OneShotText added in v0.4.0

func (s *SegmentStream) OneShotText() (string, bool)

OneShotText is the one-shot text TEXT_RESULT carried, if any.

func (*SegmentStream) Push added in v0.4.0

func (s *SegmentStream) Push(ctx context.Context, events ...ports.StreamEvent)

Push queues events; it appends at once when any must go at once.

type Semaphore

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

Semaphore is a concurrency cap: sibling subagents queue instead of running away (§2.7). See RunSlots for how a run uses them.

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

type StateChange struct {
	From []ports.ExecutionState
	To   ports.ExecutionState
	// RunID is the run the caller acts for; the change lands only while the
	// thread still belongs to it. Empty means any run.
	RunID string
	// NewRunID makes the thread belong to a new run (run admission).
	NewRunID string
	// Model is the thread's model, for the admin view; looked up when empty.
	Model string
}

StateChange is one run state change (§3.4): see Transition.

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 StopOptions added in v0.2.3

type StopOptions struct {
	// Agent resolves the registered agent a run belongs to, by the name on
	// its record. A stop that ends a run no worker holds (queued, or parked
	// on an approval) runs that agent's OnSettle itself (§5.6); with no
	// resolver the run is left unsettled.
	Agent func(name string) *RegisteredAgent
}

StopOptions tunes StopRun.

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
	// Slots caps how many subagents this run has going at once (§2.7).
	Slots *RunSlots
	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
	// Fenced reports that the run lock is gone (see LoopInput.Fenced).
	Fenced func() bool
	// Parks is the segment's park box, shared by every depth (see ParkBox).
	Parks *ParkBox
	// 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 TextEditorOptions added in v0.5.0

type TextEditorOptions struct {
	MaxUses int
	// Approval defaults to asking for changes but not for view.
	Approval ApprovalRule
}

TextEditorOptions are the app's settings for text_editor.

type ThreadCursor added in v0.4.0

type ThreadCursor struct {
	Seq      int64
	StreamID string
	Offset   string
}

ThreadCursor is where a client is: the thread record's last seq, and its place in a run stream. On the wire (an SSE id:, or a cursor query) it is one string, "<seq> <streamId> <offset>", with "-" for a part it does not have. The TS runtime reads and writes the same form.

func ParseCursor added in v0.4.0

func ParseCursor(raw string) (ThreadCursor, bool)

ParseCursor reads a cursor. A bare number is a record seq (what older clients send); anything unreadable is no cursor.

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

type ThreadSandbox struct {
	Sandbox ports.Sandbox
	// Created is true when this call made the sandbox.
	Created bool
	// Lost is true when the thread had a sandbox that is gone now: idle too
	// long, past its lifetime, or ended on its own. Its files are lost, and
	// a tool should tell the model so it does not expect them.
	Lost bool
}

ThreadSandbox is a thread's sandbox, as a call gets it.

func GetThreadSandbox added in v0.5.0

func GetThreadSandbox(ctx context.Context, run ToolRun) (ThreadSandbox, error)

GetThreadSandbox returns the thread's sandbox, making or reconnecting it.

func SandboxFor added in v0.5.0

func SandboxFor(ctx context.Context) (ThreadSandbox, error)

SandboxFor returns the thread's sandbox, for a tool you write yourself. Pass the ctx your tool's Execute was given:

ts, err := agentenkit.SandboxFor(ctx)
text, err := ts.Sandbox.Filesystem().ReadFile(ctx, path)

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 are summed from the run records. In a list that is tokens only,
	// with no money; GetThread reads the thread's usage rows instead, so its
	// Tokens carry the cost too (§4).
	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 read of those threads' 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. Live only by default: a tab that reconnects soon replays it,
	// but it is not saved. PublishOptions{Durable: true} also keeps it in the
	// thread record. 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
	// ThreadID is the thread this call is acting on.
	ThreadID string
	// RunID is the dispatched run this call is part of: a nested run's calls
	// carry their parent's run id, so one run's work is one query.
	RunID string
}

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.

type ToolRun added in v0.5.0

type ToolRun struct {
	Deps     ports.RuntimePorts
	ThreadID string
	// RunID is the dispatched run: a nested run's calls are billed to its
	// parent.
	RunID string
	// AgentID is empty for the main agent, the nested run's id otherwise.
	AgentID   string
	AgentName string
	Ledger    *RunLedger
	// State is the run's state (§2.10), for adapters that pick per tenant.
	State ports.AgentRunState
}

ToolRun is what a tool call knows about the run it is part of, beyond its state: the run's own ports (its storage is bound to the run's state, so a tenant's usage rows land in the tenant's store), the thread, the run, and the ledger its spend is booked on so tool costs count against the run's caps.

func ToolRunFromContext added in v0.5.0

func ToolRunFromContext(ctx context.Context) (ToolRun, bool)

ToolRunFromContext is the ToolRun a call was given, if it runs inside an agentenkit run.

type WebFetchOptions added in v0.5.0

type WebFetchOptions struct {
	// MaxBytes stops reading a page after this many bytes. Default 2,000,000.
	MaxBytes int
	// MaxUses is the pages read in one run. 0: no limit.
	MaxUses int
	// Model is the registry key of the small model that answers a prompt
	// from the page. Default: the config's CompactionModel.
	Model string
}

WebFetchOptions are the app's settings for web_fetch.

type WebSearchOptions added in v0.5.0

type WebSearchOptions struct {
	// MaxResults is the number of results when the model does not say.
	// Default 5; never more than 10.
	MaxResults int
	// MaxUses is the searches allowed in one run. Past it the tool answers
	// with an error the model can read, and the run goes on. 0: no limit.
	MaxUses int
	// AllowedDomains keeps only results from these domains (and their
	// subdomains). The model cannot change the domain lists or the recency:
	// small models fill in every field they are offered and narrow the
	// search by mistake, so these are the app's to set, as in Anthropic's
	// own web search.
	AllowedDomains []string
	// BlockedDomains drops results from these domains (and their
	// subdomains).
	BlockedDomains []string
	// Recency keeps only results from the last "day", "week", "month" or
	// "year".
	Recency ports.SearchRecency
}

WebSearchOptions are the app's settings for web_search.

Jump to

Keyboard shortcuts

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