agent

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 18 Imported by: ? modules, 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

Index

Constants

View Source
const (
	MaxConnectionRetries = 3
	MaxLoginRetries      = 3
)

Retry configuration constants

View Source
const (
	// MarketAnalysisFreshnessThreshold is how long market analysis is considered fresh (2 hours)
	// Analysis data changes less frequently than raw listings, so we can cache it longer
	MarketAnalysisFreshnessThreshold = 720 * time.Second
)
View Source
const (
	// MarketFreshnessThreshold is how long market data is considered fresh (1 hour)
	// Since game ticks are 10 seconds, this is 360 ticks
	MarketFreshnessThreshold = 360 * time.Second
)

Variables

This section is empty.

Functions

func CaptureMarketAnalysis

func CaptureMarketAnalysis(ctx context.Context, client *game.Client, mc *market.Collector, agentID string) error

CaptureMarketAnalysis fetches and stores market analysis data via the market collector.

func CaptureMarketData

func CaptureMarketData(ctx context.Context, client *game.Client, mc *market.Collector, agentID string) error

CaptureMarketData fetches and stores market data via the market collector.

func EmpireCapitalSystem

func EmpireCapitalSystem(empire string) string

EmpireCapitalSystem returns the capital system ID for a given empire.

func RefreshMarketAnalysis

func RefreshMarketAnalysis(ctx context.Context, client *game.Client, mc *market.Collector, agentID string) (*market.MarketAnalysis, error)

RefreshMarketAnalysis ensures fresh market analysis insights for the current station. It provides AI-generated trading insights that can help identify profitable opportunities.

Returns the market analysis (either cached or freshly captured) and any error.

The analysis includes: - Top insights (AI-identified trading opportunities) - Market analysis data - XP gained from scanning - Scanning range and stations in range

Usage example:

analysis, err := agent.RefreshMarketAnalysis(ctx, client, mc, "trader-1")
if err != nil {
    return fmt.Errorf("failed to refresh market analysis: %w", err)
}
for _, insight := range analysis.TopInsights {
    fmt.Printf("Insight: %v\n", insight)
}

func RefreshMarketData

func RefreshMarketData(ctx context.Context, client *game.Client, mc *market.Collector, agentID string) (*market.MarketSnapshot, error)

RefreshMarketData ensures fresh market data for the current station. It checks if existing market data is less than an hour old, and if not, captures new market data from the game server.

Returns the market snapshot (either cached or freshly captured) and any error.

The agentID parameter is used for tracking who captured the market data.

Usage example:

snapshot, err := agent.RefreshMarketData(ctx, client, mc, "craftsman-1")
if err != nil {
    return fmt.Errorf("failed to refresh market: %w", err)
}
// Use snapshot.Orders to make trading/crafting decisions

func SavePersonalityJSON

func SavePersonalityJSON(p Personality, path string) error

SavePersonalityJSON saves a personality to a JSON file

func ShouldCaptureMarket

func ShouldCaptureMarket(state *game.State, agentStatus Status) bool

ShouldCaptureMarket determines if market should be captured based on agent state

func WirePassengerObserver added in v0.2.0

func WirePassengerObserver(c *game.Client, kb knowledge.Base)

WirePassengerObserver registers a PassengerObserver on the given game client that persists each batch of passenger observations into the knowledge base's identity catalog. Errors from RecordPassengers are logged and swallowed — a failed write must never break the game response path.

func WirePlayerObserver added in v0.2.0

func WirePlayerObserver(c *game.Client, kb knowledge.Base, enq FactionEnqueuer)

WirePlayerObserver registers a PlayerObserver on the given game client that persists each batch of observations to the knowledge base. Errors from RecordSightings are logged and swallowed — a failed write must never break the game response path. When enq is non-nil, the distinct non-empty faction ids in each batch are also enqueued for faction_info backfill (a non-blocking call — the fetch happens on enq's own goroutine).

func WireStorageCapture added in v0.2.0

func WireStorageCapture(client *game.Client, kb knowledge.Base, agentID string, logger *log.Logger)

WireStorageCapture configures a game client to automatically save storage snapshots to the knowledge base whenever a view_storage response is received.

Types

type ActionResult

type ActionResult struct {
	Action   string // The action that was taken
	Target   string // The target of the action (if any)
	Success  bool
	Message  string
	NewState *game.State
	Reward   float64 // For reinforcement learning
	Error    error
}

ActionResult represents the result of taking an action

type Agent

type Agent interface {
	// Identity
	Name() string
	ID() string

	// Personality
	Personality() Personality

	// Decision Making
	Decide(ctx context.Context, es EnrichedState) (Decision, error)

	// Learning
	Learn(result ActionResult) error
	Memory() Memory

	// Tactical Action Queue
	EnqueueActions(actions []PlannedAction)
	DequeueAction() (*PlannedAction, bool)
	GetActionQueue() []PlannedAction
	ClearActionQueue(reason string)
	SetUsingQueuedAction(using bool)
	IsUsingQueuedAction() bool

	// Route Home
	SetRouteHome(route []game.RouteStep, fromSystem string)
	GetRouteHome() ([]game.RouteStep, string)

	// Lifecycle
	Start(ctx context.Context) error
	Stop() error
	Status() Status
}

Agent represents an autonomous game-playing agent

type AgentState

type AgentState int
const (
	AgentStateIdle AgentState = iota
	AgentStateDeciding
	AgentStateActing
	AgentStateWaiting
	AgentStateError
	AgentStateStopped
)

func (AgentState) String

func (s AgentState) String() string

String returns the string representation of AgentState

type BaseAgent

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

BaseAgent provides default agent behavior

func NewBaseAgent

func NewBaseAgent(
	id string,
	personality Personality,
	memory Memory,
	llmClient LLMClient,
) *BaseAgent

NewBaseAgent creates a new agent

func (*BaseAgent) ClearActionQueue

func (a *BaseAgent) ClearActionQueue(reason string)

ClearActionQueue removes all actions from the queue

func (*BaseAgent) Decide

func (a *BaseAgent) Decide(ctx context.Context, es EnrichedState) (Decision, error)

Decide uses the LLM to choose the next action. The EnrichedState provides both the live game state (via GameState()) and optional KB enrichment. Currently the prompt is built from the raw game state; enriched accessors will be incorporated incrementally.

func (*BaseAgent) DequeueAction

func (a *BaseAgent) DequeueAction() (*PlannedAction, bool)

DequeueAction removes and returns the next action from the queue

func (*BaseAgent) EnqueueActions

func (a *BaseAgent) EnqueueActions(actions []PlannedAction)

EnqueueActions adds a sequence of planned actions to the queue

func (*BaseAgent) GetActionQueue

func (a *BaseAgent) GetActionQueue() []PlannedAction

GetActionQueue returns a copy of the current action queue

func (*BaseAgent) GetRouteHome

func (a *BaseAgent) GetRouteHome() ([]game.RouteStep, string)

GetRouteHome returns the cached route home and the system it was calculated from.

func (*BaseAgent) ID

func (a *BaseAgent) ID() string

ID returns the agent's ID

func (*BaseAgent) IsUsingQueuedAction

func (a *BaseAgent) IsUsingQueuedAction() bool

IsUsingQueuedAction returns whether the agent is currently using a queued action

func (*BaseAgent) Learn

func (a *BaseAgent) Learn(result ActionResult) error

Learn updates the agent's memory based on action results

func (*BaseAgent) MarkProcessed added in v0.2.0

func (a *BaseAgent) MarkProcessed(ids ...string)

MarkProcessed marks the given message IDs as read in the mailbox.

func (*BaseAgent) Memory

func (a *BaseAgent) Memory() Memory

Memory returns the agent's memory

func (*BaseAgent) Name

func (a *BaseAgent) Name() string

Name returns the agent's name

func (*BaseAgent) Personality

func (a *BaseAgent) Personality() Personality

Personality returns the agent's personality

func (*BaseAgent) RecentFromSender added in v0.2.0

func (a *BaseAgent) RecentFromSender(senderID string, n int) []mbox.Message

RecentFromSender returns the n most recent messages from a specific sender.

func (*BaseAgent) SetMbox added in v0.2.0

func (a *BaseAgent) SetMbox(store *mbox.Store)

SetMbox attaches a mailbox store to the agent for inter-agent messaging.

func (*BaseAgent) SetRouteHome

func (a *BaseAgent) SetRouteHome(route []game.RouteStep, fromSystem string)

SetRouteHome caches the route to the agent's safe system.

func (*BaseAgent) SetUsingQueuedAction

func (a *BaseAgent) SetUsingQueuedAction(using bool)

SetUsingQueuedAction sets whether the agent is currently using a queued action

func (*BaseAgent) Start

func (a *BaseAgent) Start(ctx context.Context) error

Start begins the agent's main loop

func (*BaseAgent) Status

func (a *BaseAgent) Status() Status

Status returns the agent's current status

func (*BaseAgent) Stop

func (a *BaseAgent) Stop() error

Stop halts the agent (safe to call multiple times)

func (*BaseAgent) UnreadMatching added in v0.2.0

func (a *BaseAgent) UnreadMatching(keywords []string) []mbox.Message

UnreadMatching returns unread messages matching any of the given keywords. Duplicates (a message matching multiple keywords) are deduplicated.

type Decision

type Decision struct {
	Action         string          `json:"action"`
	Target         string          `json:"target,omitempty"`
	Reasoning      string          `json:"reasoning"`
	Confidence     float64         `json:"confidence,omitempty"`
	Alternatives   []string        `json:"alternatives,omitempty"`
	PlannedActions []PlannedAction `json:"planned_actions,omitempty"` // NEW: 5-step tactical plan
}

Decision represents a chosen action

type EnrichedState added in v0.2.0

type EnrichedState interface {
	// Refresh rebuilds enrichment layers from current game state and KB.
	// Called once per decision cycle.
	Refresh(ctx context.Context)

	// GameState returns the underlying game state pointer.
	GameState() *game.State

	// SystemSecurity returns a human-readable security label for the current system.
	SystemSecurity() string

	// CanDo returns whether a specific action is valid given current state.
	CanDo(action string) bool
}

EnrichedState provides enriched game state for agent decision cycles. The primary implementation is *agentstate.AgentState which layers KB data, action space evaluation, and agent context on top of live game state. When no enriched state is available, rawEnrichedState provides a minimal fallback wrapping a cloned *game.State.

func NewRawEnrichedState added in v0.2.0

func NewRawEnrichedState(state *game.State) EnrichedState

NewRawEnrichedState creates a minimal EnrichedState wrapping a cloned game state. All enrichment accessors return safe zero values.

type EnrichedStateFactory added in v0.2.0

type EnrichedStateFactory func(state *game.State, kb knowledge.Base) EnrichedState

EnrichedStateFactory creates an EnrichedState for a runner. The factory receives the live game state and the knowledge base, and should return an EnrichedState (typically *agentstate.AgentState). If nil, runners fall back to rawEnrichedState with no KB enrichment.

type EventCallback

type EventCallback func(agentID string, eventType string, data any)

EventCallback is called when events occur during agent execution

type Experience

type Experience struct {
	Time        string
	Type        string
	Description string
	Outcome     string
	Location    string
}

Experience represents a significant event in the agent's history

type FactionEnqueuer added in v0.2.0

type FactionEnqueuer interface {
	Enqueue(ids ...string)
}

FactionEnqueuer schedules background backfill of faction details for the given faction ids. Satisfied by *faction.FactionBackfiller. Kept as a local interface so this package needn't import pkg/faction.

type Goal

type Goal struct {
	Type      string  // Goal type: "wealth", "skill", "exploration", "resource", "reputation"
	Target    string  // Specific target (e.g., "Mining_5", "10000_credits", "Sol", "iron")
	Progress  float64 // Progress towards goal (0.0 to 1.0)
	Priority  int     // Priority level (1-10, higher is more important)
	Reasoning string  // Why this goal was set
}

Goal represents a strategic objective for an agent

type History

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

History maintains a ring buffer of action history entries

func NewHistory

func NewHistory(maxSize int) *History

NewHistory creates a new history tracker with specified max size

func (*History) Add

func (h *History) Add(entry HistoryEntry)

Add appends a new entry to the history (ring buffer)

func (*History) Clear

func (h *History) Clear()

Clear removes all entries from history

func (*History) GetRecent

func (h *History) GetRecent(limit int) []HistoryEntry

GetRecent returns the most recent N entries (up to limit)

func (*History) GetSince

func (h *History) GetSince(tick int64) []HistoryEntry

GetSince returns all entries since a specific tick

func (*History) Size

func (h *History) Size() int

Size returns the current number of entries in history

type HistoryEntry

type HistoryEntry struct {
	Tick       int64     `json:"tick"`
	Timestamp  time.Time `json:"timestamp"`
	Action     string    `json:"action"`
	Target     string    `json:"target,omitempty"`
	Confidence float64   `json:"confidence"`
	Result     string    `json:"result"`
	Error      string    `json:"error,omitempty"`
	Reasoning  string    `json:"reasoning,omitempty"`
}

HistoryEntry represents a single action in the agent's history

type KBMemory

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

KBMemory implements the Memory interface using the knowledge base

func NewKBMemory

func NewKBMemory(kb knowledge.Base, agentID string) *KBMemory

NewKBMemory creates a new memory backed by the knowledge base

func (*KBMemory) AddExperience

func (m *KBMemory) AddExperience(ctx context.Context, exp Experience) error

AddExperience adds an experience to memory

func (*KBMemory) GetRecentExperiences

func (m *KBMemory) GetRecentExperiences(count int) ([]Experience, error)

GetRecentExperiences retrieves recent experiences

func (*KBMemory) GetUnknownConnections

func (m *KBMemory) GetUnknownConnections(systemID string) ([]string, error)

GetUnknownConnections finds unexplored connections

func (*KBMemory) KnownPOIs

func (m *KBMemory) KnownPOIs(systemID string) []game.POI

KnownPOIs returns POIs in a system

func (*KBMemory) KnownSystems

func (m *KBMemory) KnownSystems() []game.SystemData

KnownSystems returns all known systems

func (*KBMemory) RememberConnection

func (m *KBMemory) RememberConnection(ctx context.Context, fromSystem, toSystem string) error

RememberConnection stores a connection in memory

func (*KBMemory) RememberPOI

func (m *KBMemory) RememberPOI(ctx context.Context, poi game.POI) error

RememberPOI stores a POI in memory

func (*KBMemory) RememberSystem

func (m *KBMemory) RememberSystem(ctx context.Context, sys game.SystemData) error

RememberSystem stores a system in memory

func (*KBMemory) SetCurrentTick

func (m *KBMemory) SetCurrentTick(tick int64)

SetCurrentTick sets the game tick to stamp on subsequent writes.

type LLMClient

type LLMClient interface {
	Decide(ctx context.Context, prompt string) (*llm.DecisionResponse, error)
	TestConnection(ctx context.Context) error
}

LLMClient defines the interface for LLM operations This allows injecting mock clients for testing

type Manager

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

Manager manages multiple agents with game connections

func NewManager

func NewManager(
	kb knowledge.Base,
	llmClient *llm.Client,
	credsProvider credentials.Provider,
	config ManagerConfig,
) *Manager

NewManager creates a new agent manager

func NewManagerLegacy

func NewManagerLegacy(
	kb knowledge.Base,
	llmClient *llm.Client,
	credsProvider credentials.Provider,
	maxAgents int,
) *Manager

NewManagerLegacy creates a manager with legacy signature (for backwards compatibility)

func (*Manager) AgentCount

func (m *Manager) AgentCount() int

AgentCount returns the number of active agents (LLM + strategy)

func (*Manager) GetAgent

func (m *Manager) GetAgent(id string) (Agent, bool)

GetAgent retrieves an agent by ID

func (*Manager) GetCredentials

func (m *Manager) GetCredentials(ctx context.Context, agentID string) (*credentials.Credentials, error)

GetCredentials retrieves credentials for an agent

func (*Manager) GetRunner

func (m *Manager) GetRunner(id string) (*Runner, bool)

GetRunner retrieves a runner by ID

func (*Manager) GetStatus

func (m *Manager) GetStatus() map[string]Status

GetStatus returns the status of all agents

func (*Manager) GetStrategyRunner added in v0.2.0

func (m *Manager) GetStrategyRunner(id string) (*StrategyRunner, bool)

GetStrategyRunner retrieves a strategy runner by agent ID.

func (*Manager) ListAgents

func (m *Manager) ListAgents() []Agent

ListAgents returns all agents

func (*Manager) ListRunners

func (m *Manager) ListRunners() []*Runner

ListRunners returns all runners

func (*Manager) ListStrategyRunners added in v0.2.0

func (m *Manager) ListStrategyRunners() []*StrategyRunner

ListStrategyRunners returns all strategy runners.

func (*Manager) SpawnAgent

func (m *Manager) SpawnAgent(ctx context.Context, personality Personality) (Agent, error)

SpawnAgent creates and starts a new agent with game connection This is a wrapper around SpawnAgentWithGame for backwards compatibility

func (*Manager) SpawnAgentWithGame

func (m *Manager) SpawnAgentWithGame(ctx context.Context, personality Personality) (*Runner, error)

SpawnAgentWithGame creates an agent with game connection and starts it

func (*Manager) SpawnStrategyAgent added in v0.2.0

func (m *Manager) SpawnStrategyAgent(ctx context.Context, agentID string, strat strategy.Strategy, params map[string]string) (*StrategyRunner, error)

SpawnStrategyAgent creates a game-connected agent running a strategy instead of LLM.

func (*Manager) StopAgent

func (m *Manager) StopAgent(id string) error

StopAgent stops and removes an agent

func (*Manager) StopAll

func (m *Manager) StopAll() error

StopAll stops all agents

func (*Manager) StopStrategyAgent added in v0.2.0

func (m *Manager) StopStrategyAgent(id string) error

StopStrategyAgent stops and removes a strategy agent.

func (*Manager) SwapStrategy added in v0.2.0

func (m *Manager) SwapStrategy(ctx context.Context, agentID string, newStrat strategy.Strategy, params map[string]string) error

SwapStrategy stops the current strategy runner for an agent and starts a new one.

type ManagerConfig

type ManagerConfig struct {
	MaxAgents            int
	GameServerURL        string
	Transport            string // "ws" (default) or "mcp"
	AgentsDataDir        string
	RunnerConfig         RunnerConfig
	DebugLogger          *log.Logger
	EnrichedStateFactory EnrichedStateFactory
}

ManagerConfig holds configuration for the agent manager

func DefaultManagerConfig

func DefaultManagerConfig() ManagerConfig

DefaultManagerConfig returns sensible defaults

type Memory

type Memory interface {
	// Knowledge access
	KnownSystems() []game.SystemData
	KnownPOIs(systemID string) []game.POI
	GetUnknownConnections(systemID string) ([]string, error)

	// Memory update
	RememberSystem(ctx context.Context, system game.SystemData) error
	RememberPOI(ctx context.Context, poi game.POI) error
	RememberConnection(ctx context.Context, fromSystem, toSystem string) error

	// Experience
	AddExperience(ctx context.Context, exp Experience) error
	GetRecentExperiences(count int) ([]Experience, error)
}

Memory stores agent knowledge

type Motivations

type Motivations struct {
	Primary   string             `yaml:"primary"`
	Secondary string             `yaml:"secondary"`
	Tertiary  string             `yaml:"tertiary"`
	Weights   map[string]float64 `yaml:"weights,omitempty"`
}

Motivations drives agent behavior

type Personality

type Personality struct {
	Name            string             `yaml:"name"`
	ID              string             `yaml:"id"`
	Role            string             `yaml:"role"`
	Traits          map[string]float64 `yaml:"traits"`
	Skills          map[string]string  `yaml:"skills"`
	Motivations     Motivations        `yaml:"motivations"`
	Biography       string             `yaml:"biography"`
	Faction         string             `yaml:"faction,omitempty"`
	ServiceName     string             `yaml:"service_name,omitempty" json:"service_name,omitempty"`
	PrimarySkill    string             `yaml:"primary_skill,omitempty" json:"primary_skill,omitempty"`
	GameSkills      []string           `yaml:"game_skills,omitempty" json:"game_skills,omitempty"`
	BackgroundSkill string             `yaml:"background_skill,omitempty" json:"background_skill,omitempty"`
	DecisionMode    string             `yaml:"decision_mode,omitempty" json:"decision_mode,omitempty"`
}

Personality defines an agent's traits and motivations

func LoadPersonalityJSON

func LoadPersonalityJSON(path string) (Personality, error)

LoadPersonalityJSON loads a personality from a JSON file

type PlannedAction

type PlannedAction struct {
	Sequence   int               `json:"sequence"`             // 1-5, order in the plan
	Action     string            `json:"action"`               // Action name (travel, mine, wait, etc.)
	Target     string            `json:"target,omitempty"`     // Target for the action (POI ID, system name)
	Parameters map[string]string `json:"parameters,omitempty"` // Additional parameters
	Reasoning  string            `json:"reasoning"`            // Why this step is needed
	Condition  string            `json:"condition,omitempty"`  // Condition for execution ("after_arrival", "if_cargo_full")
}

PlannedAction represents a future action in the tactical queue

type Priority

type Priority struct {
	Focus       string   // Current strategic focus (e.g., "mining", "trading", "exploring", "combat")
	Constraints []string // Active constraints preventing certain actions (e.g., "low_fuel", "cargo_full", "no_credits")
	Urgency     int      // Urgency level (1-10, higher means more urgent action needed)
}

Priority represents the agent's current strategic focus and constraints

type ResourceInfo

type ResourceInfo struct {
	ResourceID string
	Richness   float64
	Remaining  float64
}

ResourceInfo represents resource data at a POI

type Runner

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

Runner wraps an agent with its game client and runs the play loop

func NewRunner

func NewRunner(agent Agent, gameClient game.GameClient, config RunnerConfig) *Runner

NewRunner creates a new agent runner

func (*Runner) GetAgent

func (r *Runner) GetAgent() Agent

GetAgent returns the wrapped agent

func (*Runner) GetCrashCount

func (r *Runner) GetCrashCount() int

GetCrashCount returns the number of consecutive errors

func (*Runner) GetEnrichedState added in v0.2.0

func (r *Runner) GetEnrichedState() EnrichedState

GetEnrichedState returns the configured enriched state, or nil.

func (*Runner) GetGameClient

func (r *Runner) GetGameClient() game.GameClient

GetGameClient returns the game client

func (*Runner) GetHistory

func (r *Runner) GetHistory(limit int) []HistoryEntry

GetHistory returns the most recent N history entries

func (*Runner) GetLastActionTick

func (r *Runner) GetLastActionTick() int64

GetLastActionTick returns the tick of the last action

func (*Runner) GetLastActionTime

func (r *Runner) GetLastActionTime() time.Time

GetLastActionTime returns the time of the last action

func (*Runner) GetToTEvaluator added in v0.2.0

func (r *Runner) GetToTEvaluator() ToTEvaluator

GetToTEvaluator returns the configured ToT evaluator, or nil.

func (*Runner) HasCrashed

func (r *Runner) HasCrashed() bool

HasCrashed returns whether the runner has crashed (exceeded max retries)

func (*Runner) IsPaused added in v0.2.0

func (r *Runner) IsPaused() bool

IsPaused returns whether the runner is currently paused.

func (*Runner) IsRunning

func (r *Runner) IsRunning() bool

IsRunning returns whether the runner is currently running

func (*Runner) Pause added in v0.2.0

func (r *Runner) Pause()

Pause stops the runner from starting new decision/ToT cycles. Any in-progress LLM call will complete, but no new cycles will begin.

func (*Runner) Resume added in v0.2.0

func (r *Runner) Resume()

Resume allows the runner to start decision cycles again.

func (*Runner) SetEnrichedState added in v0.2.0

func (r *Runner) SetEnrichedState(es EnrichedState)

SetEnrichedState configures the enriched state provider for this runner. When set, each decision cycle will call Refresh() and pass the enriched state to Agent.Decide and ToTEvaluator. When nil, a raw fallback wrapping the cloned game state is used instead.

func (*Runner) SetEventCallback

func (r *Runner) SetEventCallback(cb EventCallback)

SetEventCallback sets the callback function for streaming events

func (*Runner) SetToTEvaluator added in v0.2.0

func (r *Runner) SetToTEvaluator(eval ToTEvaluator)

SetToTEvaluator enables Tree-of-Thought decision making for this runner.

func (*Runner) Start

func (r *Runner) Start(ctx context.Context) error

Start begins the agent's play loop

func (*Runner) Stop

func (r *Runner) Stop() error

Stop halts the agent runner

type RunnerConfig

type RunnerConfig struct {
	// DecisionInterval is how often the agent makes decisions
	// Should be aligned with game tick rate (11 seconds for 10-second ticks to avoid edge cases)
	// Query commands can run anytime, but action commands are rate-limited by the server
	DecisionInterval time.Duration

	// MaxRetries is the maximum number of consecutive decision errors before stopping
	MaxRetries int

	// ActionTimeout is how long to wait for action result before considering it failed
	ActionTimeout time.Duration

	// Logger for runner events
	Logger *log.Logger
}

RunnerConfig holds configuration for the agent runner

func DefaultRunnerConfig

func DefaultRunnerConfig() RunnerConfig

DefaultRunnerConfig returns sensible defaults

type Status

type Status struct {
	State         AgentState
	CurrentAction string
	LastUpdate    string
	Error         error
}

Status represents the current status of an agent

type StrategyRunner added in v0.2.0

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

StrategyRunner runs a Strategy instead of an LLM-based decision loop. It implements a similar lifecycle to Runner but delegates behavior to the strategy.

func NewStrategyRunner added in v0.2.0

func NewStrategyRunner(cfg StrategyRunnerConfig) *StrategyRunner

NewStrategyRunner creates a new strategy runner.

func (*StrategyRunner) AgentID added in v0.2.0

func (sr *StrategyRunner) AgentID() string

AgentID returns the agent ID.

func (*StrategyRunner) GameClient added in v0.2.0

func (sr *StrategyRunner) GameClient() game.GameClient

GameClient returns the underlying game client.

func (*StrategyRunner) IsRunning added in v0.2.0

func (sr *StrategyRunner) IsRunning() bool

IsRunning returns whether the strategy is currently executing.

func (*StrategyRunner) Start added in v0.2.0

func (sr *StrategyRunner) Start(ctx context.Context) error

Start begins running the strategy in a goroutine.

func (*StrategyRunner) Stop added in v0.2.0

func (sr *StrategyRunner) Stop() error

Stop cancels the running strategy.

func (*StrategyRunner) Strategy added in v0.2.0

func (sr *StrategyRunner) Strategy() strategy.Strategy

Strategy returns the underlying strategy.

type StrategyRunnerConfig added in v0.2.0

type StrategyRunnerConfig struct {
	AgentID    string
	Strategy   strategy.Strategy
	GameClient game.GameClient
	KB         knowledge.Base
	Parameters map[string]string
	Logger     *log.Logger
}

StrategyRunnerConfig holds config for creating a StrategyRunner.

type ToTContext added in v0.2.0

type ToTContext struct {
	RecentActions []HistoryEntry
	Goal          *Goal
	Priority      *Priority
}

ToTContext carries additional context for the Tree-of-Thought evaluator.

type ToTEvaluator added in v0.2.0

type ToTEvaluator interface {
	// EvaluateToT runs the Tree-of-Thought pipeline and returns the best decision.
	// The second return value is the full thought tree for event emission.
	EvaluateToT(ctx context.Context, personality Personality, es EnrichedState, totCtx *ToTContext) (Decision, any, error)
}

ToTEvaluator is an optional evaluator that uses Tree-of-Thought reasoning for richer decision making. Implemented by pkg/tot.Evaluator via an adapter.

Jump to

Keyboard shortcuts

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