agent

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: AGPL-3.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxResultSize         = truncate.DefaultMaxBytes
	DefaultMaxRetries            = 9
	DefaultMaxTokens             = 16384
	ContextSafetyTokens          = 4096
	DefaultCompactionReserve     = 16384
	DefaultKeepRecentTokens      = 20000
	DefaultTokenBudgetWarningPct = 80
	DefaultInboxCapacity         = 64
	SubInboxCapacity             = 16
	DefaultMaxParallelTools      = 16
)
View Source
const (
	CacheNone  = provider.CacheNone
	CacheShort = provider.CacheShort
	CacheLong  = provider.CacheLong
)
View Source
const (
	StopReasonCompleted  = hooks.StopReasonCompleted
	StopReasonTerminated = hooks.StopReasonTerminated
	StopReasonStopped    = hooks.StopReasonStopped
	StopReasonBudget     = hooks.StopReasonBudget
	StopReasonError      = hooks.StopReasonError
	StopReasonCanceled   = hooks.StopReasonCanceled
)
View Source
const DefaultContextWindow = 128000

DefaultContextWindow is used when a model-specific context size is unknown.

View Source
const DefaultMinLoopInterval = 10 * time.Second

Variables

View Source
var (
	TextMessage = provider.TextMessage

	NewProvider              = provider.NewProvider
	NewProviderFromResolved  = provider.NewProviderFromResolved
	ResolveProvider          = provider.Resolve
	InferProviderFromBaseURL = provider.InferFromBaseURL
	NormalizeProvider        = provider.NormalizeProvider
	IsSupportedProvider      = provider.IsSupportedProvider

	ErrCallTimeout      = provider.ErrCallTimeout
	ErrStreamStalled    = provider.ErrStreamStalled
	ErrStreamIncomplete = provider.ErrStreamIncomplete
)

Functions

func ContextWithLoopScheduler

func ContextWithLoopScheduler(ctx context.Context, scheduler *LoopScheduler) context.Context

ContextWithLoopScheduler scopes direct command execution to one runtime session. Agent tool calls carry the scheduler in their Config snapshot.

func ModelContextWindow

func ModelContextWindow(model string) int

ModelContextWindow returns the known context window for model.

func RetryDelay

func RetryDelay(attempt int) time.Duration

RetryDelay returns the backoff duration for the given attempt index (0-based). It keeps the original conservative policy (1s·2^attempt, capped at 10s) for backward compatibility with external callers such as runner and webagent reconnect logic.

func SaveCheckpoint

func SaveCheckpoint(dir string, data *CheckpointData) error

func TextInput

func TextInput(text string) *aop.Message

TextInput builds a plain user message from text.

Types

type APIError

type APIError = provider.APIError

type AfterToolCallContext

type AfterToolCallContext struct {
	AssistantMessage *aop.Message
	ToolCall         *aop.ToolCall
	Result           string
	IsError          bool
	SystemPrompt     string
	Messages         []*aop.Message
}

type AfterToolCallResult

type AfterToolCallResult struct {
	Result  *string
	IsError *bool
	Flow    ToolFlowDecision
}

type Agent

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

func NewAgent

func NewAgent(cfg Config) *Agent

NewAgent creates an Agent from a Config.

func (*Agent) Compact

func (a *Agent) Compact(ctx context.Context, cfg CompactConfig) (*CompactResult, error)

func (*Agent) ContextWindow

func (a *Agent) ContextWindow() int

func (*Agent) Continue

func (a *Agent) Continue(ctx context.Context, opts ...RunOption) (*Result, error)

Continue resumes the agent without a new prompt (e.g. after tool results).

func (*Agent) Derive

func (a *Agent) Derive() *Agent

Derive creates a new Agent with the same infrastructure (provider, tools, model, logger) but clean state. Use for spawning independent agent tasks.

func (*Agent) DeriveNamed

func (a *Agent) DeriveNamed(name string) *Agent

DeriveNamed creates an isolated child agent and gives its AOP stream a distinct actor name while preserving the current session as its parent.

func (*Agent) EmitStatus

func (a *Agent) EmitStatus(state string, detail proto.Message, turnID ...string)

EmitStatus emits an AOP status event on the agent's session. Used by out-of-kernel helpers (evaluator) so their events carry session/seq.

func (*Agent) IsRunning

func (a *Agent) IsRunning() bool

IsRunning returns whether the agent loop is currently executing.

func (*Agent) LoadMessages

func (a *Agent) LoadMessages(messages []*aop.Message)

func (*Agent) MessagesSnapshot

func (a *Agent) MessagesSnapshot() []*aop.Message

func (*Agent) Model

func (a *Agent) Model() string

func (*Agent) Reset

func (a *Agent) Reset()

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, input *aop.Message, opts ...RunOption) (*Result, error)

func (*Agent) SessionID

func (a *Agent) SessionID() string

func (*Agent) SetLogger

func (a *Agent) SetLogger(logger telemetry.Logger)

func (*Agent) SetMaxTurns

func (a *Agent) SetMaxTurns(n int)

SetMaxTurns overrides the per-run turn cap (0 = unlimited). Applied to the next Run; a run already in flight keeps the cap it snapshotted at its start.

func (*Agent) SetProvider

func (a *Agent) SetProvider(p Provider, model string)

SetProvider hot-swaps the LLM provider (and model, when non-empty) on the agent. A run already in flight keeps the provider it snapshotted at start; the next run picks up the new one. Safe to call concurrently with Run/Continue.

func (*Agent) SetProviderConfig

func (a *Agent) SetProviderConfig(p Provider, providerConfig ProviderConfig)

SetProviderConfig hot-swaps the provider together with its model limits.

type AgentType

type AgentType struct {
	FormattedPrompt string
	Model           string
	Background      bool
}

type AgentTypeResolver

type AgentTypeResolver func(name string) (AgentType, error)

type BeforeToolCallContext

type BeforeToolCallContext struct {
	AssistantMessage *aop.Message
	ToolCall         *aop.ToolCall
	SystemPrompt     string
	Messages         []*aop.Message
}

type BeforeToolCallResult

type BeforeToolCallResult struct {
	Block  bool
	Reason string
}

type CacheRetention

type CacheRetention = provider.CacheRetention

type ChatCompletionRequest

type ChatCompletionRequest = provider.ChatCompletionRequest

type ChatCompletionResponse

type ChatCompletionResponse = provider.ChatCompletionResponse

type ChatCompletionStreamEvent

type ChatCompletionStreamEvent = provider.ChatCompletionStreamEvent

type CheckpointData

type CheckpointData struct {
	Version   int            `json:"version"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	Model     string         `json:"model,omitempty"`
	Provider  string         `json:"provider,omitempty"`
	Messages  []*aop.Message `json:"messages"`
	// MessageCounter resumes AOP message_id allocation ("m-<n>") after restore.
	MessageCounter int64 `json:"message_counter,omitempty"`
}

func LoadCheckpoint

func LoadCheckpoint(path string) (*CheckpointData, error)

type CheckpointInfo

type CheckpointInfo struct {
	Path      string
	CreatedAt time.Time
	UpdatedAt time.Time
	ModTime   time.Time
	Model     string
	Provider  string
	Messages  int
}

func ListCheckpoints

func ListCheckpoints(dir string) ([]CheckpointInfo, error)

func (CheckpointInfo) SortTime

func (s CheckpointInfo) SortTime() time.Time

type Choice

type Choice = provider.Choice

type CompactConfig

type CompactConfig struct {
	Provider           Provider
	Model              string
	KeepRecentTokens   int
	ReserveTokens      int
	MaxTokens          int
	CustomInstructions string
}

type CompactResult

type CompactResult struct {
	TokensBefore int
	TokensAfter  int
	KeptMessages int
}

type CompactionSettings

type CompactionSettings struct {
	ReserveTokens    int
	KeepRecentTokens int
}

type Config

type Config struct {
	Provider         Provider
	Tools            tool.Executor
	Model            string
	SystemPrompt     string
	SystemPromptFn   SystemPromptFunc
	Messages         []*aop.Message
	MaxTokens        int
	ContextWindow    int
	Compaction       CompactionSettings
	Temperature      *float64
	Stream           bool
	MaxRetries       int
	TokenBudget      int
	Logger           telemetry.Logger
	TransformContext TransformContextFunc
	Bus              EventEmitter
	// Hooks is the typed extension registry shared by a runtime and its derived
	// agents. Nil means no handlers and keeps the dispatch fast path allocation-free.
	Hooks *hooks.Registry
	// OnRunEnd fires once per run with the final result — replaces the old
	// EventAgentEnd Messages subscription for session persistence.
	OnRunEnd         func(*Result)
	BeforeToolCall   func(context.Context, BeforeToolCallContext) (*BeforeToolCallResult, error)
	AfterToolCall    func(context.Context, AfterToolCallContext) (*AfterToolCallResult, error)
	MaxTurns         int
	LoopScheduler    *LoopScheduler
	Inbox            inbox.Inbox
	Expander         *inbox.Expander
	MaxResultSize    int
	MaxParallelTools int
	CacheRetention   CacheRetention
	SessionID        string
	TurnID           string
	ParentSessionID  string
	ParentToolCallID string
	Delegation       *types.DelegationDetail
	// AgentName tags emitted AOP events; defaults to "aiscan".
	AgentName string
	// MessageCounter seeds message_id allocation ("m-<n>") when a session is
	// restored; Result.MessageCounter carries the final value for saving.
	MessageCounter int64
	// CaptureProviderFrames emits exact provider request/response bytes as AOP
	// ProviderFrame events. Disabled by default because payloads may be sensitive.
	CaptureProviderFrames bool
	// contains filtered or unexported fields
}

func (Config) WithAgentName

func (c Config) WithAgentName(name string) Config

func (Config) WithBus

func (c Config) WithBus(b EventEmitter) Config

func (Config) WithCacheRetention

func (c Config) WithCacheRetention(r CacheRetention) Config

func (Config) WithContextWindow

func (c Config) WithContextWindow(n int) Config

func (Config) WithExpander

func (c Config) WithExpander(e *inbox.Expander) Config

func (Config) WithHooks

func (c Config) WithHooks(r *hooks.Registry) Config

func (Config) WithInbox

func (c Config) WithInbox(ib inbox.Inbox) Config

func (Config) WithLogger

func (c Config) WithLogger(l telemetry.Logger) Config

func (Config) WithLoopScheduler

func (c Config) WithLoopScheduler(s *LoopScheduler) Config

func (Config) WithMaxRetries

func (c Config) WithMaxRetries(n int) Config

func (Config) WithMaxTokens

func (c Config) WithMaxTokens(n int) Config

func (Config) WithMessages

func (c Config) WithMessages(msgs []*aop.Message) Config

func (Config) WithModel

func (c Config) WithModel(m string) Config

func (Config) WithOnRunEnd

func (c Config) WithOnRunEnd(fn func(*Result)) Config

func (Config) WithProvider

func (c Config) WithProvider(p Provider) Config

func (Config) WithSessionID

func (c Config) WithSessionID(id string) Config

func (Config) WithStream

func (c Config) WithStream(s bool) Config

func (Config) WithSystemPrompt

func (c Config) WithSystemPrompt(s string) Config

func (Config) WithTemperature

func (c Config) WithTemperature(t float64) Config

func (Config) WithTokenBudget

func (c Config) WithTokenBudget(n int) Config

func (Config) WithTools

func (c Config) WithTools(t tool.Executor) Config

func (Config) WithTransformContext

func (c Config) WithTransformContext(fn TransformContextFunc) Config

func (Config) WithTurnID

func (c Config) WithTurnID(id string) Config

type CronExpr

type CronExpr struct {
	Minute  []bool // [0..59]
	Hour    []bool // [0..23]
	Day     []bool // [1..31]
	Month   []bool // [1..12]
	Weekday []bool // [0..6]
	Raw     string
}

CronExpr represents a parsed 5-field cron expression:

minute(0-59) hour(0-23) day(1-31) month(1-12) weekday(0-6, 0=Sun)

func ParseCron

func ParseCron(expr string) (*CronExpr, error)

ParseCron parses a standard 5-field cron expression.

Supports: literal, *(any), */step, range(a-b), range/step(a-b/step), list(a,b,c).

func (*CronExpr) Next

func (c *CronExpr) Next(t time.Time) time.Time

Next returns the next fire time strictly after t.

func (*CronExpr) String

func (c *CronExpr) String() string

type EventEmitter

type EventEmitter interface {
	Emit(*aop.Event)
}

EventEmitter is the narrow event sink an agent needs — callers may wrap a bus with stamping/routing middleware (e.g. the runner's sessionEmitter) instead of handing over a raw *eventbus.Bus.

type FinishTool

type FinishTool struct{}

func NewFinishTool

func NewFinishTool() *FinishTool

func (*FinishTool) Definition

func (t *FinishTool) Definition() *ToolDefinition

func (*FinishTool) Description

func (t *FinishTool) Description() string

func (*FinishTool) Execute

func (t *FinishTool) Execute(_ context.Context, arguments string) (*tool.Result, error)

func (*FinishTool) Name

func (t *FinishTool) Name() string

type LoopEntry

type LoopEntry struct {
	Name      string
	Cron      *CronExpr
	Interval  time.Duration
	Prompt    string
	Mode      LoopMode
	Immediate bool
	CreatedAt time.Time
}

LoopEntry defines a single recurring task.

Schedule priority: Cron > Interval.

  • If Cron is set, it drives scheduling (Interval is ignored).
  • If only Interval is set, it is used as a simple ticker.
  • ModeInbox requires Prompt.

func (LoopEntry) Schedule

func (e LoopEntry) Schedule() string

Schedule returns a human-readable string for the schedule.

type LoopInfo

type LoopInfo struct {
	Name      string    `json:"name"`
	Prompt    string    `json:"prompt"`
	Schedule  string    `json:"schedule"`
	Mode      LoopMode  `json:"mode"`
	FireCount int       `json:"fire_count"`
	LastFired time.Time `json:"last_fired,omitempty"`
}

type LoopMode

type LoopMode int
const (
	// ModeInbox pushes LoopEntry.Prompt to the inbox as a system message.
	// The agent's turn loop drains it and lets the LLM decide what to do.
	ModeInbox LoopMode = iota
)

type LoopScheduler

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

func LoopSchedulerFromContext

func LoopSchedulerFromContext(ctx context.Context) *LoopScheduler

LoopSchedulerFromContext resolves both direct-command and agent-tool-call contexts without exposing the agent's full Config.

func NewLoopScheduler

func NewLoopScheduler(ib inbox.Inbox, logger telemetry.Logger) *LoopScheduler

func (*LoopScheduler) Active

func (s *LoopScheduler) Active() int

func (*LoopScheduler) Add

func (s *LoopScheduler) Add(ctx context.Context, entry LoopEntry) (string, error)

func (*LoopScheduler) List

func (s *LoopScheduler) List() []LoopInfo

func (*LoopScheduler) Remove

func (s *LoopScheduler) Remove(name string) error

func (*LoopScheduler) SetLogger

func (s *LoopScheduler) SetLogger(logger telemetry.Logger)

func (*LoopScheduler) Stop

func (s *LoopScheduler) Stop()

type Provider

type Provider = provider.Provider

type ProviderConfig

type ProviderConfig = provider.ProviderConfig

type ProviderEntry

type ProviderEntry struct {
	Provider Provider
	Model    string
}

type ProviderRawFrame

type ProviderRawFrame = provider.RawFrame

type Result

type Result struct {
	Output      string
	NewMessages []*aop.Message
	Messages    []*aop.Message
	Turns       int
	TotalUsage  *aop.TokenUsage
	// TurnUsages holds per-turn usage; the turn number is the slice index + 1.
	TurnUsages     []*aop.TokenUsage
	ContextTokens  int
	Stop           StopReason
	Err            error
	MessageCounter int64
}

type RunOption

type RunOption func(*Config)

Run executes the agent with an input and returns the result. For one-shot usage, create an agent and call Run once. For multi-turn, call Run repeatedly — message history accumulates.

func WithRunMaxTurns

func WithRunMaxTurns(maxTurns int) RunOption

func WithTurnID

func WithTurnID(turnID string) RunOption

type State

type State struct {
	SystemPrompt string
	Messages     []*aop.Message
	Tools        tool.Executor
	ErrorMessage string
	LastError    error
}

type StopReason

type StopReason = hooks.StopReason

StopReason is owned by agent/hooks so lifecycle events can carry it without introducing an import cycle back to the root agent package.

type StreamingProvider

type StreamingProvider = provider.StreamingProvider

type SubAgentArgs

type SubAgentArgs struct {
	Action  string `` /* 203-byte string literal not displayed */
	Prompt  string `json:"prompt"            jsonschema:"description=Task description for the subagent (required for create)"`
	Mode    string `` /* 224-byte string literal not displayed */
	Type    string `json:"type,omitempty"    jsonschema:"description=Agent type name (a skill with agent:true)"`
	Name    string `json:"name,omitempty"    jsonschema:"description=Human-readable label for tracking"`
	Message string `json:"message,omitempty" jsonschema:"description=Message to send (action=message requires name)"`
	Timeout string `json:"timeout,omitempty" jsonschema:"description=Optional timeout for sync mode (e.g. 30s or 2m). Returns error on timeout."`
}

type SubAgentTool

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

func NewSubAgentTool

func NewSubAgentTool(resolve AgentTypeResolver) *SubAgentTool

func (*SubAgentTool) Definition

func (t *SubAgentTool) Definition() *aop.ToolDefinition

func (*SubAgentTool) Description

func (t *SubAgentTool) Description() string

func (*SubAgentTool) Execute

func (t *SubAgentTool) Execute(ctx context.Context, arguments string) (*tool.Result, error)

func (*SubAgentTool) Name

func (t *SubAgentTool) Name() string

type SystemPromptFunc

type SystemPromptFunc func(cfg *Config) string

SystemPromptFunc is called at the start of each turn to produce the system prompt. Receives the current config context so it can adapt to active tools, model, etc.

type ToolDefinition

type ToolDefinition = aop.ToolDefinition

type ToolFlowDecision

type ToolFlowDecision int
const (
	ToolFlowContinue ToolFlowDecision = iota
	ToolFlowTerminate
)

type TransformContextFunc

type TransformContextFunc func([]*aop.Message) []*aop.Message

Directories

Path Synopsis
Package hooks is the agent kernel's single extension mechanism: typed hook points with explicit result semantics and error policies.
Package hooks is the agent kernel's single extension mechanism: typed hook points with explicit result semantics and error policies.
Package tmux provides a thin event-aware wrapper around the shared github.com/chainreactors/utils/pty manager.
Package tmux provides a thin event-aware wrapper around the shared github.com/chainreactors/utils/pty manager.

Jump to

Keyboard shortcuts

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