Help us shape the future of Go! Take the 2026 Go Developer Survey

agentcore

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package agentcore contains the host-facing Agent API and the advanced ReAct runtime used to execute it.

Most applications should use NewAgent, Agent.Run, Agent.RunDetailed, RunRequest, RunResult, options, events, budgets, skills, and module providers. The stage pipeline, RunState, ReActRunner, and individual stage types are exported for tests and specialized runtime composition, but hosts should prefer Agent unless they are intentionally replacing the default loop.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrApprovalPending reports that a host must resolve pending tool calls before execution can continue.
	ErrApprovalPending = errors.New("approval pending")
	// ErrInvalidRunCheckpoint reports a malformed, unsupported, or incomplete checkpoint.
	ErrInvalidRunCheckpoint = errors.New("invalid run checkpoint")
	// ErrInvalidApprovalResolution reports resolutions that do not exactly match the pending call batch.
	ErrInvalidApprovalResolution = errors.New("invalid approval resolution")
)
View Source
var ErrApprovalDenied = errors.New("approval denied")
View Source
var ErrBudgetExceeded = errors.New("budget exceeded")
View Source
var ErrInputRejected = errors.New("input rejected")
View Source
var ErrMaxIterations = errors.New("max iterations reached")
View Source
var ErrMissingLLM = errors.New("agent requires LLM client")
View Source
var ErrOutputInvalid = errors.New("output invalid")
View Source
var ErrPolicyDenied = errors.New("policy denied")

Functions

This section is empty.

Types

type ActStage

type ActStage struct {
	Executor *tools.Executor
}

func (ActStage) Name

func (s ActStage) Name() string

func (ActStage) Run

func (s ActStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type Agent

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

func NewAgent

func NewAgent(options ...Option) (*Agent, error)

func (*Agent) Resume

func (a *Agent) Resume(ctx context.Context, checkpoint RunCheckpoint, resolutions []ToolApprovalResolution) (*RunResult, error)

Resume continues a run interrupted by pending tool approval. It returns a nil result with ErrApprovalPending when another approval is required.

func (*Agent) ResumeDetailed

func (a *Agent) ResumeDetailed(ctx context.Context, checkpoint RunCheckpoint, resolutions []ToolApprovalResolution) (*RunResult, error)

ResumeDetailed continues a run interrupted by pending tool approval and preserves partial results on errors. A request-scoped ToolProvider must recreate the same tools for the checkpoint request.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, req RunRequest) (*RunResult, error)

func (*Agent) RunDetailed

func (a *Agent) RunDetailed(ctx context.Context, req RunRequest) (*RunResult, error)

func (*Agent) Stream

func (a *Agent) Stream(ctx context.Context, req RunRequest) *RunStream

type ApprovalStage

type ApprovalStage struct {
	Approver ToolApprover
}

func (ApprovalStage) Name

func (s ApprovalStage) Name() string

func (ApprovalStage) Run

func (s ApprovalStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type Budget

type Budget struct {
	MaxInputTokens  int
	MaxOutputTokens int
	MaxTotalTokens  int
}

type BudgetDecision

type BudgetDecision struct {
	Allowed bool
	Reason  string
}

type BudgetGuard

type BudgetGuard interface {
	Check(ctx context.Context, state *RunState) BudgetDecision
}

func NewBudgetGuard

func NewBudgetGuard(budget Budget) BudgetGuard

type BudgetStage

type BudgetStage struct {
	Guard BudgetGuard
}

func (BudgetStage) Name

func (s BudgetStage) Name() string

func (BudgetStage) Run

func (s BudgetStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type CheckpointRequest

type CheckpointRequest struct {
	Input              string              `json:"input"`
	UserID             string              `json:"user_id,omitempty"`
	SessionID          string              `json:"session_id,omitempty"`
	Metadata           map[string]any      `json:"metadata,omitempty"`
	AllowedPermissions []policy.Permission `json:"allowed_permissions,omitempty"`
	PolicyContext      ports.PolicyContext `json:"policy_context"`
}

CheckpointRequest is the JSON-safe request context retained for a paused run. It intentionally keeps the Run ID in RunCheckpoint so that its JSON form is a string.

type ContextProjectionRequest

type ContextProjectionRequest struct {
	Messages []Message
	Budget   Budget
	Metadata map[string]any
}

type ContextProjectionResult

type ContextProjectionResult struct {
	Messages []Message
	Metadata map[string]any
}

type ContextProjectionStage

type ContextProjectionStage struct {
	Projector ContextProjector
	Budget    Budget
}

func (ContextProjectionStage) Name

func (s ContextProjectionStage) Name() string

func (ContextProjectionStage) Run

type ContextProjector

type ContextProjector interface {
	Project(ctx context.Context, req ContextProjectionRequest) (*ContextProjectionResult, error)
}

type ContextStage

type ContextStage struct{}

func (ContextStage) Name

func (s ContextStage) Name() string

func (ContextStage) Run

func (s ContextStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type Event

type Event struct {
	RunID     RunID
	Type      EventType
	Stage     string
	Iteration int
	Message   string
	Metadata  map[string]any
}

type EventSink

type EventSink interface {
	Emit(ctx context.Context, event Event) error
}

type EventType

type EventType string
const (
	EventStageStarted    EventType = "stage.started"
	EventStageCompleted  EventType = "stage.completed"
	EventStageFailed     EventType = "stage.failed"
	EventToolStarted     EventType = "tool.started"
	EventToolCompleted   EventType = "tool.completed"
	EventToolFailed      EventType = "tool.failed"
	EventToolRejected    EventType = "tool.rejected"
	EventMemoryLoaded    EventType = "memory.loaded"
	EventMemorySaved     EventType = "memory.saved"
	EventFinalized       EventType = "finalized"
	EventOutputValidated EventType = "output.validated"
	EventInputValidated  EventType = "input.validated"
	EventInputRejected   EventType = "input.rejected"

	EventApprovalRequested EventType = "approval.requested"
	EventApprovalCompleted EventType = "approval.completed"
	EventApprovalDenied    EventType = "approval.denied"
	EventApprovalPending   EventType = "approval.pending"
)

type ExecutionSummary

type ExecutionSummary struct {
	LLMCalls    int
	ToolCalls   int
	UsedTools   []string
	Duration    time.Duration
	AbortReason string
}

type FinalizeStage

type FinalizeStage struct {
	OutputFormat    OutputFormat
	OutputValidator OutputValidator
}

func (FinalizeStage) Name

func (s FinalizeStage) Name() string

func (FinalizeStage) Run

func (s FinalizeStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type InputGuard

type InputGuard interface {
	ValidateInput(context.Context, InputGuardRequest) error
}

InputGuard screens one raw run request. It must not call tools or mutate external state.

type InputGuardFunc

type InputGuardFunc func(context.Context, InputGuardRequest) error

InputGuardFunc adapts a function to InputGuard.

func (InputGuardFunc) ValidateInput

func (f InputGuardFunc) ValidateInput(ctx context.Context, req InputGuardRequest) error

type InputGuardRequest

type InputGuardRequest struct {
	RunID         RunID
	Input         string
	Metadata      map[string]any
	PolicyContext ports.PolicyContext
}

InputGuardRequest is the host-visible request boundary before memory, context, model, or tools run.

type InputGuardStage

type InputGuardStage struct {
	Guard InputGuard
}

InputGuardStage runs the host guard once before memory and context are populated.

func (InputGuardStage) Name

func (s InputGuardStage) Name() string

func (InputGuardStage) Run

func (s InputGuardStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type MemoryLoadStage

type MemoryLoadStage struct {
	Provider ports.MemoryProvider
}

func (MemoryLoadStage) Name

func (s MemoryLoadStage) Name() string

func (MemoryLoadStage) Run

func (s MemoryLoadStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type Message

type Message struct {
	Role       string
	Content    string
	ToolCallID string
	ToolCalls  []ports.ToolCall
}

type ModelDelta

type ModelDelta struct {
	Iteration int
	Content   string
}

ModelDelta is a piece of model output streamed while a call runs, when the Agent's LLM implements ports.StreamingLLMClient. Iteration identifies the model call. Deltas reach only the stream, never the Agent's EventSink.

type Module

type Module interface {
	SystemPromptProvider
	SkillProvider
	ToolProvider
}

type MutableToolRegistry

type MutableToolRegistry interface {
	ports.ToolRegistry
	Register(tool tools.Tool)
}

MutableToolRegistry is the per-run registry shape used by stages that both read configured tools and register request-scoped tools.

type ObserveStage

type ObserveStage struct{}

func (ObserveStage) Name

func (s ObserveStage) Name() string

func (ObserveStage) Run

func (s ObserveStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type Option

type Option func(*Agent)

func WithBudget

func WithBudget(budget Budget) Option

func WithBudgetGuard

func WithBudgetGuard(guard BudgetGuard) Option

func WithContextProjector

func WithContextProjector(projector ContextProjector) Option

func WithEventSink

func WithEventSink(sink EventSink) Option

func WithInputGuard

func WithInputGuard(guard InputGuard) Option

WithInputGuard screens raw requests before memory, context, model, or tool execution.

func WithLLM

func WithLLM(llm ports.LLMClient) Option

func WithMaxIterations

func WithMaxIterations(maxIterations int) Option

func WithMaxOutputTokens

func WithMaxOutputTokens(maxOutputTokens int) Option

WithMaxOutputTokens caps generated tokens per model call.

func WithMemoryProvider

func WithMemoryProvider(provider ports.MemoryProvider) Option

func WithModule

func WithModule(module Module) Option

func WithOutputFormat

func WithOutputFormat(format OutputFormat) Option

func WithOutputValidator

func WithOutputValidator(validator OutputValidator) Option

func WithPolicyEngine

func WithPolicyEngine(engine ports.PolicyEngine) Option

func WithPromptBlocks

func WithPromptBlocks(blocks []prompt.Block) Option

func WithPromptCompiler

func WithPromptCompiler(c ports.PromptCompiler) Option

func WithSkillProvider

func WithSkillProvider(provider SkillProvider) Option

func WithSystemPromptProvider

func WithSystemPromptProvider(provider SystemPromptProvider) Option

func WithToolApprover

func WithToolApprover(approver ToolApprover) Option

func WithToolProvider

func WithToolProvider(provider ToolProvider) Option

func WithToolRegistry

func WithToolRegistry(r ports.ToolRegistry) Option

type OutputFormat

type OutputFormat struct {
	Name         string
	Description  string
	Instructions string
	JSONSchema   json.RawMessage
}

OutputFormat describes the final answer shape the host wants the model to produce. JSONSchema is both prompt guidance and a local validation contract.

func (OutputFormat) IsZero

func (f OutputFormat) IsZero() bool

type OutputFormatStage

type OutputFormatStage struct {
	Format OutputFormat
}

OutputFormatStage adds final-output instructions before the prompt is compiled. Validation still happens later in FinalizeStage.

func (OutputFormatStage) Name

func (s OutputFormatStage) Name() string

func (OutputFormatStage) Run

type OutputValidationRequest

type OutputValidationRequest struct {
	RunID    RunID
	Content  string
	Format   OutputFormat
	Metadata map[string]any
}

OutputValidationRequest is passed to host validators after the model returns a final answer and before the answer is saved to memory.

type OutputValidationResult

type OutputValidationResult struct {
	Structured json.RawMessage
	Metadata   map[string]any
}

OutputValidationResult lets custom validators attach parsed output or small validation metadata to the final RunResult.

type OutputValidator

type OutputValidator interface {
	ValidateOutput(context.Context, OutputValidationRequest) (*OutputValidationResult, error)
}

OutputValidator is a host-owned final-answer guardrail. It should validate output shape or safety, not call tools or mutate external state.

type Pipeline

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

func NewPipeline

func NewPipeline(stages ...Stage) *Pipeline

func (*Pipeline) Run

func (p *Pipeline) Run(ctx context.Context, state *RunState) (StageResult, error)

type PolicyStage

type PolicyStage struct {
	Engine       ports.PolicyEngine
	ToolRegistry ports.ToolRegistry
}

func (PolicyStage) Name

func (s PolicyStage) Name() string

func (PolicyStage) Run

func (s PolicyStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type PromptStage

type PromptStage struct {
	Compiler ports.PromptCompiler
	Blocks   []prompt.Block
}

func (PromptStage) Name

func (s PromptStage) Name() string

func (PromptStage) Run

func (s PromptStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type ReActConfig

type ReActConfig struct {
	LLM                  ports.LLMClient
	PromptCompiler       ports.PromptCompiler
	PromptBlocks         []prompt.Block
	ToolRegistry         MutableToolRegistry
	PolicyEngine         ports.PolicyEngine
	MemoryProvider       ports.MemoryProvider
	SkillProvider        SkillProvider
	SystemPromptProvider SystemPromptProvider
	ToolProvider         ToolProvider
	ContextProjector     ContextProjector
	InputGuard           InputGuard
	ToolApprover         ToolApprover
	OutputFormat         OutputFormat
	OutputValidator      OutputValidator
	BudgetGuard          BudgetGuard
	MaxIterations        int
	// MaxOutputTokens caps generated tokens per model call; zero leaves it to the provider.
	MaxOutputTokens int
}

type ReActRunner

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

func NewReActRunner

func NewReActRunner(config ReActConfig) *ReActRunner

func (*ReActRunner) Run

func (r *ReActRunner) Run(ctx context.Context, state *RunState) (StageResult, error)

type ResolvedApprovalStage

type ResolvedApprovalStage struct {
	Resolutions []ToolApprovalResolution
}

ResolvedApprovalStage verifies a complete host decision set before allowing a paused batch to execute.

func (ResolvedApprovalStage) Name

func (s ResolvedApprovalStage) Name() string

func (ResolvedApprovalStage) Run

type RunCheckpoint

type RunCheckpoint struct {
	Version            int                 `json:"version"`
	RunID              string              `json:"run_id"`
	Request            CheckpointRequest   `json:"request"`
	Iteration          int                 `json:"iteration"`
	Messages           []Message           `json:"messages"`
	Usage              Usage               `json:"usage"`
	LLMCalls           int                 `json:"llm_calls"`
	ToolCalls          int                 `json:"tool_calls"`
	UsedTools          []string            `json:"used_tools,omitempty"`
	StartedAt          time.Time           `json:"started_at"`
	Metadata           map[string]any      `json:"metadata"`
	AllowedPermissions []policy.Permission `json:"allowed_permissions"`
	PendingCalls       []ports.ToolCall    `json:"pending_calls"`
	PromptBlocks       []prompt.Block      `json:"prompt_blocks"`
}

RunCheckpoint is a versioned, JSON-serializable snapshot of a run paused before tool execution. It includes raw user content and tool inputs, so hosts must store it as sensitive data.

type RunID

type RunID uuid.UUID

func NewRunID

func NewRunID() RunID

func RunIDFromString

func RunIDFromString(value string) (RunID, error)

func (RunID) IsZero

func (id RunID) IsZero() bool

func (RunID) String

func (id RunID) String() string

type RunRequest

type RunRequest struct {
	RunID              RunID
	Input              string
	UserID             string
	SessionID          string
	Metadata           map[string]any
	AllowedPermissions []policy.Permission
	PolicyContext      ports.PolicyContext
}

type RunResult

type RunResult struct {
	RunID            RunID
	Content          string
	StructuredOutput json.RawMessage
	OutputMetadata   map[string]any
	Usage            Usage
	ExecutionSummary ExecutionSummary
	Interruption     *ToolApprovalInterruption
}

type RunState

type RunState struct {
	RunID     RunID
	Input     RunRequest
	Iteration int
	Messages  []Message
	Final     *RunResult
	Usage     Usage
	Metadata  map[string]any
	EventSink EventSink

	PromptBlocks       []prompt.Block
	CompiledPrompt     *prompt.Compiled
	ContextProjection  *ContextProjectionResult
	LastResponse       *ports.ChatResponse
	PendingCalls       []tools.Call
	ToolResults        []tools.Execution
	AllowedPermissions []policy.Permission
	// contains filtered or unexported fields
}

func NewRunState

func NewRunState(runID RunID, req RunRequest) *RunState

func (*RunState) Emit

func (s *RunState) Emit(ctx context.Context, event Event)

type RunStream

type RunStream struct {
	Events <-chan RunStreamEvent
	// contains filtered or unexported fields
}

func (*RunStream) DiscardEvents

func (s *RunStream) DiscardEvents()

DiscardEvents stops public event delivery without canceling the Agent run. Call it when Events will not be drained; repeated calls are safe.

func (*RunStream) Wait

func (s *RunStream) Wait() (*RunResult, error)

type RunStreamEvent

type RunStreamEvent struct {
	Event  Event
	Delta  *ModelDelta
	Result *RunResult
	Error  error
	Done   bool
}

RunStreamEvent carries one of: a run Event, a ModelDelta of streamed model output, or, when Done is set, the run's Result and Error.

type Skill

type Skill struct {
	Name        string
	Description string
	Content     string
	Priority    int
	Cacheable   bool
}

type SkillProvider

type SkillProvider interface {
	Skills(ctx context.Context, req RunRequest) ([]Skill, error)
}

type SkillStage

type SkillStage struct {
	Provider SkillProvider
}

func (SkillStage) Name

func (s SkillStage) Name() string

func (SkillStage) Run

func (s SkillStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type Stage

type Stage interface {
	Name() string
	Run(ctx context.Context, state *RunState) (StageResult, error)
}

type StageResult

type StageResult int
const (
	StageContinue StageResult = iota
	StageBreak
	StageAbort
	StageInterrupt
)

type SystemPromptProvider

type SystemPromptProvider interface {
	SystemPrompt(ctx context.Context, req RunRequest) ([]prompt.Block, error)
}

type SystemPromptStage

type SystemPromptStage struct {
	Provider SystemPromptProvider
}

func (SystemPromptStage) Name

func (s SystemPromptStage) Name() string

func (SystemPromptStage) Run

type ThinkStage

type ThinkStage struct {
	LLM             ports.LLMClient
	ToolRegistry    ports.ToolRegistry
	MaxOutputTokens int
}

func (ThinkStage) Name

func (s ThinkStage) Name() string

func (ThinkStage) Run

func (s ThinkStage) Run(ctx context.Context, state *RunState) (StageResult, error)

type ToolApprovalDecision

type ToolApprovalDecision struct {
	Allowed bool
	// Pending takes precedence over Allowed so an ambiguous decision cannot execute a tool.
	Pending bool
	Reason  string
}

ToolApprovalDecision is a synchronous allow, deny, or pending decision for one tool call.

type ToolApprovalInterruption

type ToolApprovalInterruption struct {
	Checkpoint RunCheckpoint `json:"checkpoint"`
}

ToolApprovalInterruption exposes the checkpoint required to continue a pending approval.

type ToolApprovalRequest

type ToolApprovalRequest struct {
	RunID     RunID
	UserID    string
	SessionID string
	Tool      string
	Input     json.RawMessage
	Metadata  map[string]any
}

type ToolApprovalResolution

type ToolApprovalResolution struct {
	Index      int    `json:"index"`
	ToolCallID string `json:"tool_call_id"`
	Tool       string `json:"tool"`
	Allowed    bool   `json:"allowed"`
	Reason     string `json:"reason,omitempty"`
}

ToolApprovalResolution is a host decision for one checkpointed pending call. Index, ToolCallID, and Tool must exactly match the original call.

type ToolApprover

type ToolApprover interface {
	ApproveTool(ctx context.Context, req ToolApprovalRequest) ToolApprovalDecision
}

type ToolProvider

type ToolProvider interface {
	Tools(ctx context.Context, req RunRequest) ([]tools.Tool, error)
}

ToolProvider returns request-scoped tools. Providers used with approval checkpoints must recreate the same valid tools for the checkpoint request.

type ToolProviderStage

type ToolProviderStage struct {
	Provider ToolProvider
	Registry interface {
		Register(tool tools.Tool)
	}
}

func (ToolProviderStage) Name

func (s ToolProviderStage) Name() string

func (ToolProviderStage) Run

type Usage

type Usage struct {
	InputTokens  int
	OutputTokens int
}

Jump to

Keyboard shortcuts

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