core

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package core defines the stable execution contracts shared by graph construction, node implementations, the registry, the runtime, and tools.

The package contains:

  • node contracts and execution primitives, including Node, NodeBase, NodeResult, Command, and ExecuteNode;
  • Context and the model, tool, environment, and execution services carried through it;
  • model invocation, observation, response validation, and usage accounting;
  • tool definition, permission and approval checks, concurrency control, invocation observation, and input/output validation;
  • classified execution errors used by retry and runtime policies; and
  • state-contract validation modes, diagnostics, violations, and initial state requirements shared by graph analysis and runtime enforcement.

These are dependency-neutral primitives that must cross package boundaries. Core may depend on foundational packages such as state and llms, but must not depend on graph, node, registry, runtime, server, or concrete implementations.

Serializable graph definitions belong to dsl, node type schemas and builders belong to registry, concrete node implementations belong to node, graph compilation and scheduling belong to graph, and run lifecycle and persistence belong to runtime. Add a type to core only when multiple higher-level packages need the same stable contract and assigning it to one consumer would reverse the dependency direction or create an import cycle.

Index

Constants

View Source
const DefaultModelID = "default"

Variables

View Source
var ErrToolApprovalRequired = errors.New("tool approval is required")

Functions

func AcquireToolExecution

func AcquireToolExecution(ctx context.Context, mode ToolExecutionMode) (context.Context, func(), error)

func ApplyNodeOptions

func ApplyNodeOptions(base *NodeBase, options []NodeOption)

func ContractFor

func ContractFor(node Node) (state.Contract, error)

func DecodeStructuredOutput

func DecodeStructuredOutput(content string, schema state.JSONSchema, compatibility bool) (string, any, error)

DecodeStructuredOutput normalizes one schema-valid JSON value from model output.

func DecodeToolArguments

func DecodeToolArguments(call llms.ToolCall, target any) error

func EnvironmentFromContext

func EnvironmentFromContext(ctx context.Context) map[string]string

func EnvironmentVariableFromContext

func EnvironmentVariableFromContext(ctx context.Context, name string) string

func ExecuteTool

func ExecuteTool(ctx context.Context, tool Tool, call llms.ToolCall) (llms.ToolResult, error)

func FilterTools

func FilterTools(available map[string]Tool, ids []string) map[string]Tool

func GenerateModel

func GenerateModel(ctx context.Context, model llms.Model, request llms.ModelRequest) (*llms.ModelResponse, error)

func IdempotencyKeyFromContext

func IdempotencyKeyFromContext(ctx context.Context) (string, bool)

func IsRetryableErrorClass

func IsRetryableErrorClass(class ErrorClass) bool

func IsWriteEffect

func IsWriteEffect(class EffectClass) bool

func ModelByIDFromContext

func ModelByIDFromContext(ctx context.Context, id string) llms.Model

func ModelConfigsFromContext

func ModelConfigsFromContext(ctx context.Context) map[string]ModelConfig

func ModelFromContext

func ModelFromContext(ctx context.Context) llms.Model

func ModelsFromContext

func ModelsFromContext(ctx context.Context) map[string]llms.Model

func ToolExecutionConcurrencyLimit

func ToolExecutionConcurrencyLimit(ctx context.Context) int

func ToolPermissionsFromContext

func ToolPermissionsFromContext(ctx context.Context) ([]string, bool)

func ToolsFromContext

func ToolsFromContext(ctx context.Context) map[string]Tool

func WithEffectJournal

func WithEffectJournal(ctx context.Context, journal EffectJournal) context.Context

func WithEffectOperation

func WithEffectOperation(ctx context.Context, operation EffectOperation) context.Context

func WithEnvironment

func WithEnvironment(ctx context.Context, environment map[string]string) context.Context

func WithFailure

func WithFailure(ctx context.Context, failure FailureContext) context.Context

func WithModel

func WithModel(ctx context.Context, model llms.Model) context.Context

func WithModelCallObserver

func WithModelCallObserver(ctx context.Context, observer ModelCallObserver) context.Context

func WithModelConfigs

func WithModelConfigs(ctx context.Context, available map[string]ModelConfig) context.Context

func WithModels

func WithModels(ctx context.Context, available map[string]llms.Model) context.Context

func WithToolApprover

func WithToolApprover(ctx context.Context, approver ToolApprover) context.Context

func WithToolConcurrencyLimiter

func WithToolConcurrencyLimiter(ctx context.Context, limiter *ConcurrencyLimiter, observer ConcurrencyWaitObserver) context.Context

func WithToolExecutionObserver

func WithToolExecutionObserver(ctx context.Context, observer ToolExecutionObserver) context.Context

func WithToolPermissions

func WithToolPermissions(ctx context.Context, permissions ...string) context.Context

func WithTools

func WithTools(ctx context.Context, available map[string]Tool) context.Context

Types

type ArtifactDraft

type ArtifactDraft struct {
	Type     string
	MIMEType string
	Data     []byte
}

type ClassifiedError

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

func NewExecutionError

func NewExecutionError(class ErrorClass, message string, cause error, details map[string]any) *ClassifiedError

func (*ClassifiedError) Class

func (executionErr *ClassifiedError) Class() ErrorClass

func (*ClassifiedError) Details

func (executionErr *ClassifiedError) Details() map[string]any

func (*ClassifiedError) Error

func (executionErr *ClassifiedError) Error() string

func (*ClassifiedError) RetryAfter

func (executionErr *ClassifiedError) RetryAfter() time.Duration

func (*ClassifiedError) Unwrap

func (executionErr *ClassifiedError) Unwrap() error

func (*ClassifiedError) WithRetryAfter

func (executionErr *ClassifiedError) WithRetryAfter(delay time.Duration) *ClassifiedError

type Command

type Command struct {
	Goto    []NodeRef
	Send    []Send
	Suspend *SuspendRequest
	Return  *ReturnCommand
}

type ConcurrencyLimiter

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

func NewConcurrencyLimiter

func NewConcurrencyLimiter(limit int) *ConcurrencyLimiter

func ToolConcurrencyLimiterFromContext

func ToolConcurrencyLimiterFromContext(ctx context.Context) *ConcurrencyLimiter

func (*ConcurrencyLimiter) Acquire

func (limiter *ConcurrencyLimiter) Acquire(ctx context.Context) (func(), error)

func (*ConcurrencyLimiter) Limit

func (limiter *ConcurrencyLimiter) Limit() int

func (*ConcurrencyLimiter) TryAcquire

func (limiter *ConcurrencyLimiter) TryAcquire() (func(), bool)

type ConcurrencyWaitObserver

type ConcurrencyWaitObserver func(limit int)

type Context

type Context struct {
	context.Context
}

func NewContext

func NewContext(ctx context.Context) Context

func (Context) Deadline

func (c Context) Deadline() (time.Time, bool)

func (Context) Done

func (c Context) Done() <-chan struct{}

func (Context) Environment

func (c Context) Environment() map[string]string

func (Context) Err

func (c Context) Err() error

func (Context) Failure

func (c Context) Failure() (FailureContext, bool)

func (Context) FilterTools

func (c Context) FilterTools(ids []string) map[string]Tool

func (Context) Model

func (c Context) Model(ids ...string) llms.Model

func (Context) ModelConfig

func (c Context) ModelConfig(ids ...string) (ModelConfig, bool)

func (Context) ModelConfigs

func (c Context) ModelConfigs() map[string]ModelConfig

func (Context) Models

func (c Context) Models() map[string]llms.Model

func (Context) Tools

func (c Context) Tools() map[string]Tool

func (Context) Value

func (c Context) Value(key any) any

type ContractDiagnostic

type ContractDiagnostic struct {
	Severity    ContractDiagnosticSeverity `json:"severity"`
	Kind        string                     `json:"kind"`
	NodeID      string                     `json:"node_id,omitempty"`
	OtherNodeID string                     `json:"other_node_id,omitempty"`
	Path        string                     `json:"path,omitempty"`
	Sources     []string                   `json:"sources,omitempty"`
	Message     string                     `json:"message"`
}

type ContractDiagnosticSeverity

type ContractDiagnosticSeverity string
const (
	ContractDiagnosticSeverityError   ContractDiagnosticSeverity = "error"
	ContractDiagnosticSeverityWarning ContractDiagnosticSeverity = "warning"
)

type ContractProvider

type ContractProvider interface {
	Contract() state.Contract
}

type ContractValidationMode

type ContractValidationMode string
const (
	ContractValidationOff    ContractValidationMode = ""
	ContractValidationWarn   ContractValidationMode = "warn"
	ContractValidationStrict ContractValidationMode = "strict"
)

type ContractViolation

type ContractViolation struct {
	NodeID  string `json:"node_id"`
	Path    string `json:"path"`
	Kind    string `json:"kind"`
	Message string `json:"message"`
}

type EffectClass

type EffectClass string
const (
	EffectUnspecified        EffectClass = "unspecified"
	EffectPure               EffectClass = "pure"
	EffectReadOnly           EffectClass = "read_only"
	EffectIdempotentWrite    EffectClass = "idempotent_write"
	EffectNonIdempotentWrite EffectClass = "non_idempotent_write"
	EffectCompensatable      EffectClass = "compensatable"
)

func NodeEffectClass

func NodeEffectClass(node Node) EffectClass

func NormalizeEffectClass

func NormalizeEffectClass(class EffectClass) EffectClass

type EffectCompensationRequest

type EffectCompensationRequest struct {
	Operation  EffectOperation   `json:"operation"`
	Operations []EffectOperation `json:"operations,omitempty"`
}

type EffectCompensator

type EffectCompensator interface {
	CompensateEffect(Context, EffectCompensationRequest, *state.Access) error
}

type EffectDeclarer

type EffectDeclarer interface {
	EffectClass() EffectClass
}

type EffectJournal

type EffectJournal interface {
	RecordEffect(context.Context, EffectOperation) error
}

func EffectJournalFromContext

func EffectJournalFromContext(ctx context.Context) EffectJournal

type EffectJournalFunc

type EffectJournalFunc func(context.Context, EffectOperation) error

func (EffectJournalFunc) RecordEffect

func (journal EffectJournalFunc) RecordEffect(ctx context.Context, operation EffectOperation) error

type EffectOperation

type EffectOperation struct {
	Key               string       `json:"key"`
	ParentKey         string       `json:"parent_key,omitempty"`
	Kind              string       `json:"kind"`
	Name              string       `json:"name"`
	Class             EffectClass  `json:"class"`
	Status            EffectStatus `json:"status"`
	Attempt           int          `json:"attempt,omitempty"`
	IdempotencyKey    string       `json:"idempotency_key,omitempty"`
	ProviderRequestID string       `json:"provider_request_id,omitempty"`
	Error             string       `json:"error,omitempty"`
}

func ChildEffectOperation

func ChildEffectOperation(parent EffectOperation, kind, name, identity string, class EffectClass) EffectOperation

func EffectOperationFromContext

func EffectOperationFromContext(ctx context.Context) (EffectOperation, bool)

type EffectStatus

type EffectStatus string
const (
	EffectIntent      EffectStatus = "intent"
	EffectSucceeded   EffectStatus = "succeeded"
	EffectFailed      EffectStatus = "failed"
	EffectUnknown     EffectStatus = "unknown"
	EffectNotApplied  EffectStatus = "not_applied"
	EffectCompensated EffectStatus = "compensated"
)

type EntryStateProvider

type EntryStateProvider struct {
	ID       string
	Contract state.Contract
}

EntryStateProvider describes state written before graph execution by one concrete invocation entry, such as a Trigger.

type ErrorClass

type ErrorClass string
const (
	ErrorUnknown           ErrorClass = "unknown"
	ErrorInvalidInput      ErrorClass = "invalid_input"
	ErrorInvalidOutput     ErrorClass = "invalid_output"
	ErrorTimeout           ErrorClass = "timeout"
	ErrorCanceled          ErrorClass = "canceled"
	ErrorRateLimited       ErrorClass = "rate_limited"
	ErrorUnavailable       ErrorClass = "unavailable"
	ErrorPermissionDenied  ErrorClass = "permission_denied"
	ErrorSideEffectFailed  ErrorClass = "side_effect_failed"
	ErrorResourceExhausted ErrorClass = "resource_exhausted"
	ErrorNonRetryable      ErrorClass = "non_retryable"
)

func ClassifyError

func ClassifyError(err error) ErrorClass

type EventDraft

type EventDraft struct {
	Type    string
	Payload any
}

type ExecutionError

type ExecutionError interface {
	error
	Class() ErrorClass
	RetryAfter() time.Duration
	Details() map[string]any
}

type ExecutionResult

type ExecutionResult struct {
	State    *state.State
	Patch    state.Patch
	Contract state.Contract
	Node     NodeResult
}

func ExecuteNode

func ExecuteNode(ctx context.Context, base *state.State, node Node) (ExecutionResult, error)

func ExecuteNodeWithOptions

func ExecuteNodeWithOptions(ctx context.Context, base *state.State, node Node, options NodeExecutionOptions) (ExecutionResult, error)

type FailureContext

type FailureContext struct {
	Stage        string
	ErrorClass   ErrorClass
	Error        string
	SourceNodeID string
	Details      map[string]any
}

func FailureFromContext

func FailureFromContext(ctx context.Context) (FailureContext, bool)

type InitialStateRequirement

type InitialStateRequirement struct {
	Path        string   `json:"path"`
	Nodes       []string `json:"nodes,omitempty"`
	Sources     []string `json:"sources,omitempty"`
	Type        string   `json:"type,omitempty"`
	Description string   `json:"description,omitempty"`
	Message     string   `json:"message,omitempty"`
}

InitialStateRequirement groups required read paths by state path. Nodes are the readers that need the path; Sources identify the entry provider or graph nodes that can provide it.

type InitialStateRequirements

type InitialStateRequirements struct {
	Required           []InitialStateRequirement `json:"required"`
	ProvidedByEntry    []InitialStateRequirement `json:"provided_by_entry"`
	ProvidedByUpstream []InitialStateRequirement `json:"provided_by_upstream"`
	Unresolved         []InitialStateRequirement `json:"unresolved"`
	Warnings           []ContractDiagnostic      `json:"warnings,omitempty"`
}

InitialStateRequirements describes which required state reads must be supplied by the graph's initial state and which can be satisfied by the graph itself.

type ModelCallEvent

type ModelCallEvent struct {
	Stage    ModelCallStage
	Request  llms.ModelRequest
	Stream   llms.ModelStreamEvent
	Response *llms.ModelResponse
	Err      error
	// CloneError reports observer fields omitted because they could not be
	// safely deep-cloned. It never exposes the original mutable value.
	CloneError error
}

type ModelCallObserver

type ModelCallObserver func(context.Context, ModelCallEvent) error

type ModelCallStage

type ModelCallStage string
const (
	ModelCallStarted   ModelCallStage = "started"
	ModelCallStream    ModelCallStage = "stream"
	ModelCallCompleted ModelCallStage = "completed"
	ModelCallFailed    ModelCallStage = "failed"
)

type ModelConfig

type ModelConfig struct {
	ID        string
	Provider  string
	APIFormat string
	Model     string
	BaseURL   string
	ExtraBody map[string]any
	APIKey    string
	Pricing   llms.ModelPricing
}

func ModelConfigByIDFromContext

func ModelConfigByIDFromContext(ctx context.Context, id string) (ModelConfig, bool)

type Node

type Node interface {
	ID() string
	Name() string
	Description() string
	Execute(ctx Context, access *state.Access) (NodeResult, error)
}

type NodeBase

type NodeBase struct {
	Spec   NodeSpec
	Effect EffectClass
}

func NewNodeBase

func NewNodeBase(spec NodeSpec) NodeBase

func (*NodeBase) Description

func (b *NodeBase) Description() string

func (*NodeBase) EffectClass

func (b *NodeBase) EffectClass() EffectClass

func (*NodeBase) ID

func (b *NodeBase) ID() string

func (*NodeBase) Name

func (b *NodeBase) Name() string

func (*NodeBase) SetID

func (b *NodeBase) SetID(id string)

func (*NodeBase) Validate

func (b *NodeBase) Validate() error

type NodeExecutionOptions

type NodeExecutionOptions struct {
	Contract               *state.Contract
	InputState             *state.State
	EnforceInputProjection bool
	ValidateRequiredReads  bool
	ValidateWrites         bool
	ApplyPatchToInput      bool
	OnRequiredReadIssues   func([]state.ValidationIssue)
	OnWriteIssues          func([]state.ValidationIssue)
	Reducers               map[string]state.Reducer
}

type NodeInfo

type NodeInfo struct {
	NodeID          string `json:"id" yaml:"id"`
	NodeName        string `json:"name" yaml:"name"`
	NodeDescription string `json:"description" yaml:"description"`
}

func (*NodeInfo) Description

func (n *NodeInfo) Description() string

func (*NodeInfo) ID

func (n *NodeInfo) ID() string

func (*NodeInfo) Name

func (n *NodeInfo) Name() string

type NodeInterrupt

type NodeInterrupt struct {
	NodeID string
	Value  any
}

func (*NodeInterrupt) Error

func (interrupt *NodeInterrupt) Error() string

type NodeOption

type NodeOption func(*NodeBase)

func WithEffectClass

func WithEffectClass(class EffectClass) NodeOption

func WithID

func WithID(id string) NodeOption

func WithName

func WithName(name string) NodeOption

type NodeRef

type NodeRef string

type NodeResult

type NodeResult struct {
	Patch     state.Patch
	Command   Command
	Events    []EventDraft
	Artifacts []ArtifactDraft
}

func Success

func Success() NodeResult

type NodeSpec

type NodeSpec struct {
	ID          string
	Name        string
	Description string
}

func (NodeSpec) Validate

func (s NodeSpec) Validate() error

type ReturnCommand

type ReturnCommand struct {
	Value any
}

type Send

type Send struct {
	Target         NodeRef
	Input          state.Patch
	CorrelationKey string
	OrderKey       string
}

type SuspendRequest

type SuspendRequest struct {
	Value any
}

type Tool

type Tool struct {
	Function      *llms.FunctionDefinition
	Handler       ToolHandler
	ExecutionMode ToolExecutionMode
	Permissions   []string
	Approval      ToolApprovalMode
	Effect        EffectClass
}

func FindTool

func FindTool(available map[string]Tool, name string) (Tool, bool)

func NewTool

func NewTool(function *llms.FunctionDefinition, handler ToolHandler) Tool

func (Tool) Definition

func (tool Tool) Definition() llms.ToolDefinition

func (Tool) Name

func (tool Tool) Name() string

type ToolApprovalDecision

type ToolApprovalDecision struct {
	ApprovalID string `json:"approval_id,omitempty"`
	Approved   bool   `json:"approved"`
	Actor      string `json:"actor,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

type ToolApprovalMode

type ToolApprovalMode string
const (
	ToolApprovalNever    ToolApprovalMode = "never"
	ToolApprovalRequired ToolApprovalMode = "required"
)

type ToolApprovalRequest

type ToolApprovalRequest struct {
	ToolCall    llms.ToolCall `json:"tool_call"`
	Permissions []string      `json:"permissions,omitempty"`
}

type ToolApprover

type ToolApprover interface {
	Approve(context.Context, ToolApprovalRequest) (ToolApprovalDecision, error)
}

func ToolApproverFromContext

func ToolApproverFromContext(ctx context.Context) ToolApprover

type ToolApproverFunc

func (ToolApproverFunc) Approve

type ToolExecutionEvent

type ToolExecutionEvent struct {
	Stage      ToolExecutionStage
	Tool       Tool
	Call       llms.ToolCall
	Result     llms.ToolResult
	Approval   *ToolApprovalDecision
	Err        error
	StartedAt  time.Time
	FinishedAt time.Time
	// CloneError reports observer fields omitted because they could not be
	// safely deep-cloned. It never changes the tool's actual returned value.
	CloneError error
	Operation  EffectOperation
}

type ToolExecutionMode

type ToolExecutionMode string
const (
	ToolExecutionLeaf      ToolExecutionMode = "leaf"
	ToolExecutionComposite ToolExecutionMode = "composite"
)

type ToolExecutionObserver

type ToolExecutionObserver func(context.Context, ToolExecutionEvent)

type ToolExecutionStage

type ToolExecutionStage string
const (
	ToolExecutionRequested      ToolExecutionStage = "requested"
	ToolExecutionApprovalNeeded ToolExecutionStage = "approval_needed"
	ToolExecutionApproved       ToolExecutionStage = "approved"
	ToolExecutionStarted        ToolExecutionStage = "started"
	ToolExecutionReturned       ToolExecutionStage = "returned"
	ToolExecutionFailed         ToolExecutionStage = "failed"
	ToolExecutionDenied         ToolExecutionStage = "denied"
)

type ToolHandler

type ToolHandler func(context.Context, llms.ToolCall) (llms.ToolResult, error)

Jump to

Keyboard shortcuts

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