agent

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxResultSize         = truncate.DefaultMaxBytes
	DefaultMaxRetries            = 9
	DefaultTokenBudgetWarningPct = 80
	DefaultInboxCapacity         = 64
	SubInboxCapacity             = 16
	DefaultMaxParallelTools      = 16
)
View Source
const (
	CacheNone  = provider.CacheNone
	CacheShort = provider.CacheShort
	CacheLong  = provider.CacheLong
)
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 (
	NewTextMessage       = provider.NewTextMessage
	NewToolResultMessage = provider.NewToolResultMessage
	NewMultimodalMessage = provider.NewMultimodalMessage
	TextPart             = provider.TextPart
	ImagePart            = provider.ImagePart
	ParseDataURI         = provider.ParseDataURI

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

	ErrCallTimeout   = provider.ErrCallTimeout
	ErrStreamStalled = provider.ErrStreamStalled
)

Functions

func LatestSessionPath

func LatestSessionPath(dir string) string

func ModelContextWindow added in v0.2.7

func ModelContextWindow(model string) int

ModelContextWindow returns the known context window for model.

func RetryDelay

func RetryDelay(attempt int) time.Duration

func SaveSession

func SaveSession(dir string, data *SessionData) error

Types

type APIError

type APIError = provider.APIError

type AfterToolCallContext

type AfterToolCallContext struct {
	AssistantMessage ChatMessage
	ToolCall         ToolCall
	Result           string
	IsError          bool
	SystemPrompt     string
	Messages         []ChatMessage
}

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

func (a *Agent) Continue(ctx context.Context) (*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) IsRunning

func (a *Agent) IsRunning() bool

IsRunning returns whether the agent loop is currently executing.

func (*Agent) LoadMessages

func (a *Agent) LoadMessages(messages []ChatMessage)

func (*Agent) Reset

func (a *Agent) Reset()

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, prompt string) (*Result, error)

Run executes the agent with a prompt 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 (*Agent) SteerUserMessage

func (a *Agent) SteerUserMessage(content string)

SteerUserMessage pushes user input into the running agent's inbox. The loop drains it at the next turn boundary.

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 ChatMessage
	ToolCall         ToolCall
	SystemPrompt     string
	Messages         []ChatMessage
}

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 ChatMessage

type ChatMessage = provider.ChatMessage

type ChatMessageDelta

type ChatMessageDelta = provider.ChatMessageDelta

type Choice

type Choice = provider.Choice

type Config

type Config struct {
	Provider         Provider
	Tools            *commands.CommandRegistry
	Model            string
	Fallbacks        []ProviderEntry
	SystemPrompt     string
	SystemPromptFn   SystemPromptFunc
	Messages         []ChatMessage
	MaxTokens        int
	Temperature      *float64
	Stream           bool
	MaxRetries       int
	TokenBudget      int
	ResponseFormat   *ResponseFormat
	Logger           telemetry.Logger
	TransformContext TransformContextFunc
	Bus              *eventbus.Bus[Event]
	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
	ParentSessionID  string
}

func (Config) WithBus

func (c Config) WithBus(b *eventbus.Bus[Event]) Config

func (Config) WithCacheRetention

func (c Config) WithCacheRetention(r CacheRetention) Config

func (Config) WithExpander

func (c Config) WithExpander(e *inbox.Expander) 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 []ChatMessage) Config

func (Config) WithModel

func (c Config) WithModel(m string) Config

func (Config) WithProvider

func (c Config) WithProvider(p Provider) Config

func (Config) WithResponseFormat

func (c Config) WithResponseFormat(rf *ResponseFormat) 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 *commands.CommandRegistry) Config

func (Config) WithTransformContext

func (c Config) WithTransformContext(fn TransformContextFunc) Config

type ContentPart

type ContentPart = provider.ContentPart

type CronExpr added in v0.2.7

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

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

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

Next returns the next fire time strictly after t.

func (*CronExpr) String added in v0.2.7

func (c *CronExpr) String() string

type Event

type Event struct {
	Type            EventType
	SessionID       string
	ParentSessionID string
	Turn            int
	EmittedAt       time.Time
	Request         *ChatCompletionRequest
	Message         ChatMessage
	Messages        []ChatMessage
	NewMessages     []ChatMessage
	ToolResults     []ChatMessage
	ToolCallID      string
	ToolName        string
	Arguments       string
	Result          string
	IsError         bool
	Err             error
	StartedAt       time.Time // tool execution start time (set on ToolExecutionEnd)
	Stop            StopReason
	Usage           *Usage
	TotalUsage      *Usage // cumulative usage across all turns (set on TurnEnd/AgentEnd)
	ContextTokens   int
	EvalRound       int
	EvalPass        bool
	EvalReason      string
	EvalError       string
}

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

type EventType

type EventType string
const (
	EventAgentStart         EventType = "agent_start"
	EventAgentEnd           EventType = "agent_end"
	EventTurnStart          EventType = "turn_start"
	EventTurnEnd            EventType = "turn_end"
	EventLLMRequest         EventType = "llm_request"
	EventMessageStart       EventType = "message_start"
	EventMessageUpdate      EventType = "message_update"
	EventMessageEnd         EventType = "message_end"
	EventToolExecutionStart EventType = "tool_execution_start"
	EventToolExecutionEnd   EventType = "tool_execution_end"
	EventTokenBudgetWarning EventType = "token_budget_warning"
	EventEvalStart          EventType = "eval_start"
	EventEvalEnd            EventType = "eval_end"
	EventEvalError          EventType = "eval_error"
)

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) (commands.ToolResult, error)

func (*FinishTool) Name

func (t *FinishTool) Name() string

type FunctionCall

type FunctionCall = provider.FunctionCall

type FunctionCallDelta

type FunctionCallDelta = provider.FunctionCallDelta

type FunctionDefinition

type FunctionDefinition = provider.FunctionDefinition

type ImageURL

type ImageURL = provider.ImageURL

type JSONSchemaSpec

type JSONSchemaSpec = provider.JSONSchemaSpec

type LoopCommand added in v0.2.7

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

LoopCommand is a pseudo-command invoked via bash:

bash(command="loop '*/5 * * * *' check scan progress")
bash(command="loop 30s check status")
bash(command="loop list")
bash(command="loop stop loop-a1b2c3d4")

func NewLoopCommand added in v0.2.7

func NewLoopCommand(scheduler *LoopScheduler) *LoopCommand

func (*LoopCommand) Execute added in v0.2.7

func (c *LoopCommand) Execute(ctx context.Context, args []string) error

func (*LoopCommand) Name added in v0.2.7

func (c *LoopCommand) Name() string

func (*LoopCommand) Usage added in v0.2.7

func (c *LoopCommand) Usage() string

type LoopEntry

type LoopEntry struct {
	Name      string
	Cron      *CronExpr
	Interval  time.Duration
	Prompt    string
	Mode      LoopMode
	Immediate bool
	OnFire    func(ctx context.Context, entry LoopEntry) (string, error)
	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.
  • ModeIndependent requires OnFire.

func (LoopEntry) Schedule added in v0.2.7

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

	// ModeIndependent calls LoopEntry.OnFire in a goroutine.
	// Used for work that needs its own agent run (e.g. swarm heartbeat).
	ModeIndependent
)

type LoopScheduler

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

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

func (s *LoopScheduler) SetMinInterval(d time.Duration)

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 ResponseFormat

type ResponseFormat = provider.ResponseFormat

type Result

type Result struct {
	Output        string
	NewMessages   []ChatMessage
	Messages      []ChatMessage
	Turns         int
	TotalUsage    Usage
	TurnUsages    []TurnUsage
	ContextTokens int
	Stop          StopReason
	Err           error
}

type SessionData

type SessionData 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  []ChatMessage `json:"messages"`
}

func LoadSession

func LoadSession(path string) (*SessionData, error)

type State

type State struct {
	SystemPrompt string
	Messages     []ChatMessage
	Tools        *commands.CommandRegistry
	ErrorMessage string
	LastError    error
}

type StopReason

type StopReason string
const (
	StopReasonCompleted  StopReason = "completed"
	StopReasonTerminated StopReason = "terminated"
	StopReasonStopped    StopReason = "stopped"
	StopReasonBudget     StopReason = "budget"
	StopReasonError      StopReason = "error"
	StopReasonCanceled   StopReason = "canceled"
)

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(agent *Agent, parentInbox inbox.Inbox, resolve AgentTypeResolver) *SubAgentTool

func (*SubAgentTool) Definition

func (t *SubAgentTool) Definition() ToolDefinition

func (*SubAgentTool) Description

func (t *SubAgentTool) Description() string

func (*SubAgentTool) Execute

func (t *SubAgentTool) Execute(ctx context.Context, arguments string) (commands.ToolResult, error)

func (*SubAgentTool) Name

func (t *SubAgentTool) Name() string

func (*SubAgentTool) RunningCount

func (t *SubAgentTool) RunningCount() int

func (*SubAgentTool) SetMessages

func (t *SubAgentTool) SetMessages(fn func() []ChatMessage)

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 ToolCall

type ToolCall = provider.ToolCall

type ToolCallDelta

type ToolCallDelta = provider.ToolCallDelta

type ToolDefinition

type ToolDefinition = provider.ToolDefinition

type ToolFlowDecision

type ToolFlowDecision int
const (
	ToolFlowContinue ToolFlowDecision = iota
	ToolFlowTerminate
)

type TransformContextFunc

type TransformContextFunc func([]ChatMessage) []ChatMessage

type TurnUsage

type TurnUsage struct {
	Turn             int `json:"turn"`
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
	CacheReadTokens  int `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
}

type Usage

type Usage = provider.Usage

Directories

Path Synopsis
Package tmux provides a thin wrapper around the shared pty.Manager from github.com/chainreactors/utils/pty.
Package tmux provides a thin wrapper around the shared pty.Manager from github.com/chainreactors/utils/pty.

Jump to

Keyboard shortcuts

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