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 ¶
- Constants
- Variables
- func CanUpgradeAnyShip(currentShipClass string, availableCredits float64, tiers []UpgradeTier) bool
- func CountModulesInCargo(state *State, itemID string) int
- func CountModulesInstalled(state *State, itemID string) int
- func DefaultEquipment(ship ShipDef, role string) (itemID string, count int)
- func DefaultRecipeSelector(client *Client, logger *log.Logger, ctx context.Context, ...) ([]string, error)
- func DockAtStation(client *Client, ctx context.Context, stationPOI string) error
- func EmpireHomeSystem(empire string) string
- func FindRouteByOreAndTarget(homeEmpire, oreID, targetEmpire string) (outbound TradeRoute, returnLeg TradeRoute, found bool)
- func FindStationID(state *State) string
- func FormatCaptainsLogForDisplay(entry *AgentLog) string
- func GenerateDataFilename(name, timestamp, dataType string) string
- func GetCaptainsLogDir(agentID string) string
- func GetMarketPricesForCargo(cargo []CargoItem, listings []MarketListing) map[string]int
- func HasStation(state *State) bool
- func InitializeAgent(agentID string, logger *log.Logger, ctx context.Context) (*Client, *Credentials, error)
- func IsOreOrResource(itemID string) bool
- func LootWreck(client *Client, logger *log.Logger, ctx context.Context, wreckID string) error
- func NavigateAndDock(client *Client, ctx context.Context, logger *log.Logger) error
- func NavigateToSystem(client *Client, ctx context.Context, targetSystem string, logger *log.Logger) error
- func POIFreshnessThreshold(poiType string) int64
- func PerformShipUpgrade(client *Client, logger *log.Logger, ctx context.Context, tier UpgradeTier, ...) bool
- func SaveJSONToFile(data []byte, dir, filename string) error
- func SaveStructToFile(data any, dir, filename string) error
- func SellAllLoot(client *Client, logger *log.Logger, ctx context.Context) error
- func ShipMaxSlots(ship ShipDef) int
- func ShouldUpgrade(credits float64, tiers []UpgradeTier, tier1Threshold float64) bool
- func StationActionCraftAndDeposit(client *Client, logger *log.Logger, ctx context.Context) error
- func StationActionCraftAndSell(client *Client, logger *log.Logger, ctx context.Context) error
- func StationActionSellAll(client *Client, logger *log.Logger, ctx context.Context) error
- func TryInstallAndSellExtras(client *Client, logger *log.Logger, ctx context.Context, maxSlots int)
- func UndockFromStation(client *Client, ctx context.Context) error
- func WithDocked(client *Client, ctx context.Context, stationID string, action func() error) error
- func WriteCaptainsLog(agentID string, entry *AgentLog) error
- type AgentLog
- type BattleParticipant
- type BattleState
- type BulkSellOrder
- type CargoItem
- type Client
- func (c *Client) AbandonMission(ctx context.Context, missionID string) error
- func (c *Client) AcceptMission(ctx context.Context, missionID string) error
- func (c *Client) AcceptMissionQueued(ctx context.Context, missionID string) error
- func (c *Client) AnalyzeMarket(ctx context.Context) error
- func (c *Client) Attack(ctx context.Context, targetID string) error
- func (c *Client) Battle(ctx context.Context, action string, payload map[string]any) error
- func (c *Client) BrowseShips(ctx context.Context, payload map[string]any) error
- func (c *Client) Buy(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) BuyInsurance(ctx context.Context, ticks int) error
- func (c *Client) BuyListedShip(ctx context.Context, listingID string) error
- func (c *Client) BuyQueued(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) BuyShip(ctx context.Context, shipClass string) error
- func (c *Client) CancelCommission(ctx context.Context, commissionID string) error
- func (c *Client) CancelOrder(ctx context.Context, payload map[string]any) error
- func (c *Client) CancelShipListing(ctx context.Context, listingID string) error
- func (c *Client) CaptainsLogAdd(ctx context.Context, entry string) error
- func (c *Client) CaptainsLogGet(ctx context.Context, index int) error
- func (c *Client) CaptainsLogList(ctx context.Context) error
- func (c *Client) Catalog(ctx context.Context, payload map[string]any) error
- func (c *Client) Chat(ctx context.Context, channel, content string, targetID string) error
- func (c *Client) Claim(ctx context.Context, registrationCode string) error
- func (c *Client) ClaimCommission(ctx context.Context, commissionID string) error
- func (c *Client) ClaimInsurance(ctx context.Context) error
- func (c *Client) ClearLastError()
- func (c *Client) Cloak(ctx context.Context, enable bool) error
- func (c *Client) Close() error
- func (c *Client) CommissionQuote(ctx context.Context, shipClass string) error
- func (c *Client) CommissionShip(ctx context.Context, shipClass string, provideMaterials bool) error
- func (c *Client) CommissionStatus(ctx context.Context, baseID string) error
- func (c *Client) CompleteMission(ctx context.Context, missionID string) error
- func (c *Client) CompleteMissionQueued(ctx context.Context, missionID string) error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) Craft(ctx context.Context, recipeCommand string) error
- func (c *Client) CraftFromCargo(ctx context.Context, logger *log.Logger, config *CraftingConfig) (int, error)
- func (c *Client) CraftQueued(ctx context.Context, recipeID string, quantity int) error
- func (c *Client) CraftWithQuantity(ctx context.Context, recipeID string, quantity int) error
- func (c *Client) CreateBulkSellOrder(ctx context.Context, orders []BulkSellOrder) error
- func (c *Client) CreateBuyOrder(ctx context.Context, payload map[string]any) error
- func (c *Client) CreateFaction(ctx context.Context, payload map[string]any) error
- func (c *Client) CreateNote(ctx context.Context, title, content string) error
- func (c *Client) CreateSellOrder(ctx context.Context, payload map[string]any) error
- func (c *Client) DeclineMission(ctx context.Context, templateID string) error
- func (c *Client) DepositAllItems(ctx context.Context) error
- func (c *Client) DepositCredits(ctx context.Context, amount float64) error
- func (c *Client) DepositCreditsQueued(ctx context.Context, amount float64) error
- func (c *Client) DepositItems(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) Disconnect() error
- func (c *Client) Dock(ctx context.Context) error
- func (c *Client) DockQueued(ctx context.Context) error
- func (c *Client) EnsureConnected(ctx context.Context) error
- func (c *Client) EstimatePurchase(ctx context.Context, itemID string, quantity int) error
- func (c *Client) Facility(ctx context.Context, payload map[string]any) error
- func (c *Client) FactionAcceptPeace(ctx context.Context, targetFactionID string) error
- func (c *Client) FactionCancelMission(ctx context.Context, templateID string) error
- func (c *Client) FactionCreateBuyOrder(ctx context.Context, itemID string, priceEach float64, quantity int) error
- func (c *Client) FactionCreateRole(ctx context.Context, name string, priority int, permissions map[string]any) error
- func (c *Client) FactionCreateSellOrder(ctx context.Context, itemID string, priceEach float64, quantity int) error
- func (c *Client) FactionDeclareWar(ctx context.Context, targetFactionID, reason string) error
- func (c *Client) FactionDeclineInvite(ctx context.Context, factionID string) error
- func (c *Client) FactionDeleteRole(ctx context.Context, roleID string) error
- func (c *Client) FactionDeleteRoom(ctx context.Context, roomID string) error
- func (c *Client) FactionDepositCredits(ctx context.Context, amount float64) error
- func (c *Client) FactionDepositItems(ctx context.Context, itemID string, quantity int) error
- func (c *Client) FactionEdit(ctx context.Context, payload map[string]any) error
- func (c *Client) FactionEditRole(ctx context.Context, roleID string, payload map[string]any) error
- func (c *Client) FactionGetInvites(ctx context.Context) error
- func (c *Client) FactionGift(ctx context.Context, factionID string, payload map[string]any) error
- func (c *Client) FactionInfo(ctx context.Context, factionID string) error
- func (c *Client) FactionIntelStatus(ctx context.Context) error
- func (c *Client) FactionInvite(ctx context.Context, playerID string) error
- func (c *Client) FactionKick(ctx context.Context, playerID string) error
- func (c *Client) FactionList(ctx context.Context, limit, offset int) error
- func (c *Client) FactionListMissions(ctx context.Context) error
- func (c *Client) FactionPostMission(ctx context.Context, payload map[string]any) error
- func (c *Client) FactionPromote(ctx context.Context, playerID, roleID string) error
- func (c *Client) FactionProposePeace(ctx context.Context, targetFactionID, terms string) error
- func (c *Client) FactionQueryIntel(ctx context.Context, payload map[string]any) error
- func (c *Client) FactionQueryTradeIntel(ctx context.Context, payload map[string]any) error
- func (c *Client) FactionRooms(ctx context.Context) error
- func (c *Client) FactionSetAlly(ctx context.Context, targetFactionID string) error
- func (c *Client) FactionSetEnemy(ctx context.Context, targetFactionID string) error
- func (c *Client) FactionSubmitIntel(ctx context.Context, systems []map[string]any) error
- func (c *Client) FactionSubmitTradeIntel(ctx context.Context, stations []map[string]any) error
- func (c *Client) FactionTradeIntelStatus(ctx context.Context) error
- func (c *Client) FactionVisitRoom(ctx context.Context, roomID string) error
- func (c *Client) FactionWithdrawCredits(ctx context.Context, amount float64) error
- func (c *Client) FactionWithdrawItems(ctx context.Context, itemID string, quantity int) error
- func (c *Client) FactionWriteRoom(ctx context.Context, payload map[string]any) error
- func (c *Client) FindRoute(ctx context.Context, targetSystem string) ([]RouteStep, error)
- func (c *Client) ForumCreateThread(ctx context.Context, title, content string, category string) error
- func (c *Client) ForumDeleteReply(ctx context.Context, replyID string) error
- func (c *Client) ForumDeleteThread(ctx context.Context, threadID string) error
- func (c *Client) ForumGetThread(ctx context.Context, threadID string) error
- func (c *Client) ForumList(ctx context.Context, page int) error
- func (c *Client) ForumReply(ctx context.Context, threadID, content string) error
- func (c *Client) ForumUpvote(ctx context.Context, threadID string, replyID string) error
- func (c *Client) GetActiveMissions(ctx context.Context) error
- func (c *Client) GetBase(ctx context.Context) error
- func (c *Client) GetBaseQueued(ctx context.Context) error
- func (c *Client) GetBattleStatus(ctx context.Context) error
- func (c *Client) GetCargo(ctx context.Context) error
- func (c *Client) GetCargoQueued(ctx context.Context) error
- func (c *Client) GetChatHistory(ctx context.Context, channel string, payload map[string]any) error
- func (c *Client) GetCommands(ctx context.Context) error
- func (c *Client) GetDrones(ctx context.Context) error
- func (c *Client) GetGuide(ctx context.Context, guide string) error
- func (c *Client) GetInsuranceQuote(ctx context.Context) error
- func (c *Client) GetLastError() map[string]any
- func (c *Client) GetListings(ctx context.Context) error
- func (c *Client) GetListingsQueued(ctx context.Context) error
- func (c *Client) GetMap(ctx context.Context) error
- func (c *Client) GetMarketListings() []MarketListing
- func (c *Client) GetMissions(ctx context.Context) error
- func (c *Client) GetNearby(ctx context.Context) error
- func (c *Client) GetNearbyQueued(ctx context.Context) error
- func (c *Client) GetNotes(ctx context.Context) error
- func (c *Client) GetPOI(ctx context.Context) error
- func (c *Client) GetPOIQueued(ctx context.Context) error
- func (c *Client) GetRawJSON(key string) []byte
- func (c *Client) GetRecipes(ctx context.Context) error
- func (c *Client) GetShip(ctx context.Context) error
- func (c *Client) GetShipListings() map[string]any
- func (c *Client) GetShipQueued(ctx context.Context) error
- func (c *Client) GetShips(ctx context.Context) error
- func (c *Client) GetSkills(ctx context.Context) error
- func (c *Client) GetState() *State
- func (c *Client) GetStatus(ctx context.Context) error
- func (c *Client) GetStatusQueued(ctx context.Context) error
- func (c *Client) GetSystem(ctx context.Context) error
- func (c *Client) GetSystemQueued(ctx context.Context) error
- func (c *Client) GetTrades(ctx context.Context) error
- func (c *Client) GetVersion(ctx context.Context) error
- func (c *Client) GetWrecks(ctx context.Context) error
- func (c *Client) Help(ctx context.Context, payload map[string]any) error
- func (c *Client) Install(ctx context.Context, itemID string) error
- func (c *Client) InstallMod(ctx context.Context, moduleID string) error
- func (c *Client) IsConnected() bool
- func (c *Client) Jettison(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) JoinFaction(ctx context.Context, factionID string) error
- func (c *Client) Jump(ctx context.Context, targetSystem string) error
- func (c *Client) JumpQueued(ctx context.Context, targetSystem string) error
- func (c *Client) LeaveFaction(ctx context.Context) error
- func (c *Client) ListShipForSale(ctx context.Context, shipID string, price float64) error
- func (c *Client) ListShips(ctx context.Context) error
- func (c *Client) Login(ctx context.Context) error
- func (c *Client) LootWreck(ctx context.Context, wreckID, itemID string, quantity float64) error
- func (c *Client) Mine(ctx context.Context) error
- func (c *Client) MineQueued(ctx context.Context) error
- func (c *Client) ModifyOrder(ctx context.Context, payload map[string]any) error
- func (c *Client) QueryCraftableRecipes(ctx context.Context, config *CraftingConfig) (*CraftQueryResult, error)
- func (c *Client) ReadNote(ctx context.Context, noteID string) error
- func (c *Client) Ready() <-chan struct{}
- func (c *Client) Reconnect(ctx context.Context) error
- func (c *Client) Refuel(ctx context.Context) error
- func (c *Client) RefuelQueued(ctx context.Context) error
- func (c *Client) Register(ctx context.Context, empire, registrationCode string) error
- func (c *Client) ReleaseTow(ctx context.Context) error
- func (c *Client) Reload(ctx context.Context, weaponInstanceID, ammoItemID string) error
- func (c *Client) Repair(ctx context.Context) error
- func (c *Client) RepairQueued(ctx context.Context) error
- func (c *Client) SalvageWreck(ctx context.Context, wreckID string) error
- func (c *Client) Scan(ctx context.Context) error
- func (c *Client) ScanTarget(ctx context.Context, targetID string) error
- func (c *Client) ScrapWreck(ctx context.Context) error
- func (c *Client) SearchChangelog(ctx context.Context, payload map[string]any) error
- func (c *Client) SearchSystems(ctx context.Context, query string) error
- func (c *Client) SelfDestruct(ctx context.Context) error
- func (c *Client) Sell(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) SellAll(ctx context.Context) error
- func (c *Client) SellAllBulk(ctx context.Context, reservedItems []string) error
- func (c *Client) SellQueued(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) SellShip(ctx context.Context, shipID string) error
- func (c *Client) SellWreck(ctx context.Context) error
- func (c *Client) Send(ctx context.Context, msg protocol.Message) error
- func (c *Client) SendGift(ctx context.Context, payload map[string]any) error
- func (c *Client) SendQueued(ctx context.Context, msg protocol.Message, timeout time.Duration) (protocol.Response, error)
- func (c *Client) SetAnonymous(ctx context.Context, anonymous bool) error
- func (c *Client) SetColors(ctx context.Context, primaryColor, secondaryColor string) error
- func (c *Client) SetHandler(handler MessageHandler)
- func (c *Client) SetHomeBase(ctx context.Context, baseID string) error
- func (c *Client) SetPlayerStatus(ctx context.Context, payload map[string]any) error
- func (c *Client) ShipyardShowroom(ctx context.Context, payload map[string]any) error
- func (c *Client) SurveySystem(ctx context.Context) error
- func (c *Client) SwitchShip(ctx context.Context, shipID string) error
- func (c *Client) TowWreck(ctx context.Context, wreckID string) error
- func (c *Client) TradeAccept(ctx context.Context, tradeID string) error
- func (c *Client) TradeCancel(ctx context.Context, tradeID string) error
- func (c *Client) TradeDecline(ctx context.Context, tradeID string) error
- func (c *Client) TradeOffer(ctx context.Context, targetID string, payload map[string]any) error
- func (c *Client) Travel(ctx context.Context, targetPOI string) error
- func (c *Client) TravelQueued(ctx context.Context, targetPOI string) error
- func (c *Client) Undock(ctx context.Context) error
- func (c *Client) UndockQueued(ctx context.Context) error
- func (c *Client) UninstallMod(ctx context.Context, moduleID string) error
- func (c *Client) UseItem(ctx context.Context, itemID string, quantity int) error
- func (c *Client) ViewFactionStorage(ctx context.Context) error
- func (c *Client) ViewMarket(ctx context.Context, itemID string) error
- func (c *Client) ViewOrders(ctx context.Context) error
- func (c *Client) ViewStorage(ctx context.Context) error
- func (c *Client) ViewStorageQueued(ctx context.Context) error
- func (c *Client) WaitForReady(ctx context.Context, timeout time.Duration) error
- func (c *Client) WithdrawCredits(ctx context.Context, amount float64) error
- func (c *Client) WithdrawItems(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) WithdrawItemsQueued(ctx context.Context, itemID string, quantity float64) error
- func (c *Client) WriteNote(ctx context.Context, noteID, content string) error
- type CommandQueue
- type Component
- type ConnectionInfo
- type CraftQueryResult
- type CraftableRecipe
- type CraftingConfig
- type CraftingLoopConfig
- type CraftingLoopResult
- type Credentials
- type GameClient
- type MCPClient
- type MCPCraftQueryResponse
- type MCPManager
- type MarketListing
- type MarketSnapshot
- type MessageHandler
- type MiningLoopConfig
- type MiningLoopResult
- type ModuleDefinition
- type NearbyPlayer
- type OwnedShip
- type POI
- type POIResource
- type Player
- type PlayerSkill
- type PlayerStats
- type Position
- type QueuedCommand
- type RecipeSelector
- type ReconnectingHandler
- type RobustCommandExecutor
- type RouteStep
- type SafeCommandBuilder
- func (s *SafeCommandBuilder) AcceptMissionQueued(ctx context.Context, missionID string) error
- func (s *SafeCommandBuilder) Buy(ctx context.Context, itemID string, quantity float64) error
- func (s *SafeCommandBuilder) BuyQueued(ctx context.Context, itemID string, quantity float64) error
- func (s *SafeCommandBuilder) CompleteMissionQueued(ctx context.Context, missionID string) error
- func (s *SafeCommandBuilder) CraftQueued(ctx context.Context, recipeID string, quantity int) error
- func (s *SafeCommandBuilder) Dock(ctx context.Context) error
- func (s *SafeCommandBuilder) DockQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetBaseQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetCargoQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetListings(ctx context.Context) error
- func (s *SafeCommandBuilder) GetListingsQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetNearbyQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetPOI(ctx context.Context) error
- func (s *SafeCommandBuilder) GetPOIQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetShipQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetStatus(ctx context.Context) error
- func (s *SafeCommandBuilder) GetStatusQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) GetSystem(ctx context.Context) error
- func (s *SafeCommandBuilder) GetSystemQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) Jump(ctx context.Context, targetSystem string) error
- func (s *SafeCommandBuilder) JumpQueued(ctx context.Context, targetSystem string) error
- func (s *SafeCommandBuilder) Mine(ctx context.Context) error
- func (s *SafeCommandBuilder) MineQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) Refuel(ctx context.Context) error
- func (s *SafeCommandBuilder) RefuelQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) Repair(ctx context.Context) error
- func (s *SafeCommandBuilder) RepairQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) SellAllBulk(ctx context.Context, reservedItems []string) error
- func (s *SafeCommandBuilder) SellQueued(ctx context.Context, itemID string, quantity float64) error
- func (s *SafeCommandBuilder) Travel(ctx context.Context, targetPOI string) error
- func (s *SafeCommandBuilder) TravelQueued(ctx context.Context, targetPOI string) error
- func (s *SafeCommandBuilder) Undock(ctx context.Context) error
- func (s *SafeCommandBuilder) UndockQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) ViewStorageQueued(ctx context.Context) error
- func (s *SafeCommandBuilder) WithdrawItemsQueued(ctx context.Context, itemID string, quantity float64) error
- type Ship
- type ShipDef
- type SimpleHandler
- type Skill
- type SkillDefinition
- type State
- func (s *State) Clone() *State
- func (s *State) GetCredits() float64
- func (s *State) GetCurrentSystem() string
- func (s *State) GetFuel() (float64, float64)
- func (s *State) GetNearbyPlayers() []NearbyPlayer
- func (s *State) GetSystem() SystemData
- func (s *State) GetTick() int64
- func (s *State) IsDocked() bool
- type StationActionStrategy
- type StorageManager
- type SystemData
- type TradeRoute
- type TravelProgress
- type UpgradeProgression
- type UpgradeTier
Examples ¶
Constants ¶
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
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
const ( FuelCriticalThreshold = 0.3 // 30% fuel: critically low, refuel soon FuelLowThreshold = 0.8 // 80% fuel: refuel when at station )
Fuel thresholds
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
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
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
const ( ClientName = "rsned/spacemolt" VersionID = "v0.0.1" UserAgent = ClientName + "/" + VersionID )
Client identity
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)
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
const (
// DefaultGameServerURL is the default WebSocket endpoint for the game
DefaultGameServerURL = "wss://game.spacemolt.com/ws"
)
const (
MinimumPurchaseThreshold = 100.0 // Minimum credits to attempt any purchase
)
Credit thresholds
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
const (
ShieldDepletedThreshold = 10.0 // Shield percent: depleted, combine with hull for flee decision
)
Shield percentage thresholds
Variables ¶
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 ¶
CountModulesInCargo counts how many of a specific module type are in cargo
func CountModulesInstalled ¶
CountModulesInstalled counts how many of a specific module type are installed
func DefaultEquipment ¶
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 ¶
DockAtStation docks the client at a station POI Returns error if docking fails (excluding "already docked" which is treated as success)
func EmpireHomeSystem ¶
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 ¶
FindStationID returns the ID of the first station in the current system, or empty string if none found
func FormatCaptainsLogForDisplay ¶
FormatCaptainsLogForDisplay formats a captain's log entry for human-readable display
func GenerateDataFilename ¶
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 ¶
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 ¶
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 ¶
IsOreOrResource returns true if item is ore or a resource (should be sold, not installed)
func LootWreck ¶
LootWreck loots all items from a wreck Useful for fighters and pirates who defeat NPCs
func NavigateAndDock ¶
NavigateAndDock finds the station in the current system, travels to it, and docks.
func NavigateToSystem ¶
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 ¶
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 ¶
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 ¶
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 ¶
SellAllLoot sells all loot items in cargo Useful for fighters and pirates after combat
func ShipMaxSlots ¶
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 ¶
StationActionCraftAndDeposit crafts items from cargo resources, then deposits everything
func StationActionCraftAndSell ¶
StationActionCraftAndSell crafts items from cargo resources, then sells everything
func StationActionSellAll ¶
StationActionSellAll simply sells all cargo without any crafting
func TryInstallAndSellExtras ¶
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 ¶
UndockFromStation undocks the client from the current station
func WithDocked ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 (*Client) AbandonMission ¶
AbandonMission abandons an active mission.
func (*Client) AcceptMission ¶
AcceptMission accepts a mission from the mission board.
func (*Client) AcceptMissionQueued ¶
AcceptMissionQueued accepts a mission using the queue
func (*Client) AnalyzeMarket ¶
AnalyzeMarket gets actionable trading insights at the current station.
func (*Client) Battle ¶
Battle manages tactical battle actions (advance, retreat, stance, target, engage).
func (*Client) BrowseShips ¶
BrowseShips browses ships listed for sale at a base.
func (*Client) BuyInsurance ¶
BuyInsurance purchases ship insurance for a number of ticks.
func (*Client) BuyListedShip ¶
BuyListedShip purchases a ship listed by another player.
func (*Client) CancelCommission ¶
CancelCommission cancels a pending or in-progress ship commission.
func (*Client) CancelOrder ¶
CancelOrder cancels an active exchange order and returns escrow.
func (*Client) CancelShipListing ¶
CancelShipListing removes a ship listing from the exchange.
func (*Client) CaptainsLogAdd ¶
CaptainsLogAdd adds an entry to your captain's log.
func (*Client) CaptainsLogGet ¶
CaptainsLogGet gets a specific entry from your captain's log.
func (*Client) CaptainsLogList ¶
CaptainsLogList lists all entries in your captain's log.
func (*Client) Claim ¶
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 ¶
ClaimCommission claims a completed ship from a commission.
func (*Client) ClaimInsurance ¶
ClaimInsurance views your active insurance policies.
func (*Client) ClearLastError ¶
func (c *Client) ClearLastError()
ClearLastError clears the stored error
func (*Client) CommissionQuote ¶
CommissionQuote gets a cost estimate for commissioning a ship.
func (*Client) CommissionShip ¶
CommissionShip commissions a ship to be built at the current shipyard.
func (*Client) CommissionStatus ¶
CommissionStatus checks the status of ship commissions.
func (*Client) CompleteMission ¶
CompleteMission completes a mission and claims rewards.
func (*Client) CompleteMissionQueued ¶
CompleteMissionQueued completes a mission using the queue
func (*Client) Connect ¶
Connect establishes a WebSocket connection to the game server Implements retry logic with exponential backoff for rate limiting (429 errors)
func (*Client) Craft ¶
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 ¶
CraftQueued crafts an item using the queue
func (*Client) CraftWithQuantity ¶
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 ¶
CreateBuyOrder places a buy offer on the station exchange.
func (*Client) CreateFaction ¶
CreateFaction creates a new faction.
func (*Client) CreateNote ¶
CreateNote creates a new note document.
func (*Client) CreateSellOrder ¶
CreateSellOrder lists items for sale on the station exchange.
func (*Client) DeclineMission ¶
DeclineMission declines a mission and hears the NPC's response.
func (*Client) DepositAllItems ¶
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 ¶
DepositCredits moves credits from wallet to station storage.
func (*Client) DepositCreditsQueued ¶
DepositCreditsQueued deposits credits to storage using the queue
func (*Client) DepositItems ¶
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 ¶
Disconnect closes the WebSocket connection
func (*Client) DockQueued ¶
DockQueued docks at a station using the queue
func (*Client) EnsureConnected ¶
EnsureConnected ensures the client is connected, reconnecting if necessary
func (*Client) EstimatePurchase ¶
EstimatePurchase previews what buying would cost without executing.
func (*Client) FactionAcceptPeace ¶
FactionAcceptPeace accepts a peace proposal.
func (*Client) FactionCancelMission ¶
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 ¶
FactionDeclareWar declares war on another faction.
func (*Client) FactionDeclineInvite ¶
FactionDeclineInvite declines a faction invitation.
func (*Client) FactionDeleteRole ¶
FactionDeleteRole deletes a custom faction role.
func (*Client) FactionDeleteRoom ¶
FactionDeleteRoom deletes a room from your faction's common space.
func (*Client) FactionDepositCredits ¶
FactionDepositCredits transfers credits from your wallet to faction storage.
func (*Client) FactionDepositItems ¶
FactionDepositItems moves items from your cargo to faction storage.
func (*Client) FactionEdit ¶
FactionEdit updates faction description, charter, and colors.
func (*Client) FactionEditRole ¶
FactionEditRole edits a custom faction role.
func (*Client) FactionGetInvites ¶
FactionGetInvites views pending faction invitations.
func (*Client) FactionGift ¶
FactionGift gifts items or credits to a faction's storage.
func (*Client) FactionInfo ¶
FactionInfo views faction details. If factionID is empty, views your own faction.
func (*Client) FactionIntelStatus ¶
FactionIntelStatus views faction intel coverage statistics.
func (*Client) FactionInvite ¶
FactionInvite invites a player to your faction.
func (*Client) FactionKick ¶
FactionKick kicks a player from your faction.
func (*Client) FactionList ¶
FactionList lists all factions.
func (*Client) FactionListMissions ¶
FactionListMissions lists your faction's posted missions at this station.
func (*Client) FactionPostMission ¶
FactionPostMission posts a mission on your faction's mission board.
func (*Client) FactionPromote ¶
FactionPromote promotes or demotes a faction member.
func (*Client) FactionProposePeace ¶
FactionProposePeace proposes peace to a faction you're at war with.
func (*Client) FactionQueryIntel ¶
FactionQueryIntel queries your faction's intel database.
func (*Client) FactionQueryTradeIntel ¶
FactionQueryTradeIntel searches your faction's market price database.
func (*Client) FactionRooms ¶
FactionRooms lists rooms in your faction's common space at the current station.
func (*Client) FactionSetAlly ¶
FactionSetAlly marks another faction as ally.
func (*Client) FactionSetEnemy ¶
FactionSetEnemy marks another faction as enemy.
func (*Client) FactionSubmitIntel ¶
FactionSubmitIntel submits system intel to your faction's shared map.
func (*Client) FactionSubmitTradeIntel ¶
FactionSubmitTradeIntel submits market price observations to your faction's trade ledger.
func (*Client) FactionTradeIntelStatus ¶
FactionTradeIntelStatus views faction trade intelligence coverage statistics.
func (*Client) FactionVisitRoom ¶
FactionVisitRoom visits a room and reads its description.
func (*Client) FactionWithdrawCredits ¶
FactionWithdrawCredits transfers credits from faction storage to your wallet.
func (*Client) FactionWithdrawItems ¶
FactionWithdrawItems moves items from faction storage to your cargo.
func (*Client) FactionWriteRoom ¶
FactionWriteRoom creates or updates a room in your faction's common space.
func (*Client) FindRoute ¶
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 ¶
ForumDeleteReply deletes a forum reply.
func (*Client) ForumDeleteThread ¶
ForumDeleteThread deletes a forum thread.
func (*Client) ForumGetThread ¶
ForumGetThread gets a forum thread and its replies.
func (*Client) ForumReply ¶
ForumReply replies to a forum thread.
func (*Client) ForumUpvote ¶
ForumUpvote upvotes a thread or reply.
func (*Client) GetActiveMissions ¶
GetActiveMissions views your active missions and progress.
func (*Client) GetBaseQueued ¶
GetBaseQueued gets base info using the queue
func (*Client) GetBattleStatus ¶
GetBattleStatus queries the current battle state (free query, no tick cost).
func (*Client) GetCargoQueued ¶
GetCargoQueued gets cargo contents using the queue
func (*Client) GetChatHistory ¶
GetChatHistory gets chat message history.
func (*Client) GetCommands ¶
GetCommands gets a structured list of all commands.
func (*Client) GetInsuranceQuote ¶
GetInsuranceQuote gets a risk-based insurance quote for the current ship.
func (*Client) GetLastError ¶
GetLastError returns the most recent error response
func (*Client) GetListings ¶
GetListings requests market listings for the current station
func (*Client) GetListingsQueued ¶
GetListingsQueued gets market listings using the queue
func (*Client) GetMarketListings ¶
func (c *Client) GetMarketListings() []MarketListing
GetMarketListings returns the most recently fetched market listings
func (*Client) GetMissions ¶
GetMissions gets available missions at the current base.
func (*Client) GetNearbyQueued ¶
GetNearbyQueued gets nearby players using the queue
func (*Client) GetPOIQueued ¶
GetPOIQueued gets POI info using the queue
func (*Client) GetRawJSON ¶
GetRawJSON retrieves the raw JSON payload for a given key
func (*Client) GetRecipes ¶
GetRecipes gets available crafting recipes.
func (*Client) GetShipListings ¶
GetShipListings returns the most recently fetched ship listings
func (*Client) GetShipQueued ¶
GetShipQueued gets ship info using the queue
func (*Client) GetStatusQueued ¶
GetStatusQueued gets status using the queue
func (*Client) GetSystemQueued ¶
GetSystemQueued gets system info using the queue
func (*Client) GetVersion ¶
GetVersion gets game version and release notes.
func (*Client) InstallMod ¶
InstallMod installs a module on the ship.
func (*Client) IsConnected ¶
IsConnected returns whether the client is connected
func (*Client) JoinFaction ¶
JoinFaction joins a faction via invitation.
func (*Client) JumpQueued ¶
JumpQueued jumps to another system using the queue
func (*Client) LeaveFaction ¶
LeaveFaction leaves your current faction.
func (*Client) ListShipForSale ¶
ListShipForSale lists a stored ship for sale on the exchange.
func (*Client) Login ¶
Login authenticates with the server using stored credentials This is a synchronous operation that waits for the server response
func (*Client) MineQueued ¶
MineQueued mines resources using the queue
func (*Client) ModifyOrder ¶
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) 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) RefuelQueued ¶
RefuelQueued refuels using the queue
func (*Client) Register ¶
Register creates a new account This is a synchronous operation that waits for the server response
func (*Client) ReleaseTow ¶
ReleaseTow releases a towed wreck at the current location.
func (*Client) RepairQueued ¶
RepairQueued repairs using the queue
func (*Client) SalvageWreck ¶
SalvageWreck salvages a wreck for raw materials.
func (*Client) ScanTarget ¶
ScanTarget scans a specific target player.
func (*Client) ScrapWreck ¶
ScrapWreck scraps a towed wreck for salvage materials.
func (*Client) SearchChangelog ¶
SearchChangelog searches release notes and version history.
func (*Client) SearchSystems ¶
SearchSystems searches for systems by name.
func (*Client) SelfDestruct ¶
SelfDestruct destroys your own ship.
func (*Client) SellAllBulk ¶
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 ¶
SellQueued sells items using the queue
func (*Client) SendGift ¶
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 ¶
SetAnonymous sets anonymous mode.
func (*Client) SetHandler ¶
func (c *Client) SetHandler(handler MessageHandler)
SetHandler sets the message handler
func (*Client) SetHomeBase ¶
SetHomeBase sets the home base for respawning.
func (*Client) SetPlayerStatus ¶
SetPlayerStatus sets your status message and clan tag.
func (*Client) ShipyardShowroom ¶
ShipyardShowroom browses ships available for immediate purchase at this shipyard.
func (*Client) SurveySystem ¶
SurveySystem scans for hidden POIs in the current system Requires a survey scanner module installed
func (*Client) SwitchShip ¶
SwitchShip switches to a different ship stored at the current station.
func (*Client) TradeAccept ¶
TradeAccept accepts a trade offer.
func (*Client) TradeCancel ¶
TradeCancel cancels your trade offer.
func (*Client) TradeDecline ¶
TradeDecline declines a trade offer.
func (*Client) TradeOffer ¶
TradeOffer offers a trade to another player.
func (*Client) TravelQueued ¶
TravelQueued travels to a POI using the queue
func (*Client) UndockQueued ¶
UndockQueued undocks from a station using the queue
func (*Client) UninstallMod ¶
UninstallMod uninstalls a module from the ship.
func (*Client) ViewFactionStorage ¶
ViewFactionStorage views your faction's shared storage at the current station.
func (*Client) ViewMarket ¶
ViewMarket views the order book at the current station.
func (*Client) ViewOrders ¶
ViewOrders views your own orders at the current station.
func (*Client) ViewStorage ¶
ViewStorage views your storage at the current station.
func (*Client) ViewStorageQueued ¶
ViewStorageQueued views station storage using the queue
func (*Client) WaitForReady ¶
WaitForReady waits for the connection to be ready (first message received)
func (*Client) WithdrawCredits ¶
WithdrawCredits moves credits from station storage to wallet.
func (*Client) WithdrawItems ¶
WithdrawItems moves items from station storage to cargo.
func (*Client) WithdrawItemsQueued ¶
WithdrawItemsQueued withdraws items from storage using the queue
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
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:
- Find nearest station
- Dock at station if not docked
- Withdraw resources from storage (if configured)
- Craft items based on strategy
- Handle crafted items (deposit/sell)
- 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 ¶
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
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
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:
- Find mining POI and station in current system
- Undock if docked
- Travel to mining location
- Mine until cargo full or fuel low
- Travel back to station
- Dock at station
- Sell all cargo
- Refuel if needed
- 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 ¶
FindJumpGate returns the first jump gate POI in the current system, or nil if none found
func FindMiningLocation ¶
FindMiningLocation returns the first mining POI (asteroid_belt or asteroid_field) in the current system, or nil if none found
func FindPOIByType ¶
FindPOIByType returns the first POI of the given type in the current system, or nil if none found
func FindStation ¶
FindStation returns the first station POI in the current system, or nil if none found
func POIFromAPI ¶
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 ¶
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 ¶
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) CompleteMissionQueued ¶
func (s *SafeCommandBuilder) CompleteMissionQueued(ctx context.Context, missionID string) error
CompleteMissionQueued completes a mission using the queue
func (*SafeCommandBuilder) CraftQueued ¶
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 ¶
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 ¶
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 ¶
FilterShipsByEmpire returns only ships whose ID starts with the given empire prefix. Empire values: "solarian", "crimson", "nebula", "outerrim", "voidborn".
type SimpleHandler ¶
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 ¶
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 ¶
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) GetCredits ¶
GetCredits returns the current credits
func (*State) GetCurrentSystem ¶
GetCurrentSystem returns the current system name
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
type StationActionStrategy ¶
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