Documentation
¶
Index ¶
- Constants
- func CaptureMarketAnalysis(ctx context.Context, client *game.Client, kb knowledge.Base, agentID string) error
- func CaptureMarketData(ctx context.Context, client *game.Client, kb knowledge.Base, agentID string) error
- func EmpireCapitalSystem(empire string) string
- func GetMarketAge(ctx context.Context, kb knowledge.Base, systemID, stationID string) (time.Duration, bool, error)
- func GetMarketAnalysisAge(ctx context.Context, kb knowledge.Base, systemID, stationID string) (time.Duration, bool, error)
- func RefreshMarketAnalysis(ctx context.Context, client *game.Client, kb knowledge.Base, agentID string) (*knowledge.MarketAnalysis, error)
- func RefreshMarketData(ctx context.Context, client *game.Client, kb knowledge.Base, agentID string) (*knowledge.MarketSnapshot, error)
- func SavePersonalityJSON(p Personality, path string) error
- func ShouldCaptureMarket(state *game.State, agentStatus Status) bool
- func ShouldRefreshMarket(ctx context.Context, kb knowledge.Base, systemID, stationID string) (bool, error)
- func ShouldRefreshMarketAnalysis(ctx context.Context, kb knowledge.Base, systemID, stationID string) (bool, error)
- type ActionResult
- type Agent
- type AgentState
- type BaseAgent
- func (a *BaseAgent) ClearActionQueue(reason string)
- func (a *BaseAgent) Decide(ctx context.Context, state *game.State) (Decision, error)
- func (a *BaseAgent) DequeueAction() (*PlannedAction, bool)
- func (a *BaseAgent) EnqueueActions(actions []PlannedAction)
- func (a *BaseAgent) GetActionQueue() []PlannedAction
- func (a *BaseAgent) GetRouteHome() ([]game.RouteStep, string)
- func (a *BaseAgent) ID() string
- func (a *BaseAgent) IsUsingQueuedAction() bool
- func (a *BaseAgent) Learn(result ActionResult) error
- func (a *BaseAgent) Memory() Memory
- func (a *BaseAgent) Name() string
- func (a *BaseAgent) Personality() Personality
- func (a *BaseAgent) SetRouteHome(route []game.RouteStep, fromSystem string)
- func (a *BaseAgent) SetUsingQueuedAction(using bool)
- func (a *BaseAgent) Start(ctx context.Context) error
- func (a *BaseAgent) Status() Status
- func (a *BaseAgent) Stop() error
- type Decision
- type EventCallback
- type Experience
- type Goal
- type History
- type HistoryEntry
- type KBMemory
- func (m *KBMemory) AddExperience(ctx context.Context, exp Experience) error
- func (m *KBMemory) GetRecentExperiences(count int) ([]Experience, error)
- func (m *KBMemory) GetUnknownConnections(systemID string) ([]string, error)
- func (m *KBMemory) KnownPOIs(systemID string) []game.POI
- func (m *KBMemory) KnownSystems() []game.SystemData
- func (m *KBMemory) RememberConnection(ctx context.Context, fromSystem, toSystem string) error
- func (m *KBMemory) RememberPOI(ctx context.Context, poi game.POI) error
- func (m *KBMemory) RememberSystem(ctx context.Context, sys game.SystemData) error
- func (m *KBMemory) SetCurrentTick(tick int64)
- type LLMClient
- type Manager
- func (m *Manager) AgentCount() int
- func (m *Manager) GetAgent(id string) (Agent, bool)
- func (m *Manager) GetCredentials(ctx context.Context, agentID string) (*credentials.Credentials, error)
- func (m *Manager) GetRunner(id string) (*Runner, bool)
- func (m *Manager) GetStatus() map[string]Status
- func (m *Manager) ListAgents() []Agent
- func (m *Manager) ListRunners() []*Runner
- func (m *Manager) SpawnAgent(ctx context.Context, personality Personality) (Agent, error)
- func (m *Manager) SpawnAgentWithGame(ctx context.Context, personality Personality) (*Runner, error)
- func (m *Manager) StopAgent(id string) error
- func (m *Manager) StopAll() error
- type ManagerConfig
- type Memory
- type Motivations
- type Personality
- type PlannedAction
- type Priority
- type ResourceInfo
- type Runner
- func (r *Runner) GetAgent() Agent
- func (r *Runner) GetCrashCount() int
- func (r *Runner) GetGameClient() game.GameClient
- func (r *Runner) GetHistory(limit int) []HistoryEntry
- func (r *Runner) GetLastActionTick() int64
- func (r *Runner) GetLastActionTime() time.Time
- func (r *Runner) HasCrashed() bool
- func (r *Runner) IsRunning() bool
- func (r *Runner) SetEventCallback(cb EventCallback)
- func (r *Runner) Start(ctx context.Context) error
- func (r *Runner) Stop() error
- type RunnerConfig
- type Status
Constants ¶
const ( MaxConnectionRetries = 3 MaxLoginRetries = 3 )
Retry configuration constants
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 )
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, kb knowledge.Base, agentID string) error
CaptureMarketAnalysis fetches and stores market analysis data
func CaptureMarketData ¶
func CaptureMarketData(ctx context.Context, client *game.Client, kb knowledge.Base, agentID string) error
CaptureMarketData fetches and stores market data
func EmpireCapitalSystem ¶
EmpireCapitalSystem returns the capital system ID for a given empire.
func GetMarketAge ¶
func GetMarketAge(ctx context.Context, kb knowledge.Base, systemID, stationID string) (time.Duration, bool, error)
GetMarketAge returns the age of the most recent market snapshot and whether it exists
func GetMarketAnalysisAge ¶
func GetMarketAnalysisAge(ctx context.Context, kb knowledge.Base, systemID, stationID string) (time.Duration, bool, error)
GetMarketAnalysisAge returns the age of the most recent market analysis
func RefreshMarketAnalysis ¶
func RefreshMarketAnalysis(ctx context.Context, client *game.Client, kb knowledge.Base, agentID string) (*knowledge.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, kb, "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, kb knowledge.Base, agentID string) (*knowledge.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, kb, "craftsman-1")
if err != nil {
return fmt.Errorf("failed to refresh market: %w", err)
}
// Use snapshot.Listings to make trading/crafting decisions
func SavePersonalityJSON ¶
func SavePersonalityJSON(p Personality, path string) error
SavePersonalityJSON saves a personality to a JSON file
func ShouldCaptureMarket ¶
ShouldCaptureMarket determines if market should be captured based on agent state
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, state *game.State) (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 ¶
ClearActionQueue removes all actions from the queue
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 ¶
GetRouteHome returns the cached route home and the system it was calculated from.
func (*BaseAgent) IsUsingQueuedAction ¶
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) Personality ¶
func (a *BaseAgent) Personality() Personality
Personality returns the agent's personality
func (*BaseAgent) SetRouteHome ¶
SetRouteHome caches the route to the agent's safe system.
func (*BaseAgent) SetUsingQueuedAction ¶
SetUsingQueuedAction sets whether the agent is currently using a queued action
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 EventCallback ¶
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 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 ¶
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) 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
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 ¶
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 ¶
GetUnknownConnections finds unexplored connections
func (*KBMemory) KnownSystems ¶
func (m *KBMemory) KnownSystems() []game.SystemData
KnownSystems returns all known systems
func (*KBMemory) RememberConnection ¶
RememberConnection stores a connection in memory
func (*KBMemory) RememberPOI ¶
RememberPOI stores a POI in memory
func (*KBMemory) RememberSystem ¶
RememberSystem stores a system in memory
func (*KBMemory) SetCurrentTick ¶
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 ¶
AgentCount returns the number of active agents
func (*Manager) GetCredentials ¶
func (m *Manager) GetCredentials(ctx context.Context, agentID string) (*credentials.Credentials, error)
GetCredentials retrieves credentials for an agent
func (*Manager) ListRunners ¶
ListRunners returns all runners
func (*Manager) SpawnAgent ¶
SpawnAgent creates and starts a new agent with game connection This is a wrapper around SpawnAgentWithGame for backwards compatibility
func (*Manager) SpawnAgentWithGame ¶
SpawnAgentWithGame creates an agent with game connection and starts it
type ManagerConfig ¶
type ManagerConfig struct {
MaxAgents int
GameServerURL string
AgentsDataDir string
RunnerConfig RunnerConfig
DebugLogger *log.Logger
}
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"`
}
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 ¶
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) GetCrashCount ¶
GetCrashCount returns the number of consecutive errors
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 ¶
GetLastActionTick returns the tick of the last action
func (*Runner) GetLastActionTime ¶
GetLastActionTime returns the time of the last action
func (*Runner) HasCrashed ¶
HasCrashed returns whether the runner has crashed (exceeded max retries)
func (*Runner) SetEventCallback ¶
func (r *Runner) SetEventCallback(cb EventCallback)
SetEventCallback sets the callback function for streaming events
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