game

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 20 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

Overview

Example (CaptainsLog)

Example demonstrates basic usage of the captain's log system

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/rsned/spacemolt/pkg/game"
)

func main() {
	agentID := "example-explorer"
	defer func() { _ = os.RemoveAll("data/agents/" + agentID) }() // Cleanup

	// Write a captain's log entry
	entry := &game.AgentLog{
		AgentName:   "Captain Example",
		CurrentGoal: "Exploring uncharted systems",
		Location:    "System: frontier-7, POI: asteroid_belt",
		Notes: []string{
			"Found rich mineral deposits",
			"Low fuel - need to return to station soon",
		},
	}

	err := game.WriteCaptainsLog(agentID, entry)
	if err != nil {
		log.Fatal(err)
	}

	// Read the latest log entry
	latest, err := game.ReadLatestCaptainsLog(agentID)
	if err != nil {
		log.Fatal(err)
	}

	if latest != nil {
		fmt.Printf("Agent: %s\n", latest.AgentName)
		fmt.Printf("Goal: %s\n", latest.CurrentGoal)
		fmt.Printf("Location: %s\n", latest.Location)
		fmt.Printf("Notes: %d\n", len(latest.Notes))
	}

}
Output:
Agent: Captain Example
Goal: Exploring uncharted systems
Location: System: frontier-7, POI: asteroid_belt
Notes: 2
Example (Recovery)

Example_recovery demonstrates how to recover from a captain's log on startup

package main

import (
	"fmt"
	"os"

	"github.com/rsned/spacemolt/pkg/game"
)

func main() {
	agentID := "recovery-example"
	defer func() { _ = os.RemoveAll("data/agents/" + agentID) }() // Cleanup

	// Simulate previous mission
	_ = game.WriteCaptainsLog(agentID, &game.AgentLog{
		AgentName:   "Captain Recovery",
		CurrentGoal: "Mining operations in progress",
		Location:    "System: sol, POI: sol_belt",
	})

	// Agent restarts and recovers state
	log, err := game.ReadLatestCaptainsLog(agentID)
	if err != nil {
		fmt.Println("Error reading log")
		return
	}

	if log != nil {
		fmt.Printf("Resuming: %s\n", log.CurrentGoal)
		fmt.Printf("Last Location: %s\n", log.Location)
	} else {
		fmt.Println("No previous mission found, starting fresh")
	}

}
Output:
Resuming: Mining operations in progress
Last Location: System: sol, POI: sol_belt

Index

Examples

Constants

View Source
const (
	SleepTick   = 10 * time.Second // One game server tick is 10 seconds.
	SleepQuick  = SleepTick / 5    // Non-mutation command and queries.
	SleepShort  = SleepTick / 3    // Short operations (refuel, repair, install)
	SleepMedium = SleepTick / 2    // Medium wait operations
	SleepLong   = 2 * SleepTick    // Longer wait operations

	SleepDock   = 3 * SleepTick / 2 // Dock timing (15s)
	SleepUndock = 3 * SleepTick / 2 // Undock timing (15s)

	SleepTravel = 1 * SleepTick // POI travel within system
	SleepJump   = 2 * SleepTick // System jump travel timea

	SleepReconnect = 30 * time.Second // Reconnection recovery wait
)

Sleep durations for various game operations

View Source
const (
	HullCriticalThreshold   = 40.0 // Hull percent: critical damage, flee immediately
	HullDamagedThreshold    = 50.0 // Hull percent: damaged, seek repairs
	HullCombatFleeThreshold = 70.0 // Hull percent in combat: consider fleeing
)

Hull percentage thresholds

View Source
const (
	FuelCriticalThreshold = 0.3 // 30% fuel: critically low, refuel soon
	FuelLowThreshold      = 0.8 // 80% fuel: refuel when at station
)

Fuel thresholds

View Source
const (
	CargoFullThreshold       = 0.9 // 90% capacity: consider full, return to sell
	CargoHalfFullThreshold   = 0.5 // 50% capacity: half full, limit purchases
	CargoReserveForPurchases = 0.5 // Reserve 50% space when buying equipment
)

Cargo capacity thresholds

View Source
const (
	CombatHullCriticalThreshold = 30.0 // Hull percent: critical in combat, flee immediately
	CombatHullFleeThreshold     = 70.0 // Hull percent: flee if below this AND shields low
	CombatShieldLowThreshold    = 10.0 // Shield percent: low enough to combine with hull for flee decision
)

Combat thresholds

View Source
const (
	MiningCycleTime    = 11 * time.Second // Time between mining operations
	GameTickRate       = 1 * time.Second  // Basic game tick rate
	ModuleInstallDelay = 10 * time.Second // Delay between module installations
)

Timing constants

View Source
const (
	ClientName = "rsned/spacemolt"
	VersionID  = "v0.0.1"
	UserAgent  = ClientName + "/" + VersionID
)

Client identity

View Source
const (
	// FreshnessResourcePOI is the threshold for resource POIs (asteroid_belt, asteroid_field, gas_cloud, ice_field): 6 hours
	FreshnessResourcePOI = 6 * 60 * 60 // 21,600 ticks

	// FreshnessDefaultPOI is the threshold for non-resource POIs (planet, sun, jump_gate, wreck): 1 week
	FreshnessDefaultPOI = 7 * 24 * 60 * 60 // 604,800 ticks

	// FreshnessStationPOI is the threshold for stations and bases: 1 day
	FreshnessStationPOI = 24 * 60 * 60 // 86,400 ticks

	// FreshnessSystem is the threshold for system data: 1 day
	FreshnessSystem = 24 * 60 * 60 // 86,400 ticks
)

Data freshness thresholds (in game ticks, where 1 tick = 1 second)

View Source
const (
	TimestampDaily   = "20060102"       // YYYYMMDD - daily snapshots
	TimestampPrecise = "20060102150405" // YYYYMMDDHHMMSS - precise timestamps
	TimestampISO8601 = time.RFC3339     // ISO8601 format for data fields
)

TimestampFormat constants for consistent filename generation

View Source
const (
	// DefaultGameServerURL is the default WebSocket endpoint for the game
	DefaultGameServerURL = "wss://game.spacemolt.com/ws"
)
View Source
const (
	MinimumPurchaseThreshold = 100.0 // Minimum credits to attempt any purchase
)

Credit thresholds

View Source
const ServerAPIVersion = "v0.112.0"

ServerAPIVersion is the game server API version this client was built against. See server_docs/api.md for full API documentation. This version should match the version documented at the top of server_docs/api.md

View Source
const (
	ShieldDepletedThreshold = 10.0 // Shield percent: depleted, combine with hull for flee decision
)

Shield percentage thresholds

Variables

View Source
var RoleCategories = map[string][]string{
	"miner":     {"Mining", "Mining Capital"},
	"fighter":   {"Fighter", "Heavy Fighter", "Interceptor", "Cruiser"},
	"trader":    {"Freighter", "Bulk Hauler", "Armed Freighter", "Armored Transport"},
	"explorer":  {"Explorer", "Expedition", "Scout", "Armed Explorer"},
	"pirate":    {"Raider", "Boarding Craft", "Assault", "Assault Cruiser"},
	"salvager":  {"Salvager"},
	"engineer":  {"Repair", "Construction", "Field Repair"},
	"craftsman": {"Refinery", "Gas Refinery", "Ice Refinery"},
}

RoleCategories maps agent roles to their upgrade-eligible ship classes. Ships are queried from the knowledge DB filtered by these classes.

Functions

func CanUpgradeAnyShip

func CanUpgradeAnyShip(currentShipClass string, availableCredits float64, tiers []UpgradeTier) bool

CanUpgradeAnyShip checks if any ship upgrade is affordable based on current ship class

func CountModulesInCargo

func CountModulesInCargo(state *State, itemID string) int

CountModulesInCargo counts how many of a specific module type are in cargo

func CountModulesInstalled

func CountModulesInstalled(state *State, itemID string) int

CountModulesInstalled counts how many of a specific module type are installed

func DefaultEquipment

func DefaultEquipment(ship ShipDef, role string) (itemID string, count int)

DefaultEquipment returns the item ID and count to install after buying a ship.

func DefaultRecipeSelector

func DefaultRecipeSelector(client *Client, logger *log.Logger, ctx context.Context, storage StorageManager) ([]string, error)

DefaultRecipeSelector selects basic recipes based on available cargo and skills For now, it prioritizes: 1. basic_smelt_iron (ore_iron -> iron_ingot) 2. basic_copper_processing (ore_copper -> copper_plate) When agents reach higher skill levels (crafting > 5, refinement > 5, crafting_advanced > 1), more advanced recipes will be unlocked

func DockAtStation

func DockAtStation(client *Client, ctx context.Context, stationPOI string) error

DockAtStation docks the client at a station POI Returns error if docking fails (excluding "already docked" which is treated as success)

func EmpireHomeSystem

func EmpireHomeSystem(empire string) string

EmpireHomeSystem returns the home system for a given empire name.

func FindRouteByOreAndTarget

func FindRouteByOreAndTarget(homeEmpire, oreID, targetEmpire string) (outbound TradeRoute, returnLeg TradeRoute, found bool)

FindRouteByOreAndTarget finds a specific outbound route by ore ID and target empire.

func FindStationID

func FindStationID(state *State) string

FindStationID returns the ID of the first station in the current system, or empty string if none found

func FormatCaptainsLogForDisplay

func FormatCaptainsLogForDisplay(entry *AgentLog) string

FormatCaptainsLogForDisplay formats a captain's log entry for human-readable display

func GenerateDataFilename

func GenerateDataFilename(name, timestamp, dataType string) string

GenerateDataFilename creates a standardized filename for data files Format: {sanitized_name}.{timestamp}.{type}.json

Examples:

  • GenerateDataFilename("Solar System", "20250101", "system") -> "solar_system.20250101.system.json"
  • GenerateDataFilename("Alpha Station", "20250102150405", "market") -> "alpha_station.20250102150405.market.json"

func GetCaptainsLogDir

func GetCaptainsLogDir(agentID string) string

GetCaptainsLogDir returns the path to the captain's log directory for an agent

func GetMarketPricesForCargo

func GetMarketPricesForCargo(cargo []CargoItem, listings []MarketListing) map[string]int

GetMarketPricesForCargo creates a price map for cargo items using market listings. This helper uses the "highest buy order" price for each item (what buyers are willing to pay). If an item has no buy orders, it uses the "lowest sell order" price minus 1 credit to be competitive. If no market data exists for an item, it won't be in the returned map (use default price instead).

Parameters:

  • cargo: The ship's cargo to price
  • listings: Market listings from Client.GetMarketListings() or view_market

Returns:

  • priceMap: Map of item_id to suggested price_each for selling

func HasStation

func HasStation(state *State) bool

HasStation checks if the current system has a station

func InitializeAgent

func InitializeAgent(agentID string, logger *log.Logger, ctx context.Context) (*Client, *Credentials, error)

InitializeAgent creates and initializes a game client for an autonomous agent It handles the complete setup flow: load credentials, create client, set up handlers, connect to server, wait for ready, and authenticate.

Parameters:

  • agentID: The agent identifier (used for logger prefix and credential path)
  • logger: A logger instance for agent-specific logging
  • ctx: Context for lifecycle management

Returns:

  • *Client: Fully initialized and authenticated game client
  • *Credentials: The loaded credentials (for reference if needed)
  • error: Any error during initialization

Example usage:

client, creds, err := game.InitializeAgent("miner-1", logger, ctx)
if err != nil {
    log.Fatalf("Failed to initialize agent: %v", err)
}
defer client.Close()

// Now use the client for autonomous operations...

func IsOreOrResource

func IsOreOrResource(itemID string) bool

IsOreOrResource returns true if item is ore or a resource (should be sold, not installed)

func LootWreck

func LootWreck(client *Client, logger *log.Logger, ctx context.Context, wreckID string) error

LootWreck loots all items from a wreck Useful for fighters and pirates who defeat NPCs

func NavigateAndDock(client *Client, ctx context.Context, logger *log.Logger) error

NavigateAndDock finds the station in the current system, travels to it, and docks.

func NavigateToSystem(client *Client, ctx context.Context, targetSystem string, logger *log.Logger) error

NavigateToSystem uses FindRoute + sequential Jump calls to travel from the current system to the target system. Handles multi-hop routes. The agent must be undocked before calling this function.

func POIFreshnessThreshold

func POIFreshnessThreshold(poiType string) int64

POIFreshnessThreshold returns the appropriate freshness threshold for a given POI type.

func PerformShipUpgrade

func PerformShipUpgrade(client *Client, logger *log.Logger, ctx context.Context, tier UpgradeTier, availableCredits float64) bool

PerformShipUpgrade handles the complete ship upgrade process: 1. Sell all cargo 2. Uninstall all modules 3. Buy new ship 4. Buy equipment items 5. Install equipment items

func SaveJSONToFile

func SaveJSONToFile(data []byte, dir, filename string) error

SaveJSONToFile saves JSON data to a file in the specified directory Creates the directory if it doesn't exist

Parameters:

  • data: The JSON data to save (already marshaled to []byte)
  • dir: The directory path (e.g., "data/server/systems")
  • filename: The filename (e.g., "sol.20250101.json")

Returns error if directory creation or file write fails

func SaveStructToFile

func SaveStructToFile(data any, dir, filename string) error

SaveStructToFile saves any Go struct as JSON to a file Marshals the struct with pretty-printing (indent 2 spaces)

Example:

data := map[string]any{
    "system_id": "sol",
    "timestamp": time.Now(),
}
if err := game.SaveStructToFile(data, "data/server/systems", "sol.json"); err != nil {
    log.Printf("Failed to save: %v", err)
}

func SellAllLoot

func SellAllLoot(client *Client, logger *log.Logger, ctx context.Context) error

SellAllLoot sells all loot items in cargo Useful for fighters and pirates after combat

func ShipMaxSlots

func ShipMaxSlots(ship ShipDef) int

ShipMaxSlots returns the relevant max equipment slot count for a ship. Combat-oriented classes use weapon slots; others use utility slots.

func ShouldUpgrade

func ShouldUpgrade(credits float64, tiers []UpgradeTier, tier1Threshold float64) bool

ShouldUpgrade checks if it's time to check for upgrades based on credits

func StationActionCraftAndDeposit

func StationActionCraftAndDeposit(client *Client, logger *log.Logger, ctx context.Context) error

StationActionCraftAndDeposit crafts items from cargo resources, then deposits everything

func StationActionCraftAndSell

func StationActionCraftAndSell(client *Client, logger *log.Logger, ctx context.Context) error

StationActionCraftAndSell crafts items from cargo resources, then sells everything

func StationActionSellAll

func StationActionSellAll(client *Client, logger *log.Logger, ctx context.Context) error

StationActionSellAll simply sells all cargo without any crafting

func TryInstallAndSellExtras

func TryInstallAndSellExtras(client *Client, logger *log.Logger, ctx context.Context, maxSlots int)

TryInstallAndSellExtras attempts to install modules from cargo and sells any that can't be installed. maxSlots is the relevant slot count for the current ship (use ShipMaxSlots to compute it). This is useful for all agent types that collect loot or buy equipment.

func UndockFromStation

func UndockFromStation(client *Client, ctx context.Context) error

UndockFromStation undocks the client from the current station

func WithDocked

func WithDocked(client *Client, ctx context.Context, stationID string, action func() error) error

WithDocked executes a function while docked at a station Docks, runs the action, then undocks. Useful for station operations like refueling, repairing, buying/selling, etc.

Example:

err := game.WithDocked(client, ctx, logger, stationID, func() error {
    if err := client.Refuel(ctx); err != nil {
        return err
    }
    time.Sleep(game.SleepShort)
    return nil
})

func WriteCaptainsLog

func WriteCaptainsLog(agentID string, entry *AgentLog) error

WriteCaptainsLog writes a captain's log entry if: 1. More than 1 minute has passed since last entry 2. The content has changed from the last entry

Example usage:

entry := &game.AgentLog{
    AgentName:   "Ironbeard",
    CurrentGoal: "Exploring the galaxy, scanning every POI and docking at every station",
    Location:    "System: sol, POI: sol_station",
    Notes:       []string{"Found rare minerals at sol_belt", "Market prices favorable for ore"},
}
if err := game.WriteCaptainsLog("explorer-1", entry); err != nil {
    log.Printf("Failed to write captain's log: %v", err)
}

Types

type AgentLog

type AgentLog struct {
	Timestamp   time.Time `json:"timestamp"`
	AgentID     string    `json:"agent_id"`
	AgentName   string    `json:"agent_name"`
	CurrentGoal string    `json:"current_goal"` // What they're doing now
	Location    string    `json:"location"`     // Current system/POI
	Notes       []string  `json:"notes"`        // Things learned/observed
}

AgentLog represents what an agent is currently doing and has learned. This is stored locally in data/agents/{AGENT_ID}/captains_log/ for agent memory across restarts. Not to be confused with CaptainsLogEntry which is the server's captain's log API response.

func ReadAllCaptainsLogs

func ReadAllCaptainsLogs(agentID string) ([]*AgentLog, error)

ReadAllCaptainsLogs reads all captain's log entries for an agent, newest first. Returns nil if no logs exist yet.

Example usage:

logs, err := game.ReadAllCaptainsLogs("explorer-1")
if err != nil {
    return err
}
for _, log := range logs {
    fmt.Printf("[%s] %s: %s\n", log.Timestamp.Format(time.RFC3339), log.Location, log.CurrentGoal)
}

func ReadLatestCaptainsLog

func ReadLatestCaptainsLog(agentID string) (*AgentLog, error)

ReadLatestCaptainsLog reads the most recent captain's log entry for an agent. Returns nil if no logs exist yet.

Example usage:

log, err := game.ReadLatestCaptainsLog("explorer-1")
if err != nil {
    return err
}
if log != nil {
    logger.Printf("Resuming previous mission: %s", log.CurrentGoal)
}

type BattleParticipant

type BattleParticipant struct {
	PlayerID  string  `json:"player_id"`
	Username  string  `json:"username"`
	ShipClass string  `json:"ship_class"`
	SideID    string  `json:"side_id"`
	Zone      string  `json:"zone"`
	Stance    string  `json:"stance"`
	Hull      float64 `json:"hull"`
	MaxHull   float64 `json:"max_hull"`
	Shield    float64 `json:"shield"`
	MaxShield float64 `json:"max_shield"`
}

BattleParticipant represents a participant in a tactical battle.

type BattleState

type BattleState struct {
	BattleID      string              `json:"battle_id"`
	SystemID      string              `json:"system_id"`
	IsParticipant bool                `json:"is_participant"`
	Participants  []BattleParticipant `json:"participants"`
	TickDuration  int                 `json:"tick_duration"`
}

BattleState represents the current state of a tactical battle.

type BulkSellOrder

type BulkSellOrder struct {
	ItemID    string `json:"item_id"`
	Quantity  int    `json:"quantity"`
	PriceEach int    `json:"price_each"`
}

BulkSellOrder represents a single item to sell in a bulk order

func PrepareBulkSellOrder

func PrepareBulkSellOrder(cargo []CargoItem, reservedItems []string, pricePerItem map[string]int) (orders []BulkSellOrder, skippedCount int)

PrepareBulkSellOrder prepares cargo items for a bulk sell order API call. It filters out reserved items and equipment, keeping only ores and resources. Returns a slice of BulkSellOrder items ready for the create_sell_order API (max 50).

Parameters:

  • cargo: The ship's current cargo contents
  • reservedItems: List of item IDs that should NOT be sold (e.g., crafting materials to keep)
  • pricePerItem: Map of item_id to price_each for pricing strategy. If nil or missing an item, uses a default price of 1 credit (you should call view_market first for better pricing)

Returns:

  • orders: Slice of BulkSellOrder ready for API call (empty if nothing to sell)
  • skippedCount: Number of items skipped (reserved or equipment)

type CargoItem

type CargoItem struct {
	ItemID   string  `json:"item_id"`
	Quantity float64 `json:"quantity"`
}

ConnectionInfo represents a connection from one system to another with details. Embedded in Ship.Cargo array in server responses. Server commands that include this:

  • Any command returning Ship (logged_in, state_update, get_ship, get_status)

func CargoItemFromAPI

func CargoItemFromAPI(ext serverapi.CargoItem) CargoItem

CargoItemFromAPI converts a serverapi CargoItem to an internal CargoItem.

type Client

type Client struct {

	// Crafting configuration
	CraftingConfig *CraftingConfig

	// Command queue for sequential execution
	CmdQueue *CommandQueue
	// contains filtered or unexported fields
}

Client represents a WebSocket client for the Spacemolt game

func NewClient

func NewClient(url, username, password string, debugLogger *log.Logger) *Client

NewClient creates a new game client

func (*Client) AbandonMission

func (c *Client) AbandonMission(ctx context.Context, missionID string) error

AbandonMission abandons an active mission.

func (*Client) AcceptMission

func (c *Client) AcceptMission(ctx context.Context, missionID string) error

AcceptMission accepts a mission from the mission board.

func (*Client) AcceptMissionQueued

func (c *Client) AcceptMissionQueued(ctx context.Context, missionID string) error

AcceptMissionQueued accepts a mission using the queue

func (*Client) AnalyzeMarket

func (c *Client) AnalyzeMarket(ctx context.Context) error

AnalyzeMarket gets actionable trading insights at the current station.

func (*Client) Attack

func (c *Client) Attack(ctx context.Context, targetID string) error

Attack attacks a target player or NPC

func (*Client) Battle

func (c *Client) Battle(ctx context.Context, action string, payload map[string]any) error

Battle manages tactical battle actions (advance, retreat, stance, target, engage).

func (*Client) BrowseShips

func (c *Client) BrowseShips(ctx context.Context, payload map[string]any) error

BrowseShips browses ships listed for sale at a base.

func (*Client) Buy

func (c *Client) Buy(ctx context.Context, itemID string, quantity float64) error

Buy purchases items or modules at the current station

func (*Client) BuyInsurance

func (c *Client) BuyInsurance(ctx context.Context, ticks int) error

BuyInsurance purchases ship insurance for a number of ticks.

func (*Client) BuyListedShip

func (c *Client) BuyListedShip(ctx context.Context, listingID string) error

BuyListedShip purchases a ship listed by another player.

func (*Client) BuyQueued

func (c *Client) BuyQueued(ctx context.Context, itemID string, quantity float64) error

BuyQueued buys items using the queue

func (*Client) BuyShip

func (c *Client) BuyShip(ctx context.Context, shipClass string) error

BuyShip buys a pre-built ship from the station showroom.

func (*Client) CancelCommission

func (c *Client) CancelCommission(ctx context.Context, commissionID string) error

CancelCommission cancels a pending or in-progress ship commission.

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, payload map[string]any) error

CancelOrder cancels an active exchange order and returns escrow.

func (*Client) CancelShipListing

func (c *Client) CancelShipListing(ctx context.Context, listingID string) error

CancelShipListing removes a ship listing from the exchange.

func (*Client) CaptainsLogAdd

func (c *Client) CaptainsLogAdd(ctx context.Context, entry string) error

CaptainsLogAdd adds an entry to your captain's log.

func (*Client) CaptainsLogGet

func (c *Client) CaptainsLogGet(ctx context.Context, index int) error

CaptainsLogGet gets a specific entry from your captain's log.

func (*Client) CaptainsLogList

func (c *Client) CaptainsLogList(ctx context.Context) error

CaptainsLogList lists all entries in your captain's log.

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context, payload map[string]any) error

Catalog browses game reference data (ships, skills, recipes, items).

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, channel, content string, targetID string) error

Chat sends a chat message.

func (*Client) Claim

func (c *Client) Claim(ctx context.Context, registrationCode string) error

Claim links the current player to a website account using a registration code This is a synchronous operation that waits for the server response

func (*Client) ClaimCommission

func (c *Client) ClaimCommission(ctx context.Context, commissionID string) error

ClaimCommission claims a completed ship from a commission.

func (*Client) ClaimInsurance

func (c *Client) ClaimInsurance(ctx context.Context) error

ClaimInsurance views your active insurance policies.

func (*Client) ClearLastError

func (c *Client) ClearLastError()

ClearLastError clears the stored error

func (*Client) Cloak

func (c *Client) Cloak(ctx context.Context, enable bool) error

Cloak toggles the cloaking device. Pass true to enable, false to disable.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection

func (*Client) CommissionQuote

func (c *Client) CommissionQuote(ctx context.Context, shipClass string) error

CommissionQuote gets a cost estimate for commissioning a ship.

func (*Client) CommissionShip

func (c *Client) CommissionShip(ctx context.Context, shipClass string, provideMaterials bool) error

CommissionShip commissions a ship to be built at the current shipyard.

func (*Client) CommissionStatus

func (c *Client) CommissionStatus(ctx context.Context, baseID string) error

CommissionStatus checks the status of ship commissions.

func (*Client) CompleteMission

func (c *Client) CompleteMission(ctx context.Context, missionID string) error

CompleteMission completes a mission and claims rewards.

func (*Client) CompleteMissionQueued

func (c *Client) CompleteMissionQueued(ctx context.Context, missionID string) error

CompleteMissionQueued completes a mission using the queue

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect establishes a WebSocket connection to the game server Implements retry logic with exponential backoff for rate limiting (429 errors)

func (*Client) Craft

func (c *Client) Craft(ctx context.Context, recipeCommand string) error

Craft executes a crafting command for a specific recipe The recipe_id should match the format expected by the game server

func (*Client) CraftFromCargo

func (c *Client) CraftFromCargo(ctx context.Context, logger *log.Logger, config *CraftingConfig) (int, error)

CraftFromCargo automatically crafts items from available cargo resources Returns the number of items successfully crafted

func (*Client) CraftQueued

func (c *Client) CraftQueued(ctx context.Context, recipeID string, quantity int) error

CraftQueued crafts an item using the queue

func (*Client) CraftWithQuantity

func (c *Client) CraftWithQuantity(ctx context.Context, recipeID string, quantity int) error

CraftWithQuantity executes a crafting command with a specific quantity (1-10)

func (*Client) CreateBulkSellOrder

func (c *Client) CreateBulkSellOrder(ctx context.Context, orders []BulkSellOrder) error

CreateBulkSellOrder creates multiple sell orders in a single API call (up to 50 items). This is more efficient than calling Sell repeatedly for each item. The orders parameter should be prepared using PrepareBulkSellOrder().

Example:

orders, _ := game.PrepareBulkSellOrder(state.Ship.Cargo, []string{}, priceMap)
if len(orders) > 0 {
    err := client.CreateBulkSellOrder(ctx, orders)
}

func (*Client) CreateBuyOrder

func (c *Client) CreateBuyOrder(ctx context.Context, payload map[string]any) error

CreateBuyOrder places a buy offer on the station exchange.

func (*Client) CreateFaction

func (c *Client) CreateFaction(ctx context.Context, payload map[string]any) error

CreateFaction creates a new faction.

func (*Client) CreateNote

func (c *Client) CreateNote(ctx context.Context, title, content string) error

CreateNote creates a new note document.

func (*Client) CreateSellOrder

func (c *Client) CreateSellOrder(ctx context.Context, payload map[string]any) error

CreateSellOrder lists items for sale on the station exchange.

func (*Client) DeclineMission

func (c *Client) DeclineMission(ctx context.Context, templateID string) error

DeclineMission declines a mission and hears the NPC's response.

func (*Client) DepositAllItems

func (c *Client) DepositAllItems(ctx context.Context) error

DepositAllItems deposits all items from the ship's cargo to station storage. This moves everything in cargo to the station's storage.

Returns an error if:

  • Not docked at a station
  • Station doesn't have storage service
  • Any individual deposit fails

Example:

err := client.DepositAllItems(ctx)

func (*Client) DepositCredits

func (c *Client) DepositCredits(ctx context.Context, amount float64) error

DepositCredits moves credits from wallet to station storage.

func (*Client) DepositCreditsQueued

func (c *Client) DepositCreditsQueued(ctx context.Context, amount float64) error

DepositCreditsQueued deposits credits to storage using the queue

func (*Client) DepositItems

func (c *Client) DepositItems(ctx context.Context, itemID string, quantity float64) error

DepositItems deposits items from the ship's cargo to station storage. This moves the specified quantity of items from cargo to the station's storage.

Parameters:

  • ctx: Context for cancellation
  • itemID: The ID of the item to deposit
  • quantity: The quantity to deposit (must be >= 0)

Returns an error if:

  • Not docked at a station
  • Item not found in cargo
  • Quantity exceeds available amount
  • Station doesn't have storage service

Example:

// Deposit all iron ore
err := client.DepositItems(ctx, "ore_iron", 100.0)

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect closes the WebSocket connection

func (*Client) Dock

func (c *Client) Dock(ctx context.Context) error

Dock docks at a station in the current system

func (*Client) DockQueued

func (c *Client) DockQueued(ctx context.Context) error

DockQueued docks at a station using the queue

func (*Client) EnsureConnected

func (c *Client) EnsureConnected(ctx context.Context) error

EnsureConnected ensures the client is connected, reconnecting if necessary

func (*Client) EstimatePurchase

func (c *Client) EstimatePurchase(ctx context.Context, itemID string, quantity int) error

EstimatePurchase previews what buying would cost without executing.

func (*Client) Facility

func (c *Client) Facility(ctx context.Context, payload map[string]any) error

Facility manages facilities at stations.

func (*Client) FactionAcceptPeace

func (c *Client) FactionAcceptPeace(ctx context.Context, targetFactionID string) error

FactionAcceptPeace accepts a peace proposal.

func (*Client) FactionCancelMission

func (c *Client) FactionCancelMission(ctx context.Context, templateID string) error

FactionCancelMission cancels a posted faction mission and refunds escrowed rewards.

func (*Client) FactionCreateBuyOrder

func (c *Client) FactionCreateBuyOrder(ctx context.Context, itemID string, priceEach float64, quantity int) error

FactionCreateBuyOrder creates a buy order on behalf of your faction.

func (*Client) FactionCreateRole

func (c *Client) FactionCreateRole(ctx context.Context, name string, priority int, permissions map[string]any) error

FactionCreateRole creates a custom faction role.

func (*Client) FactionCreateSellOrder

func (c *Client) FactionCreateSellOrder(ctx context.Context, itemID string, priceEach float64, quantity int) error

FactionCreateSellOrder creates a sell order on behalf of your faction.

func (*Client) FactionDeclareWar

func (c *Client) FactionDeclareWar(ctx context.Context, targetFactionID, reason string) error

FactionDeclareWar declares war on another faction.

func (*Client) FactionDeclineInvite

func (c *Client) FactionDeclineInvite(ctx context.Context, factionID string) error

FactionDeclineInvite declines a faction invitation.

func (*Client) FactionDeleteRole

func (c *Client) FactionDeleteRole(ctx context.Context, roleID string) error

FactionDeleteRole deletes a custom faction role.

func (*Client) FactionDeleteRoom

func (c *Client) FactionDeleteRoom(ctx context.Context, roomID string) error

FactionDeleteRoom deletes a room from your faction's common space.

func (*Client) FactionDepositCredits

func (c *Client) FactionDepositCredits(ctx context.Context, amount float64) error

FactionDepositCredits transfers credits from your wallet to faction storage.

func (*Client) FactionDepositItems

func (c *Client) FactionDepositItems(ctx context.Context, itemID string, quantity int) error

FactionDepositItems moves items from your cargo to faction storage.

func (*Client) FactionEdit

func (c *Client) FactionEdit(ctx context.Context, payload map[string]any) error

FactionEdit updates faction description, charter, and colors.

func (*Client) FactionEditRole

func (c *Client) FactionEditRole(ctx context.Context, roleID string, payload map[string]any) error

FactionEditRole edits a custom faction role.

func (*Client) FactionGetInvites

func (c *Client) FactionGetInvites(ctx context.Context) error

FactionGetInvites views pending faction invitations.

func (*Client) FactionGift

func (c *Client) FactionGift(ctx context.Context, factionID string, payload map[string]any) error

FactionGift gifts items or credits to a faction's storage.

func (*Client) FactionInfo

func (c *Client) FactionInfo(ctx context.Context, factionID string) error

FactionInfo views faction details. If factionID is empty, views your own faction.

func (*Client) FactionIntelStatus

func (c *Client) FactionIntelStatus(ctx context.Context) error

FactionIntelStatus views faction intel coverage statistics.

func (*Client) FactionInvite

func (c *Client) FactionInvite(ctx context.Context, playerID string) error

FactionInvite invites a player to your faction.

func (*Client) FactionKick

func (c *Client) FactionKick(ctx context.Context, playerID string) error

FactionKick kicks a player from your faction.

func (*Client) FactionList

func (c *Client) FactionList(ctx context.Context, limit, offset int) error

FactionList lists all factions.

func (*Client) FactionListMissions

func (c *Client) FactionListMissions(ctx context.Context) error

FactionListMissions lists your faction's posted missions at this station.

func (*Client) FactionPostMission

func (c *Client) FactionPostMission(ctx context.Context, payload map[string]any) error

FactionPostMission posts a mission on your faction's mission board.

func (*Client) FactionPromote

func (c *Client) FactionPromote(ctx context.Context, playerID, roleID string) error

FactionPromote promotes or demotes a faction member.

func (*Client) FactionProposePeace

func (c *Client) FactionProposePeace(ctx context.Context, targetFactionID, terms string) error

FactionProposePeace proposes peace to a faction you're at war with.

func (*Client) FactionQueryIntel

func (c *Client) FactionQueryIntel(ctx context.Context, payload map[string]any) error

FactionQueryIntel queries your faction's intel database.

func (*Client) FactionQueryTradeIntel

func (c *Client) FactionQueryTradeIntel(ctx context.Context, payload map[string]any) error

FactionQueryTradeIntel searches your faction's market price database.

func (*Client) FactionRooms

func (c *Client) FactionRooms(ctx context.Context) error

FactionRooms lists rooms in your faction's common space at the current station.

func (*Client) FactionSetAlly

func (c *Client) FactionSetAlly(ctx context.Context, targetFactionID string) error

FactionSetAlly marks another faction as ally.

func (*Client) FactionSetEnemy

func (c *Client) FactionSetEnemy(ctx context.Context, targetFactionID string) error

FactionSetEnemy marks another faction as enemy.

func (*Client) FactionSubmitIntel

func (c *Client) FactionSubmitIntel(ctx context.Context, systems []map[string]any) error

FactionSubmitIntel submits system intel to your faction's shared map.

func (*Client) FactionSubmitTradeIntel

func (c *Client) FactionSubmitTradeIntel(ctx context.Context, stations []map[string]any) error

FactionSubmitTradeIntel submits market price observations to your faction's trade ledger.

func (*Client) FactionTradeIntelStatus

func (c *Client) FactionTradeIntelStatus(ctx context.Context) error

FactionTradeIntelStatus views faction trade intelligence coverage statistics.

func (*Client) FactionVisitRoom

func (c *Client) FactionVisitRoom(ctx context.Context, roomID string) error

FactionVisitRoom visits a room and reads its description.

func (*Client) FactionWithdrawCredits

func (c *Client) FactionWithdrawCredits(ctx context.Context, amount float64) error

FactionWithdrawCredits transfers credits from faction storage to your wallet.

func (*Client) FactionWithdrawItems

func (c *Client) FactionWithdrawItems(ctx context.Context, itemID string, quantity int) error

FactionWithdrawItems moves items from faction storage to your cargo.

func (*Client) FactionWriteRoom

func (c *Client) FactionWriteRoom(ctx context.Context, payload map[string]any) error

FactionWriteRoom creates or updates a room in your faction's common space.

func (*Client) FindRoute

func (c *Client) FindRoute(ctx context.Context, targetSystem string) ([]RouteStep, error)

FindRoute finds a route to a target system using the server's pathfinding. Returns the route steps (excluding the current system) or an error.

func (*Client) ForumCreateThread

func (c *Client) ForumCreateThread(ctx context.Context, title, content string, category string) error

ForumCreateThread creates a new forum thread.

func (*Client) ForumDeleteReply

func (c *Client) ForumDeleteReply(ctx context.Context, replyID string) error

ForumDeleteReply deletes a forum reply.

func (*Client) ForumDeleteThread

func (c *Client) ForumDeleteThread(ctx context.Context, threadID string) error

ForumDeleteThread deletes a forum thread.

func (*Client) ForumGetThread

func (c *Client) ForumGetThread(ctx context.Context, threadID string) error

ForumGetThread gets a forum thread and its replies.

func (*Client) ForumList

func (c *Client) ForumList(ctx context.Context, page int) error

ForumList lists forum threads.

func (*Client) ForumReply

func (c *Client) ForumReply(ctx context.Context, threadID, content string) error

ForumReply replies to a forum thread.

func (*Client) ForumUpvote

func (c *Client) ForumUpvote(ctx context.Context, threadID string, replyID string) error

ForumUpvote upvotes a thread or reply.

func (*Client) GetActiveMissions

func (c *Client) GetActiveMissions(ctx context.Context) error

GetActiveMissions views your active missions and progress.

func (*Client) GetBase

func (c *Client) GetBase(ctx context.Context) error

GetBase gets docked base details.

func (*Client) GetBaseQueued

func (c *Client) GetBaseQueued(ctx context.Context) error

GetBaseQueued gets base info using the queue

func (*Client) GetBattleStatus

func (c *Client) GetBattleStatus(ctx context.Context) error

GetBattleStatus queries the current battle state (free query, no tick cost).

func (*Client) GetCargo

func (c *Client) GetCargo(ctx context.Context) error

GetCargo gets the ship's cargo contents.

func (*Client) GetCargoQueued

func (c *Client) GetCargoQueued(ctx context.Context) error

GetCargoQueued gets cargo contents using the queue

func (*Client) GetChatHistory

func (c *Client) GetChatHistory(ctx context.Context, channel string, payload map[string]any) error

GetChatHistory gets chat message history.

func (*Client) GetCommands

func (c *Client) GetCommands(ctx context.Context) error

GetCommands gets a structured list of all commands.

func (*Client) GetDrones

func (c *Client) GetDrones(ctx context.Context) error

GetDrones gets deployed drone information.

func (*Client) GetGuide

func (c *Client) GetGuide(ctx context.Context, guide string) error

GetGuide gets a detailed playstyle progression guide.

func (*Client) GetInsuranceQuote

func (c *Client) GetInsuranceQuote(ctx context.Context) error

GetInsuranceQuote gets a risk-based insurance quote for the current ship.

func (*Client) GetLastError

func (c *Client) GetLastError() map[string]any

GetLastError returns the most recent error response

func (*Client) GetListings

func (c *Client) GetListings(ctx context.Context) error

GetListings requests market listings for the current station

func (*Client) GetListingsQueued

func (c *Client) GetListingsQueued(ctx context.Context) error

GetListingsQueued gets market listings using the queue

func (*Client) GetMap

func (c *Client) GetMap(ctx context.Context) error

GetMap requests all systems with coordinates and connections

func (*Client) GetMarketListings

func (c *Client) GetMarketListings() []MarketListing

GetMarketListings returns the most recently fetched market listings

func (*Client) GetMissions

func (c *Client) GetMissions(ctx context.Context) error

GetMissions gets available missions at the current base.

func (*Client) GetNearby

func (c *Client) GetNearby(ctx context.Context) error

GetNearby gets other players at the current POI.

func (*Client) GetNearbyQueued

func (c *Client) GetNearbyQueued(ctx context.Context) error

GetNearbyQueued gets nearby players using the queue

func (*Client) GetNotes

func (c *Client) GetNotes(ctx context.Context) error

GetNotes lists all your note documents.

func (*Client) GetPOI

func (c *Client) GetPOI(ctx context.Context) error

GetPOI requests information about the current POI

func (*Client) GetPOIQueued

func (c *Client) GetPOIQueued(ctx context.Context) error

GetPOIQueued gets POI info using the queue

func (*Client) GetRawJSON

func (c *Client) GetRawJSON(key string) []byte

GetRawJSON retrieves the raw JSON payload for a given key

func (*Client) GetRecipes

func (c *Client) GetRecipes(ctx context.Context) error

GetRecipes gets available crafting recipes.

func (*Client) GetShip

func (c *Client) GetShip(ctx context.Context) error

GetShip gets detailed ship information.

func (*Client) GetShipListings

func (c *Client) GetShipListings() map[string]any

GetShipListings returns the most recently fetched ship listings

func (*Client) GetShipQueued

func (c *Client) GetShipQueued(ctx context.Context) error

GetShipQueued gets ship info using the queue

func (*Client) GetShips

func (c *Client) GetShips(ctx context.Context) error

GetShips requests ship listings from the current station

func (*Client) GetSkills

func (c *Client) GetSkills(ctx context.Context) error

GetSkills gets your skill progress.

func (*Client) GetState

func (c *Client) GetState() *State

GetState returns the current game state

func (*Client) GetStatus

func (c *Client) GetStatus(ctx context.Context) error

GetStatus requests player status

func (*Client) GetStatusQueued

func (c *Client) GetStatusQueued(ctx context.Context) error

GetStatusQueued gets status using the queue

func (*Client) GetSystem

func (c *Client) GetSystem(ctx context.Context) error

GetSystem requests information about the current system

func (*Client) GetSystemQueued

func (c *Client) GetSystemQueued(ctx context.Context) error

GetSystemQueued gets system info using the queue

func (*Client) GetTrades

func (c *Client) GetTrades(ctx context.Context) error

GetTrades views pending trade offers.

func (*Client) GetVersion

func (c *Client) GetVersion(ctx context.Context) error

GetVersion gets game version and release notes.

func (*Client) GetWrecks

func (c *Client) GetWrecks(ctx context.Context) error

GetWrecks lists all wrecks at the current POI.

func (*Client) Help

func (c *Client) Help(ctx context.Context, payload map[string]any) error

Help gets help for commands.

func (*Client) Install

func (c *Client) Install(ctx context.Context, itemID string) error

Install installs a module from cargo onto the ship

func (*Client) InstallMod

func (c *Client) InstallMod(ctx context.Context, moduleID string) error

InstallMod installs a module on the ship.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is connected

func (*Client) Jettison

func (c *Client) Jettison(ctx context.Context, itemID string, quantity float64) error

Jettison jettisons items from cargo into space.

func (*Client) JoinFaction

func (c *Client) JoinFaction(ctx context.Context, factionID string) error

JoinFaction joins a faction via invitation.

func (*Client) Jump

func (c *Client) Jump(ctx context.Context, targetSystem string) error

Jump jumps to another system

func (*Client) JumpQueued

func (c *Client) JumpQueued(ctx context.Context, targetSystem string) error

JumpQueued jumps to another system using the queue

func (*Client) LeaveFaction

func (c *Client) LeaveFaction(ctx context.Context) error

LeaveFaction leaves your current faction.

func (*Client) ListShipForSale

func (c *Client) ListShipForSale(ctx context.Context, shipID string, price float64) error

ListShipForSale lists a stored ship for sale on the exchange.

func (*Client) ListShips

func (c *Client) ListShips(ctx context.Context) error

ListShips lists all ships owned by the player and their locations.

func (*Client) Login

func (c *Client) Login(ctx context.Context) error

Login authenticates with the server using stored credentials This is a synchronous operation that waits for the server response

func (*Client) LootWreck

func (c *Client) LootWreck(ctx context.Context, wreckID, itemID string, quantity float64) error

LootWreck loots items from a wreck.

func (*Client) Mine

func (c *Client) Mine(ctx context.Context) error

Mine mines resources at the current location

func (*Client) MineQueued

func (c *Client) MineQueued(ctx context.Context) error

MineQueued mines resources using the queue

func (*Client) ModifyOrder

func (c *Client) ModifyOrder(ctx context.Context, payload map[string]any) error

ModifyOrder changes the price on an existing exchange order.

func (*Client) QueryCraftableRecipes

func (c *Client) QueryCraftableRecipes(ctx context.Context, config *CraftingConfig) (*CraftQueryResult, error)

QueryCraftableRecipes queries the crafting MCP server to find what can be crafted with the current cargo and skills

func (*Client) ReadNote

func (c *Client) ReadNote(ctx context.Context, noteID string) error

ReadNote reads a note document's contents.

func (*Client) Ready

func (c *Client) Ready() <-chan struct{}

Ready returns a channel that is closed when the WebSocket connection is ready (i.e., when the first message has been received from the server)

func (*Client) Reconnect

func (c *Client) Reconnect(ctx context.Context) error

Reconnect disconnects and reconnects to the server

func (*Client) Refuel

func (c *Client) Refuel(ctx context.Context) error

Refuel refills the ship's fuel tank at the current station

func (*Client) RefuelQueued

func (c *Client) RefuelQueued(ctx context.Context) error

RefuelQueued refuels using the queue

func (*Client) Register

func (c *Client) Register(ctx context.Context, empire, registrationCode string) error

Register creates a new account This is a synchronous operation that waits for the server response

func (*Client) ReleaseTow

func (c *Client) ReleaseTow(ctx context.Context) error

ReleaseTow releases a towed wreck at the current location.

func (*Client) Reload

func (c *Client) Reload(ctx context.Context, weaponInstanceID, ammoItemID string) error

Reload reloads a weapon's magazine from ammo in cargo.

func (*Client) Repair

func (c *Client) Repair(ctx context.Context) error

Repair repairs the ship's hull at the current station

func (*Client) RepairQueued

func (c *Client) RepairQueued(ctx context.Context) error

RepairQueued repairs using the queue

func (*Client) SalvageWreck

func (c *Client) SalvageWreck(ctx context.Context, wreckID string) error

SalvageWreck salvages a wreck for raw materials.

func (*Client) Scan

func (c *Client) Scan(ctx context.Context) error

Scan scans the current area

func (*Client) ScanTarget

func (c *Client) ScanTarget(ctx context.Context, targetID string) error

ScanTarget scans a specific target player.

func (*Client) ScrapWreck

func (c *Client) ScrapWreck(ctx context.Context) error

ScrapWreck scraps a towed wreck for salvage materials.

func (*Client) SearchChangelog

func (c *Client) SearchChangelog(ctx context.Context, payload map[string]any) error

SearchChangelog searches release notes and version history.

func (*Client) SearchSystems

func (c *Client) SearchSystems(ctx context.Context, query string) error

SearchSystems searches for systems by name.

func (*Client) SelfDestruct

func (c *Client) SelfDestruct(ctx context.Context) error

SelfDestruct destroys your own ship.

func (*Client) Sell

func (c *Client) Sell(ctx context.Context, itemID string, quantity float64) error

Sell sells items from cargo at the current station

func (*Client) SellAll

func (c *Client) SellAll(ctx context.Context) error

SellAll sells all cargo items at the current station

func (*Client) SellAllBulk

func (c *Client) SellAllBulk(ctx context.Context, reservedItems []string) error

SellAllBulk sells all cargo items using the bulk create_sell_order API. This is much faster than SellAll as it makes only one API call instead of N calls. It fetches market listings to price items competitively, then creates sell orders. Only sells ores and resources, not equipment.

Parameters:

  • ctx: Context for cancellation
  • reservedItems: Optional list of item IDs to keep (not sell)

Returns error if not docked or if API call fails.

func (*Client) SellQueued

func (c *Client) SellQueued(ctx context.Context, itemID string, quantity float64) error

SellQueued sells items using the queue

func (*Client) SellShip

func (c *Client) SellShip(ctx context.Context, shipID string) error

SellShip sells a stored ship at the current station.

func (*Client) SellWreck

func (c *Client) SellWreck(ctx context.Context) error

SellWreck sells a towed wreck to the salvage yard for credits.

func (*Client) Send

func (c *Client) Send(ctx context.Context, msg protocol.Message) error

Send sends a message to the game server

func (*Client) SendGift

func (c *Client) SendGift(ctx context.Context, payload map[string]any) error

SendGift sends items or credits to another player's storage at this station.

func (*Client) SendQueued

func (c *Client) SendQueued(ctx context.Context, msg protocol.Message, timeout time.Duration) (protocol.Response, error)

SendQueued sends a command using the queue system for reliable sequential execution This is the recommended way to send commands for agents that need guaranteed delivery and proper response matching.

func (*Client) SetAnonymous

func (c *Client) SetAnonymous(ctx context.Context, anonymous bool) error

SetAnonymous sets anonymous mode.

func (*Client) SetColors

func (c *Client) SetColors(ctx context.Context, primaryColor, secondaryColor string) error

SetColors sets your ship colors.

func (*Client) SetHandler

func (c *Client) SetHandler(handler MessageHandler)

SetHandler sets the message handler

func (*Client) SetHomeBase

func (c *Client) SetHomeBase(ctx context.Context, baseID string) error

SetHomeBase sets the home base for respawning.

func (*Client) SetPlayerStatus

func (c *Client) SetPlayerStatus(ctx context.Context, payload map[string]any) error

SetPlayerStatus sets your status message and clan tag.

func (*Client) ShipyardShowroom

func (c *Client) ShipyardShowroom(ctx context.Context, payload map[string]any) error

ShipyardShowroom browses ships available for immediate purchase at this shipyard.

func (*Client) SurveySystem

func (c *Client) SurveySystem(ctx context.Context) error

SurveySystem scans for hidden POIs in the current system Requires a survey scanner module installed

func (*Client) SwitchShip

func (c *Client) SwitchShip(ctx context.Context, shipID string) error

SwitchShip switches to a different ship stored at the current station.

func (*Client) TowWreck

func (c *Client) TowWreck(ctx context.Context, wreckID string) error

TowWreck attaches a tow line to a wreck for hauling.

func (*Client) TradeAccept

func (c *Client) TradeAccept(ctx context.Context, tradeID string) error

TradeAccept accepts a trade offer.

func (*Client) TradeCancel

func (c *Client) TradeCancel(ctx context.Context, tradeID string) error

TradeCancel cancels your trade offer.

func (*Client) TradeDecline

func (c *Client) TradeDecline(ctx context.Context, tradeID string) error

TradeDecline declines a trade offer.

func (*Client) TradeOffer

func (c *Client) TradeOffer(ctx context.Context, targetID string, payload map[string]any) error

TradeOffer offers a trade to another player.

func (*Client) Travel

func (c *Client) Travel(ctx context.Context, targetPOI string) error

Travel travels to a POI within the current system

func (*Client) TravelQueued

func (c *Client) TravelQueued(ctx context.Context, targetPOI string) error

TravelQueued travels to a POI using the queue

func (*Client) Undock

func (c *Client) Undock(ctx context.Context) error

Undock undocks from the current station

func (*Client) UndockQueued

func (c *Client) UndockQueued(ctx context.Context) error

UndockQueued undocks from a station using the queue

func (*Client) UninstallMod

func (c *Client) UninstallMod(ctx context.Context, moduleID string) error

UninstallMod uninstalls a module from the ship.

func (*Client) UseItem

func (c *Client) UseItem(ctx context.Context, itemID string, quantity int) error

UseItem uses a consumable item from cargo.

func (*Client) ViewFactionStorage

func (c *Client) ViewFactionStorage(ctx context.Context) error

ViewFactionStorage views your faction's shared storage at the current station.

func (*Client) ViewMarket

func (c *Client) ViewMarket(ctx context.Context, itemID string) error

ViewMarket views the order book at the current station.

func (*Client) ViewOrders

func (c *Client) ViewOrders(ctx context.Context) error

ViewOrders views your own orders at the current station.

func (*Client) ViewStorage

func (c *Client) ViewStorage(ctx context.Context) error

ViewStorage views your storage at the current station.

func (*Client) ViewStorageQueued

func (c *Client) ViewStorageQueued(ctx context.Context) error

ViewStorageQueued views station storage using the queue

func (*Client) WaitForReady

func (c *Client) WaitForReady(ctx context.Context, timeout time.Duration) error

WaitForReady waits for the connection to be ready (first message received)

func (*Client) WithdrawCredits

func (c *Client) WithdrawCredits(ctx context.Context, amount float64) error

WithdrawCredits moves credits from station storage to wallet.

func (*Client) WithdrawItems

func (c *Client) WithdrawItems(ctx context.Context, itemID string, quantity float64) error

WithdrawItems moves items from station storage to cargo.

func (*Client) WithdrawItemsQueued

func (c *Client) WithdrawItemsQueued(ctx context.Context, itemID string, quantity float64) error

WithdrawItemsQueued withdraws items from storage using the queue

func (*Client) WriteNote

func (c *Client) WriteNote(ctx context.Context, noteID, content string) error

WriteNote edits an existing note document.

type CommandQueue

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

CommandQueue manages a queue of commands to be executed sequentially This ensures that commands are sent one at a time and responses are properly matched

func NewCommandQueue

func NewCommandQueue(client *Client) *CommandQueue

NewCommandQueue creates a new command queue

func (*CommandQueue) Enqueue

func (q *CommandQueue) Enqueue(ctx context.Context, msg protocol.Message, timeout time.Duration) (protocol.Response, error)

Enqueue adds a command to the queue and waits for it to complete This blocks until the command is executed and a response is received

func (*CommandQueue) GetActiveCommand

func (q *CommandQueue) GetActiveCommand() *QueuedCommand

GetActiveCommand returns the currently executing command (if any)

func (*CommandQueue) QueueSize

func (q *CommandQueue) QueueSize() int

QueueSize returns the current size of the queue

func (*CommandQueue) Start

func (q *CommandQueue) Start(ctx context.Context)

Start begins processing the command queue

func (*CommandQueue) Stop

func (q *CommandQueue) Stop()

Stop stops processing the command queue

type Component

type Component struct {
	ID       string  `json:"id"`
	Quantity float64 `json:"quantity"`
}

Component represents a crafting component

type ConnectionInfo

type ConnectionInfo struct {
	SystemID string `json:"system_id"`
	Name     string `json:"name"`
	Distance int    `json:"distance"`
}

ConnectionInfo represents a connection from one system to another with details.

  • logged_in (in payload.system.connections)

func ConnectionInfoFromAPI

func ConnectionInfoFromAPI(ext serverapi.ConnectionInfo) ConnectionInfo

ConnectionInfoFromAPI converts a serverapi ConnectionInfo to an internal ConnectionInfo.

type CraftQueryResult

type CraftQueryResult struct {
	FullyCraftable []CraftableRecipe `json:"fully_craftable"`
	PartialMatches []CraftableRecipe `json:"partial_matches"`
	SkillBlocked   []CraftableRecipe `json:"skill_blocked"`
}

CraftQueryResult is the simplified response from craft_query

type CraftableRecipe

type CraftableRecipe struct {
	RecipeID         string      `json:"id"`
	RecipeName       string      `json:"name"`
	CanCraftQuantity int         `json:"can_craft_quantity"` // How many can be crafted
	Components       []Component `json:"components"`         // Required components
	CanCraft         bool        `json:"-"`
	SkillGaps        []string    `json:"-"`
	Profit           float64     `json:"-"`
}

CraftableRecipe represents a recipe that can be crafted

type CraftingConfig

type CraftingConfig struct {
	// Path to the crafting MCP server executable
	CraftingServerPath string
}

CraftingConfig configures the crafting integration

type CraftingLoopConfig

type CraftingLoopConfig struct {
	// AgentID for captain's log updates (optional)
	AgentID string

	// Strategy determines what to do with crafted items
	// "craft-deposit": Craft items and deposit to storage
	// "craft-sell": Craft items and sell for credits
	// "craft-profit": Craft items based on market profitability and deposit to storage
	Strategy string

	// StopCondition is called before each crafting run to check if we should stop
	// Return true to stop crafting, false to continue
	// If nil, crafting continues indefinitely
	StopCondition func(state *State) bool

	// OnRunComplete is called after each successful crafting run (optional)
	// Useful for tracking stats, updating logs, etc.
	OnRunComplete func(runNum int, itemsCrafted int, totalCredits float64)

	// RecipeSelector selects which recipes to craft based on available resources and skills
	// If nil, uses DefaultRecipeSelector
	RecipeSelector RecipeSelector

	// StorageManager handles withdrawing and depositing items from/to station storage
	// If nil, only uses cargo (no storage interaction)
	StorageManager StorageManager

	// CaptainsLogInterval controls how often to update captain's log
	// If 0, defaults to 2 minutes
	CaptainsLogInterval time.Duration
}

CraftingLoopConfig configures the behavior of the crafting loop

type CraftingLoopResult

type CraftingLoopResult struct {
	RunsCompleted     int
	TotalItemsCrafted int
	StartingCredits   float64
	EndingCredits     float64
	StoppedReason     string // "context_cancelled", "stop_condition", "error", etc.
}

CraftingLoopResult contains stats from a crafting loop execution

func CraftingLoop

func CraftingLoop(client *Client, logger *log.Logger, ctx context.Context, config *CraftingLoopConfig) (*CraftingLoopResult, error)

CraftingLoop runs the core crafting cycle:

  1. Find nearest station
  2. Dock at station if not docked
  3. Withdraw resources from storage (if configured)
  4. Craft items based on strategy
  5. Handle crafted items (deposit/sell)
  6. Refuel and repair as needed

The loop continues until:

  • Context is cancelled
  • StopCondition returns true
  • An error occurs (returns error)

type Credentials

type Credentials struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Empire   string `json:"empire"`
}

Credentials holds agent authentication information loaded from credentials.json

func LoadCredentials

func LoadCredentials(agentDir string) (*Credentials, error)

LoadCredentials reads and parses credentials.json from an agent directory The file must exist at: data/agents/{agentID}/credentials.json

type GameClient

type GameClient interface {
	// Connection
	Connect(ctx context.Context) error
	Close() error
	IsConnected() bool
	Ready() <-chan struct{}

	// Authentication
	Login(ctx context.Context) error
	Register(ctx context.Context, empire, registrationCode string) error

	// Actions
	Undock(ctx context.Context) error
	Dock(ctx context.Context) error
	Travel(ctx context.Context, targetPOI string) error
	Jump(ctx context.Context, targetSystem string) error
	Mine(ctx context.Context) error
	Scan(ctx context.Context) error

	// Route Planning
	FindRoute(ctx context.Context, targetSystem string) ([]RouteStep, error)

	// Queries
	GetSystem(ctx context.Context) error
	GetStatus(ctx context.Context) error

	// State
	GetState() *State
}

GameClient defines the interface for game client operations This allows for mocking in tests

type MCPClient

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

MCPClient represents a client for communicating with MCP servers over stdio

func NewMCPClient

func NewMCPClient(serverPath string, logger *log.Logger) *MCPClient

NewMCPClient creates a new MCP client for the specified server executable

func (*MCPClient) CallTool

func (m *MCPClient) CallTool(ctx context.Context, toolName string, params map[string]interface{}) (map[string]interface{}, error)

CallTool invokes a tool on the MCP server

func (*MCPClient) Close

func (m *MCPClient) Close() error

Close closes all connections and stops the server

func (*MCPClient) Start

func (m *MCPClient) Start(ctx context.Context) error

Start starts the MCP server process and establishes stdio communication

func (*MCPClient) Stop

func (m *MCPClient) Stop() error

Stop gracefully shuts down the MCP server

type MCPCraftQueryResponse

type MCPCraftQueryResponse struct {
	Craftable []struct {
		Recipe struct {
			ID           string `json:"id"`
			Name         string `json:"name"`
			Description  string `json:"description"`
			Category     string `json:"category"`
			CraftTimeSec int    `json:"craft_time_sec"`
			Components   []struct {
				ComponentID string  `json:"component_id"`
				Quantity    float64 `json:"quantity"`
			} `json:"components"`
		} `json:"recipe"`
		CanCraftQuantity int `json:"can_craft_quantity"`
	} `json:"craftable"`
	PartialComponents []struct {
		Recipe struct {
			ID   string `json:"id"`
			Name string `json:"name"`
		} `json:"recipe"`
	} `json:"partial_components"`
	BlockedBySkills []struct {
		Recipe struct {
			ID   string `json:"id"`
			Name string `json:"name"`
		} `json:"recipe"`
	} `json:"blocked_by_skills"`
}

MCPCraftQueryResponse is the raw response from the crafting MCP server

type MCPManager

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

MCPManager manages the lifecycle of MCP client connections

func NewMCPManager

func NewMCPManager(logger *log.Logger) *MCPManager

NewMCPManager creates a new MCP manager

func (*MCPManager) CloseAll

func (mgr *MCPManager) CloseAll() error

CloseAll closes all MCP clients

func (*MCPManager) GetClient

func (mgr *MCPManager) GetClient(ctx context.Context, serverPath string) (*MCPClient, error)

GetClient gets or creates an MCP client for the specified server

type MarketListing

type MarketListing struct {
	ItemID       string  `json:"item_id"`
	ItemType     string  `json:"item_type"`
	Quantity     float64 `json:"quantity"`
	PricePerUnit float64 `json:"price_per_unit"`
	TotalPrice   float64 `json:"total_price"`
	Type         string  `json:"type"` // 'buy' or 'sell'
	ListedBy     string  `json:"listed_by,omitempty"`
}

MarketListing represents a single market listing (NPC or player exchange order). Server commands that return this struct:

  • get_listings (in payload.listings array)

func MarketListingFromAPI

func MarketListingFromAPI(ext serverapi.MarketListing) MarketListing

MarketListingFromAPI converts a serverapi MarketListing to an internal MarketListing. Handles server field name variations (price_per_unit/price_each, total_price/total, listed_by/seller).

type MarketSnapshot

type MarketSnapshot struct {
	SystemID    string          `json:"system_id"`
	SystemName  string          `json:"system_name"`
	StationID   string          `json:"station_id"`
	StationName string          `json:"station_name"`
	GameTick    int64           `json:"game_tick"`
	Listings    []MarketListing `json:"listings"`
	CapturedAt  time.Time       `json:"captured_at"`
}

MarketSnapshot represents a captured market state. This is an internal client-side structure for data collection, NOT a server response.

type MessageHandler

type MessageHandler interface {
	OnConnected(state *State)
	OnMessage(resp protocol.Response)
	OnDisconnected(err error)
}

MessageHandler handles incoming game messages

type MiningLoopConfig

type MiningLoopConfig struct {
	// AgentID for captain's log updates (optional)
	AgentID string

	// StopCondition is called before each mining run to check if we should stop
	// Return true to stop mining, false to continue
	// If nil, mining continues indefinitely
	StopCondition func(state *State) bool

	// OnRunComplete is called after each successful mining run (optional)
	// Useful for tracking stats, updating logs, etc.
	OnRunComplete func(runNum int, creditsEarned float64, totalCredits float64)

	// OnUpgradeCheck is called when it's time to check for upgrades (optional)
	// Return true if an upgrade was performed
	OnUpgradeCheck func() bool

	// OnStationActions is called when docked at station with cargo
	// Determines what to do with cargo: sell, craft+sell, or craft+deposit
	// If nil, defaults to selling everything (StationActionSellAll)
	OnStationActions StationActionStrategy

	// UpgradeCheckInterval controls how often to check for upgrades
	// If 0, checks every run when credits > tier1Threshold
	// If > 0, checks every N runs
	UpgradeCheckInterval int

	// Tier1Threshold is the minimum credits to trigger upgrade checks
	// If 0, defaults to 300.0
	Tier1Threshold float64

	// ReserveCredits is the amount to always keep (never spend below this)
	// If 0, defaults to 50.0
	ReserveCredits float64

	// MaxMiningAttempts limits mining iterations per run
	// If 0, calculates based on cargo capacity and laser count
	MaxMiningAttempts int

	// CargoFullThreshold is the percentage of cargo capacity to consider "full"
	// If 0, defaults to 0.97 (97%)
	CargoFullThreshold float64

	// FuelLowThreshold is the percentage of fuel to consider "low"
	// If 0, defaults to 0.1 (10%)
	FuelLowThreshold float64

	// UseBulkSell uses SellAllBulk instead of SellAll
	// Recommended for better performance
	UseBulkSell bool

	// CaptainsLogInterval controls how often to update captain's log
	// If 0, defaults to 2 minutes
	CaptainsLogInterval time.Duration
}

MiningLoopConfig configures the behavior of the mining loop

type MiningLoopResult

type MiningLoopResult struct {
	RunsCompleted      int
	TotalCreditsEarned float64
	StartingCredits    float64
	EndingCredits      float64
	StoppedReason      string // "context_cancelled", "stop_condition", "error", etc.
}

MiningLoopResult contains stats from a mining loop execution

func MiningLoop

func MiningLoop(client *Client, logger *log.Logger, ctx context.Context, config *MiningLoopConfig) (*MiningLoopResult, error)

MiningLoop runs the core mining cycle: undock, mine, dock, sell, refuel, repair, upgrade

This is the shared mining loop used by auto-miner, auto-explorer, and other autonomous agents. It handles the complete mining workflow:

  1. Find mining POI and station in current system
  2. Undock if docked
  3. Travel to mining location
  4. Mine until cargo full or fuel low
  5. Travel back to station
  6. Dock at station
  7. Sell all cargo
  8. Refuel if needed
  9. Repair if needed

10. Check for upgrades (if configured)

The loop continues until:

  • Context is cancelled
  • StopCondition returns true
  • An error occurs (returns error)

Example usage:

config := &game.MiningLoopConfig{
    AgentID: "miner-1",
    StopCondition: func(state *game.State) bool {
        return state.Credits >= 5000.0 // Stop when we have 5000 credits
    },
    OnUpgradeCheck: func() bool {
        return attemptUpgrades(client, logger, ctx)
    },
    UseBulkSell: true,
}
result, err := game.MiningLoop(client, logger, ctx, config)

type ModuleDefinition

type ModuleDefinition struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Type        string `json:"type"` // "weapon", "defense", "utility", etc.
	Description string `json:"description"`
}

ModuleDefinition represents a module's definition including stats and requirements. Server commands that return this struct:

  • get_ship (in payload.modules array with full stats)
  • logged_in (embedded in player.modules map)

func ModuleDefinitionFromAPI

func ModuleDefinitionFromAPI(ext serverapi.ModuleDefinition) ModuleDefinition

ModuleDefinitionFromAPI converts a serverapi ModuleDefinition to an internal ModuleDefinition.

type NearbyPlayer

type NearbyPlayer struct {
	PlayerID       string `json:"player_id"`
	Username       string `json:"username"`
	ShipClass      string `json:"ship_class"`
	PrimaryColor   string `json:"primary_color,omitempty"`
	SecondaryColor string `json:"secondary_color,omitempty"`
	Anonymous      bool   `json:"anonymous"`
	InCombat       bool   `json:"in_combat"`
	// Deprecated: Server no longer sends these fields as of v0.93.0
	FactionID     string `json:"faction_id,omitempty"`
	FactionTag    string `json:"faction_tag,omitempty"`
	StatusMessage string `json:"status_message,omitempty"`
	ClanTag       string `json:"clan_tag,omitempty"`
}

NearbyPlayer represents another player or pirate NPC at the same POI. Server commands that return this struct:

  • state_update (in payload.nearby array)
  • get_nearby (in payload.nearby array)

Note: As of v0.93.0, the server only sends player_id, username, ship_class, primary_color, secondary_color, anonymous, and in_combat. Other fields (faction_id, faction_tag, status_message, clan_tag) are present in the documentation but not sent by the current server.

func NearbyPlayerFromAPI

func NearbyPlayerFromAPI(ext serverapi.NearbyPlayer) NearbyPlayer

NearbyPlayerFromAPI converts a serverapi NearbyPlayer to an internal NearbyPlayer.

type OwnedShip

type OwnedShip struct {
	ID       string `json:"id"`
	ClassID  string `json:"class_id"`
	Name     string `json:"name"`
	Location string `json:"location,omitempty"`
	BaseID   string `json:"base_id,omitempty"`
	BaseName string `json:"base_name,omitempty"`
	IsActive bool   `json:"is_active"`
}

OwnedShip represents a ship in the player's fleet (from list_ships).

type POI

type POI struct {
	ID          string        `json:"id"`
	SystemID    string        `json:"system_id"`
	Type        string        `json:"type"`
	Name        string        `json:"name"`
	Description string        `json:"description"`
	Position    Position      `json:"position"`
	Resources   []POIResource `json:"resources"`
	BaseID      string        `json:"base_id,omitempty"`
	HasBase     bool          `json:"has_base,omitempty"`
	BaseName    string        `json:"base_name,omitempty"`
	Online      int           `json:"online,omitempty"`
	Hidden      bool          `json:"hidden,omitempty"`
}

POI represents a Point of Interest in a system (planets, stations, asteroid belts, etc). Server commands that return this struct:

  • get_poi (single POI in payload.poi)
  • get_system (array in payload.pois)
  • logged_in (in payload.poi and payload.system.pois)

v0.87.1+ Enriched format includes has_base, base_name, and online fields.

func FindJumpGate

func FindJumpGate(state *State) *POI

FindJumpGate returns the first jump gate POI in the current system, or nil if none found

func FindMiningLocation

func FindMiningLocation(state *State) *POI

FindMiningLocation returns the first mining POI (asteroid_belt or asteroid_field) in the current system, or nil if none found

func FindPOIByType

func FindPOIByType(state *State, poiType string) *POI

FindPOIByType returns the first POI of the given type in the current system, or nil if none found

func FindStation

func FindStation(state *State) *POI

FindStation returns the first station POI in the current system, or nil if none found

func POIFromAPI

func POIFromAPI(ext serverapi.POI) POI

POIFromAPI converts a serverapi POI to an internal POI.

type POIResource

type POIResource struct {
	ResourceID string  `json:"resource_id"`
	Richness   float64 `json:"richness"`
	Remaining  float64 `json:"remaining"`
}

POIResource represents a minable resource at a POI. Embedded in POI.Resources array in server responses.

func POIResourceFromAPI

func POIResourceFromAPI(ext serverapi.POIResource) POIResource

POIResourceFromAPI converts a serverapi POIResource to an internal POIResource.

type Player

type Player struct {
	ID                string             `json:"id"`
	Username          string             `json:"username"`
	Empire            string             `json:"empire"`
	Credits           float64            `json:"credits"`
	CurrentSystem     string             `json:"current_system"`
	CurrentPOI        string             `json:"current_poi"`
	CurrentShipID     string             `json:"current_ship_id"`
	HomeBase          string             `json:"home_base"`
	DockedAtBase      string             `json:"docked_at_base"`
	FactionID         string             `json:"faction_id,omitempty"`
	FactionRank       string             `json:"faction_rank,omitempty"`
	StatusMessage     string             `json:"status_message,omitempty"`
	ClanTag           string             `json:"clan_tag,omitempty"`
	PrimaryColor      string             `json:"primary_color,omitempty"`
	SecondaryColor    string             `json:"secondary_color,omitempty"`
	Anonymous         bool               `json:"anonymous"`
	IsCloaked         bool               `json:"is_cloaked"`
	Skills            map[string]Skill   `json:"skills"`
	SkillXP           map[string]float64 `json:"skill_xp,omitempty"` // Current XP toward next level
	Stats             PlayerStats        `json:"stats"`
	TowingWreckID     string             `json:"towing_wreck_id,omitempty"`
	Experience        int64              `json:"experience,omitempty"`
	DiscoveredSystems map[string]any     `json:"discovered_systems,omitempty"`
	LastActiveAt      string             `json:"last_active_at,omitempty"`
	LastLoginAt       string             `json:"last_login_at,omitempty"`
	CreatedAt         string             `json:"created_at,omitempty"`
}

Player represents a player in the game. Server commands that return this struct:

  • logged_in (in payload.player)
  • state_update (in payload.player)
  • get_status (in payload.player)

func PlayerFromAPI

func PlayerFromAPI(ext serverapi.Player) Player

PlayerFromAPI converts a serverapi Player to an internal Player.

type PlayerSkill

type PlayerSkill struct {
	SkillID     string  `json:"skill_id"`
	Name        string  `json:"name"`
	Category    string  `json:"category"`
	Level       int     `json:"level"`
	MaxLevel    int     `json:"max_level"`
	CurrentXP   float64 `json:"current_xp"`
	NextLevelXP float64 `json:"next_level_xp"`
}

PlayerSkill represents a player's progress in a specific skill with XP tracking. Server commands that return this struct:

  • get_skills (in payload.player_skills array)

type PlayerStats

type PlayerStats struct {
	ShipsDestroyed    int     `json:"ships_destroyed"`
	TimesDestroyed    int     `json:"times_destroyed"`
	OreMined          float64 `json:"ore_mined"`
	CreditsEarned     float64 `json:"credits_earned"`
	CreditsSpent      float64 `json:"credits_spent"`
	TradesCompleted   int     `json:"trades_completed"`
	SystemsDiscovered int     `json:"systems_discovered"`
	ItemsCrafted      int     `json:"items_crafted"`
	MissionsCompleted int     `json:"missions_completed"`
	BasesDestroyed    int     `json:"bases_destroyed"`
	DistanceTraveled  int64   `json:"distance_traveled"`
	PiratesDestroyed  int     `json:"pirates_destroyed"`
	ShipsLost         int     `json:"ships_lost"`
	TimePlayed        int64   `json:"time_played"`
}

PlayerStats tracks player statistics and lifetime achievements. Embedded in Player.Stats in server responses. Server commands that include this:

  • Any command returning Player (logged_in, state_update, get_status)

func PlayerStatsFromAPI

func PlayerStatsFromAPI(ext serverapi.PlayerStats) PlayerStats

PlayerStatsFromAPI converts a serverapi PlayerStats to an internal PlayerStats.

type Position

type Position struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
	Z float64 `json:"z,omitempty"` // Reserved for future 3D positioning
}

Position represents 3D coordinates (Z is reserved for future use). Embedded in POI and SystemData in server responses.

func PositionFromAPI

func PositionFromAPI(ext serverapi.Position) Position

PositionFromAPI converts a serverapi Position to an internal Position.

type QueuedCommand

type QueuedCommand struct {
	ID        string                 // Unique identifier for this command
	Message   protocol.Message       // The message to send
	Response  chan protocol.Response // Channel to receive the response
	Error     chan error             // Channel to receive errors
	Timeout   time.Duration          // Timeout for this command
	Timestamp time.Time              // When the command was queued
}

QueuedCommand represents a command in the execution queue

type RecipeSelector

type RecipeSelector func(client *Client, logger *log.Logger, ctx context.Context, storage StorageManager) ([]string, error)

RecipeSelector selects recipes to craft based on current state and storage

type ReconnectingHandler

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

ReconnectingHandler wraps a MessageHandler and adds automatic reconnection

func NewReconnectingHandler

func NewReconnectingHandler(client *Client, handler MessageHandler, ctx context.Context, logger *log.Logger) *ReconnectingHandler

NewReconnectingHandler creates a handler that automatically reconnects on disconnect

func (*ReconnectingHandler) OnConnected

func (r *ReconnectingHandler) OnConnected(state *State)

func (*ReconnectingHandler) OnDisconnected

func (r *ReconnectingHandler) OnDisconnected(err error)

func (*ReconnectingHandler) OnMessage

func (r *ReconnectingHandler) OnMessage(resp protocol.Response)

type RobustCommandExecutor

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

RobustCommandExecutor provides a wrapper around Client that handles connection issues and retries automatically, making it easier to write reliable agent code.

func NewRobustCommandExecutor

func NewRobustCommandExecutor(client *Client) *RobustCommandExecutor

NewRobustCommandExecutor creates a new robust command executor

func (*RobustCommandExecutor) ExecuteCommand

func (r *RobustCommandExecutor) ExecuteCommand(ctx context.Context, cmdFunc func(context.Context) error) error

ExecuteCommand executes a game command with automatic retry on connection failures This is the preferred way to execute commands for agents, as it handles: - Connection drops and automatic reconnection - Transient failures with retry - Context cancellation

func (*RobustCommandExecutor) ExecuteWithRetry

func (r *RobustCommandExecutor) ExecuteWithRetry(ctx context.Context, cmdFunc func(context.Context) error, maxRetries int) error

ExecuteWithRetry executes a command with custom retry logic

type RouteStep

type RouteStep struct {
	SystemID string `json:"system_id"`
	Name     string `json:"name"`
	Jumps    int    `json:"jumps"`
}

RouteStep represents a step in a route from find_route.

type SafeCommandBuilder

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

SafeCommandBuilder helps build commands with proper error handling

func NewSafeCommandBuilder

func NewSafeCommandBuilder(client *Client) *SafeCommandBuilder

NewSafeCommandBuilder creates a new safe command builder

func (*SafeCommandBuilder) AcceptMissionQueued

func (s *SafeCommandBuilder) AcceptMissionQueued(ctx context.Context, missionID string) error

AcceptMissionQueued accepts a mission using the queue

func (*SafeCommandBuilder) Buy

func (s *SafeCommandBuilder) Buy(ctx context.Context, itemID string, quantity float64) error

Buy safely buys items

func (*SafeCommandBuilder) BuyQueued

func (s *SafeCommandBuilder) BuyQueued(ctx context.Context, itemID string, quantity float64) error

BuyQueued buys items using the queue

func (*SafeCommandBuilder) CompleteMissionQueued

func (s *SafeCommandBuilder) CompleteMissionQueued(ctx context.Context, missionID string) error

CompleteMissionQueued completes a mission using the queue

func (*SafeCommandBuilder) CraftQueued

func (s *SafeCommandBuilder) CraftQueued(ctx context.Context, recipeID string, quantity int) error

CraftQueued crafts an item using the queue

func (*SafeCommandBuilder) Dock

func (s *SafeCommandBuilder) Dock(ctx context.Context) error

Dock safely docks at a station

func (*SafeCommandBuilder) DockQueued

func (s *SafeCommandBuilder) DockQueued(ctx context.Context) error

DockQueued docks at a station using the queue

func (*SafeCommandBuilder) GetBaseQueued

func (s *SafeCommandBuilder) GetBaseQueued(ctx context.Context) error

GetBaseQueued gets base info using the queue

func (*SafeCommandBuilder) GetCargoQueued

func (s *SafeCommandBuilder) GetCargoQueued(ctx context.Context) error

GetCargoQueued gets cargo contents using the queue

func (*SafeCommandBuilder) GetListings

func (s *SafeCommandBuilder) GetListings(ctx context.Context) error

GetListings safely gets market listings

func (*SafeCommandBuilder) GetListingsQueued

func (s *SafeCommandBuilder) GetListingsQueued(ctx context.Context) error

GetListingsQueued gets market listings using the queue

func (*SafeCommandBuilder) GetNearbyQueued

func (s *SafeCommandBuilder) GetNearbyQueued(ctx context.Context) error

GetNearbyQueued gets nearby players using the queue

func (*SafeCommandBuilder) GetPOI

func (s *SafeCommandBuilder) GetPOI(ctx context.Context) error

GetPOI safely gets POI information

func (*SafeCommandBuilder) GetPOIQueued

func (s *SafeCommandBuilder) GetPOIQueued(ctx context.Context) error

GetPOIQueued gets POI info using the queue

func (*SafeCommandBuilder) GetShipQueued

func (s *SafeCommandBuilder) GetShipQueued(ctx context.Context) error

GetShipQueued gets ship info using the queue

func (*SafeCommandBuilder) GetStatus

func (s *SafeCommandBuilder) GetStatus(ctx context.Context) error

GetStatus safely gets player status

func (*SafeCommandBuilder) GetStatusQueued

func (s *SafeCommandBuilder) GetStatusQueued(ctx context.Context) error

GetStatusQueued gets status using the queue

func (*SafeCommandBuilder) GetSystem

func (s *SafeCommandBuilder) GetSystem(ctx context.Context) error

GetSystem safely gets system information

func (*SafeCommandBuilder) GetSystemQueued

func (s *SafeCommandBuilder) GetSystemQueued(ctx context.Context) error

GetSystemQueued gets system info using the queue

func (*SafeCommandBuilder) Jump

func (s *SafeCommandBuilder) Jump(ctx context.Context, targetSystem string) error

Jump safely jumps to another system

func (*SafeCommandBuilder) JumpQueued

func (s *SafeCommandBuilder) JumpQueued(ctx context.Context, targetSystem string) error

JumpQueued jumps to another system using the queue

func (*SafeCommandBuilder) Mine

func (s *SafeCommandBuilder) Mine(ctx context.Context) error

Mine safely mines resources

func (*SafeCommandBuilder) MineQueued

func (s *SafeCommandBuilder) MineQueued(ctx context.Context) error

MineQueued mines resources using the queue

func (*SafeCommandBuilder) Refuel

func (s *SafeCommandBuilder) Refuel(ctx context.Context) error

Refuel safely refuels the ship

func (*SafeCommandBuilder) RefuelQueued

func (s *SafeCommandBuilder) RefuelQueued(ctx context.Context) error

RefuelQueued refuels the ship using the queue

func (*SafeCommandBuilder) Repair

func (s *SafeCommandBuilder) Repair(ctx context.Context) error

Repair safely repairs the ship

func (*SafeCommandBuilder) RepairQueued

func (s *SafeCommandBuilder) RepairQueued(ctx context.Context) error

RepairQueued repairs the ship using the queue

func (*SafeCommandBuilder) SellAllBulk

func (s *SafeCommandBuilder) SellAllBulk(ctx context.Context, reservedItems []string) error

SellAllBulk safely sells all cargo

func (*SafeCommandBuilder) SellQueued

func (s *SafeCommandBuilder) SellQueued(ctx context.Context, itemID string, quantity float64) error

SellQueued sells items using the queue

func (*SafeCommandBuilder) Travel

func (s *SafeCommandBuilder) Travel(ctx context.Context, targetPOI string) error

Travel safely travels to a POI

func (*SafeCommandBuilder) TravelQueued

func (s *SafeCommandBuilder) TravelQueued(ctx context.Context, targetPOI string) error

TravelQueued travels to a POI using the queue

func (*SafeCommandBuilder) Undock

func (s *SafeCommandBuilder) Undock(ctx context.Context) error

Undock safely undocks from a station

func (*SafeCommandBuilder) UndockQueued

func (s *SafeCommandBuilder) UndockQueued(ctx context.Context) error

UndockQueued undocks from a station using the queue

func (*SafeCommandBuilder) ViewStorageQueued

func (s *SafeCommandBuilder) ViewStorageQueued(ctx context.Context) error

ViewStorageQueued views station storage using the queue

func (*SafeCommandBuilder) WithdrawItemsQueued

func (s *SafeCommandBuilder) WithdrawItemsQueued(ctx context.Context, itemID string, quantity float64) error

WithdrawItemsQueued withdraws items from storage using the queue

type Ship

type Ship struct {
	ID                       string           `json:"id"`
	OwnerID                  string           `json:"owner_id"`
	ClassID                  string           `json:"class_id"`
	Name                     string           `json:"name"`
	Hull                     float64          `json:"hull"`
	MaxHull                  float64          `json:"max_hull"`
	Shield                   float64          `json:"shield"`
	MaxShield                float64          `json:"max_shield"`
	ShieldRecharge           float64          `json:"shield_recharge"`
	Armor                    float64          `json:"armor"`
	Speed                    float64          `json:"speed"`
	Fuel                     float64          `json:"fuel"`
	MaxFuel                  float64          `json:"max_fuel"`
	CargoUsed                float64          `json:"cargo_used"`
	CargoCapacity            float64          `json:"cargo_capacity"`
	CPUUsed                  float64          `json:"cpu_used"`
	CPUCapacity              float64          `json:"cpu_capacity"`
	PowerUsed                float64          `json:"power_used"`
	PowerCapacity            float64          `json:"power_capacity"`
	WeaponSlots              int              `json:"weapon_slots"`
	DefenseSlots             int              `json:"defense_slots"`
	UtilitySlots             int              `json:"utility_slots"`
	Modules                  []string         `json:"modules"`
	Cargo                    []CargoItem      `json:"cargo"`
	ActiveBuffs              []map[string]any `json:"active_buffs,omitempty"`
	DamagePenalty            float64          `json:"damage_penalty,omitempty"`
	SpeedPenalty             float64          `json:"speed_penalty,omitempty"`
	DisruptionTicksRemaining int              `json:"disruption_ticks_remaining,omitempty"`
	DockedAtBase             string           `json:"docked_at_base,omitempty"`
	LastProcessTick          int64            `json:"last_process_tick,omitempty"`
	CreatedAt                string           `json:"created_at,omitempty"`
}

Ship represents the player's ship with all stats, modules, and cargo. Server commands that return this struct:

  • logged_in (in payload.ship)
  • state_update (in payload.ship)
  • get_ship (in payload.ship)
  • get_status (in payload.ship)

func ShipFromAPI

func ShipFromAPI(ext serverapi.Ship) Ship

ShipFromAPI converts a serverapi Ship to an internal Ship.

type ShipDef

type ShipDef struct {
	ID            string
	Name          string
	Class         string
	Price         int
	WeaponSlots   int
	DefenseSlots  int
	UtilitySlots  int
	CargoCapacity int
}

ShipDef is a minimal ship definition used for progression building. This avoids importing pkg/knowledge into pkg/game.

func FilterShipsByEmpire

func FilterShipsByEmpire(ships []ShipDef, empire string) []ShipDef

FilterShipsByEmpire returns only ships whose ID starts with the given empire prefix. Empire values: "solarian", "crimson", "nebula", "outerrim", "voidborn".

type SimpleHandler

type SimpleHandler struct {
	Client *Client
	Logger *log.Logger
}

SimpleHandler is a basic message handler for agents It logs connection lifecycle events and message responses

func (*SimpleHandler) OnConnected

func (h *SimpleHandler) OnConnected(state *State)

OnConnected logs successful connection events

func (*SimpleHandler) OnDisconnected

func (h *SimpleHandler) OnDisconnected(err error)

OnDisconnected logs disconnection events

func (*SimpleHandler) OnMessage

func (h *SimpleHandler) OnMessage(resp protocol.Response)

OnMessage logs informational and error messages from server

type Skill

type Skill struct {
	Level int     `json:"level"`
	XP    float64 `json:"xp"`
}

Skill represents a player's skill level and XP. Embedded in Player.Skills map in server responses. Server commands that include this:

  • Any command returning Player (logged_in, state_update, get_status)

func SkillFromAPI

func SkillFromAPI(ext serverapi.Skill) Skill

SkillFromAPI converts a serverapi Skill to an internal Skill.

type SkillDefinition

type SkillDefinition struct {
	ID            string             `json:"id"`
	Name          string             `json:"name"`
	Description   string             `json:"description,omitempty"`
	Category      string             `json:"category,omitempty"`
	MaxLevel      int                `json:"max_level"`
	XpPerLevel    []float64          `json:"xp_per_level"`              // XP required to reach level i+1 (index 0 = level 0->1)
	BonusPerLevel map[string]float64 `json:"bonus_per_level,omitempty"` // e.g. {"miningYield": 5}
}

SkillDefinition holds static skill data (e.g. xp_per_level, max_level, bonuses). Server commands that return this struct:

  • get_skills (in payload.skills map, keyed by skill_id)

func SkillDefinitionFromAPI

func SkillDefinitionFromAPI(ext serverapi.SkillDefinition) SkillDefinition

SkillDefinitionFromAPI converts a serverapi SkillDefinition to an internal SkillDefinition.

type State

type State struct {
	Mu             sync.Mutex
	Username       string
	Password       string // Permanent password from registration (64-char hex string)
	Doc            bool
	CurrentSystem  string
	CurrentPOI     string
	Traveling      bool
	TravelProgress *TravelProgress // nil when not traveling
	ServerVersion  string          // Server API version

	// Player data
	Player  Player
	Credits float64
	SkillXP map[string]float64 `json:"skill_xp"` // Current XP toward next level for each skill

	// From get_skills response: XP required for next level per skill; nil if not yet loaded.
	SkillNextLevelXP map[string]float64
	// From get_skills response: skill definitions (xp_per_level, max_level, name); nil if not loaded.
	SkillDefinitions map[string]SkillDefinition

	// Ship data
	Ship     Ship
	Fuel     float64
	MaxFuel  float64
	Hull     float64
	MaxHull  float64
	Cargo    []map[string]any // Legacy format, use Ship.Cargo
	MaxCargo int

	// Module definitions (maps module ID to name/type)
	ModuleDefinitions map[string]ModuleDefinition `json:"modules,omitempty"`

	// System data
	System        SystemData
	CurrentTick   int64
	LastMapUpdate time.Time

	// Nearby players (from state_update)
	Nearby   []NearbyPlayer
	InCombat bool

	// Pirate combat information
	PirateName string
	PirateTier string
	PirateID   string
	LastDamage float64

	// Battle system (from get_battle_status / battle responses)
	InBattle    bool
	BattleState *BattleState

	// Pending trades (from logged_in response)
	PendingTrades []map[string]any
}

State represents the current game state

func (*State) Clone

func (s *State) Clone() *State

Clone creates a deep copy of the state for safe concurrent access

func (*State) GetCredits

func (s *State) GetCredits() float64

GetCredits returns the current credits

func (*State) GetCurrentSystem

func (s *State) GetCurrentSystem() string

GetCurrentSystem returns the current system name

func (*State) GetFuel

func (s *State) GetFuel() (float64, float64)

GetFuel returns current and max fuel

func (*State) GetNearbyPlayers

func (s *State) GetNearbyPlayers() []NearbyPlayer

GetNearbyPlayers returns the list of nearby players

func (*State) GetSystem

func (s *State) GetSystem() SystemData

GetSystem returns the current system data

func (*State) GetTick

func (s *State) GetTick() int64

GetTick returns the current game tick

func (*State) IsDocked

func (s *State) IsDocked() bool

IsDocked returns whether the ship is currently docked

type StationActionStrategy

type StationActionStrategy func(client *Client, logger *log.Logger, ctx context.Context) error

StationActionStrategy defines what to do with cargo when docked at a station

type StorageManager

type StorageManager interface {
	// WithdrawItems withdraws items from storage to cargo
	WithdrawItems(ctx context.Context, itemID string, quantity float64) error
	// DepositItems deposits items from cargo to storage
	DepositItems(ctx context.Context, itemID string, quantity float64) error
	// ViewStorage returns the current storage contents
	ViewStorage(ctx context.Context) (map[string]float64, error)
}

StorageManager handles storage operations

type SystemData

type SystemData struct {
	ID             string           `json:"id"`
	Name           string           `json:"name"`
	Description    string           `json:"description"`
	Empire         string           `json:"empire"`
	PoliceLevel    int              `json:"police_level"`
	SecurityStatus string           `json:"security_status,omitempty"` // Human-readable: "High Security", "Lawless", etc.
	IsStronghold   bool             `json:"is_stronghold,omitempty"`   // True for pirate stronghold systems
	Online         int              `json:"online,omitempty"`          // Number of online players (from get_map)
	POIs           []POI            `json:"pois"`                      // v0.87.1+: Enriched POI objects
	Connections    []ConnectionInfo `json:"connections"`               // v0.87.1+: ConnectionInfo objects instead of system IDs
	Discovered     bool             `json:"discovered"`
	Position       Position         `json:"position"`
	DiscoveredBy   string           `json:"discovered_by,omitempty"`
	ShipPOI        string           // ID of the POI where the ship is located (internal field, not from JSON)
}

SystemData holds complete system information including POIs, connections, and security status. Server commands that return this struct:

  • get_system (in payload.system)
  • logged_in (in payload.system)
  • get_map (array of systems when called without system_id parameter)

v0.87.1+ Enriched format:

  • POIs are objects with has_base/base_name/online instead of bare IDs
  • Connections are ConnectionInfo objects instead of bare system IDs

func SystemDataFromAPI

func SystemDataFromAPI(ext serverapi.SystemData) SystemData

SystemDataFromAPI converts a serverapi SystemData to an internal SystemData.

type TradeRoute

type TradeRoute struct {
	Name             string  `json:"name"`               // Human-readable name
	BuyEmpire        string  `json:"buy_empire"`         // Empire to buy from (lowercase)
	SellEmpire       string  `json:"sell_empire"`        // Empire to sell at (lowercase)
	OreID            string  `json:"ore_id"`             // Item to trade (e.g., "ore_silicon")
	OreName          string  `json:"ore_name"`           // Display name
	ExpectedBuy      float64 `json:"expected_buy"`       // Expected buy price per unit
	ExpectedSell     float64 `json:"expected_sell"`      // Expected sell price per unit
	Priority         int     `json:"priority"`           // Route priority (higher = better)
	ReturnRouteIndex int     `json:"return_route_index"` // Index of the paired return leg (-1 if none)
}

TradeRoute defines a one-way trade leg: buy ore at one empire, sell at another. Routes are grouped in round-trip pairs (outbound + return).

func FindTradeRoutes

func FindTradeRoutes(homeEmpire string) []TradeRoute

FindTradeRoutes returns outbound trade routes where the agent's home empire is the buy endpoint (i.e., routes that start from the agent's empire). Routes are returned sorted by priority (highest first).

func GetReturnLeg

func GetReturnLeg(route TradeRoute) (TradeRoute, bool)

GetReturnLeg returns the paired return route for a given trade route.

func (TradeRoute) Margin

func (r TradeRoute) Margin() float64

Margin returns the expected profit per unit.

type TravelProgress

type TravelProgress struct {
	Progress    float64 `json:"travel_progress"`
	Destination string  `json:"travel_destination"`
	Type        string  `json:"travel_type"` // "travel" or "jump"
	ArrivalTick int64   `json:"travel_arrival_tick"`
}

TravelProgress represents travel state when in transit (travel or jump). Server commands that return this struct:

  • state_update (when traveling, as separate fields in payload)

Fields: travel_progress, travel_destination, travel_type, travel_arrival_tick

type UpgradeProgression

type UpgradeProgression struct {
	CareerName string        // e.g., "Mining", "Combat", "Trading", "Exploration"
	Tiers      []UpgradeTier // Ordered list of upgrade tiers
}

UpgradeProgression defines a career path with upgrade tiers

func BuildProgression

func BuildProgression(ships []ShipDef, currentShipID string, role string) *UpgradeProgression

BuildProgression generates an UpgradeProgression from ship definitions. It sorts ships by price, finds the agent's current position, and chains them into upgrade tiers.

Parameters:

  • ships: all eligible ships (pre-filtered by role categories + empire)
  • currentShipID: the agent's current ship class ID
  • role: agent role (for equipment selection and career name)

Returns nil if no upgrades are available.

type UpgradeTier

type UpgradeTier struct {
	Name          string  // Human-readable name
	Threshold     float64 // Credits required
	FromShipClass string  // Current ship class to upgrade from
	ToShipClass   string  // Ship class to buy
	NumItems      int     // Number of items to buy and install (e.g., mining lasers, weapons)
	ItemID        string  // Item ID to buy (e.g., "mining_laser_1", "weapon_laser_1")
	LogEmoji      string  // Emoji for logging
	Capacity      string  // Cargo/capability description for logging
	SuccessMsg    string  // Success message template
}

UpgradeTier defines a ship/equipment upgrade configuration

Directories

Path Synopsis
Package serverapi defines types that mirror the game server's JSON wire format.
Package serverapi defines types that mirror the game server's JSON wire format.

Jump to

Keyboard shortcuts

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