game

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 31 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package game — structured server-error types and goal-reached classification. See docs/superpowers/specs/2026-04-22-loop-goal-reached-design.md.

Example (CaptainsLog)

Example demonstrates basic usage of the captain's log system

package main

import (
	"fmt"
	"log"
	"os"

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

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

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

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

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

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

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

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

package main

import (
	"fmt"
	"os"

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

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

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

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

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

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

Index

Examples

Constants

View Source
const (
	// DefaultGameServerURL is the default WebSocket endpoint for the game
	DefaultGameServerURL = "wss://game.spacemolt.com/ws"

	// DefaultMCPServerURL is the default MCP endpoint for the game
	DefaultMCPServerURL = "https://game.spacemolt.com/mcp"

	// DefaultCatalogURL is the static game catalog download (no auth required).
	// It returns the entire catalog (ships, skills, recipes, items, modules,
	// facilities) as a single JSON document with a top-level version field.
	// Cached with an ETag (supports If-None-Match -> 304) and rate-limited to
	// 1/min per IP, so fetch it once per version and grep the local copy.
	DefaultCatalogURL = "https://game.spacemolt.com/api/catalog.json"
)
View Source
const (
	SleepTick   = 10 * time.Second // One game server tick is 10 seconds.
	SleepQuick  = SleepTick / 5    // Non-mutation command and queries.
	SleepShort  = SleepTick / 3    // Short operations (refuel, repair, install)
	SleepMedium = SleepTick / 2    // Medium wait operations
	SleepLong   = 2 * SleepTick    // Longer wait operations

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

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

	// Initial response timeouts for actions that may take multiple ticks to start
	SleepActionStartTimeout = 3 * SleepTick // 30s timeout for travel/jump to acknowledge

	// Hard cap on the wait window a travel/jump can spend blocked waiting
	// for an arrival event. Within-system travel never exceeds ~9 ticks of
	// game time, so 18 ticks (~3min) is an overgenerous safety bound that
	// also defeats the failure mode where a stale local CurrentTick inflates
	// `arrival_tick - currentTick`.
	SleepTravelMaxWait = 18 * SleepTick // 3min hard cap for in-system travel
	SleepJumpMaxWait   = 30 * SleepTick // 5min hard cap for cross-system jump

	// Espionage blocks the player for ~90s (9 ticks) server-side before it
	// resolves, far longer than an ordinary mutation. 18 ticks doubles that
	// for headroom against a slow-running server.
	SleepEspionageMaxWait = 18 * SleepTick // 3min hard cap for espionage

	SleepReconnect         = 30 * time.Second // Reconnection recovery wait
	SleepRetry             = 1 * time.Second  // Retry delay for failed operations
	SleepScanInterval      = 5 * time.Minute  // Delay between scan_for_distress cycles
	SleepChatPoll          = 1 * time.Hour    // Chat channel polling interval (background reconcile/ingest)
	SleepIPRateLimitJitter = 60 * time.Second // Max random jitter added after IP rate limit expires

	SleepPartnerJoinWindow = 5 * time.Minute // Max wait for a human to attack a bot in spar partner mode

	// WebSocket keepalive timing
	// We actively send protocol-level pings to keep NAT/proxy flows warm and to
	// detect dead connections promptly. The passive no-message timeout remains as
	// a safety net for the case where the ping goroutine itself wedges.
	SleepWSPingInterval = 20 * time.Second // Send a WebSocket ping every 20s
	SleepWSPingTimeout  = 10 * time.Second // Per-ping deadline waiting for pong
	SleepWSHealthCheck  = 30 * time.Second // Check connection health every 30 seconds
	SleepWSPongTimeout  = 5 * time.Minute  // Safety net: only trigger if pings also stopped firing

	// PingMaxConsecutiveFailures is how many consecutive ping failures we
	// tolerate before force-closing the socket to trigger a reconnect. Two
	// failures means ~30s of unresponsiveness (20s interval + 10s timeout).
	PingMaxConsecutiveFailures = 2

	// SessionContentionMinUptime is the threshold under which a connection
	// that just died is considered "short-lived" for session-contention
	// detection. Healthy reconnects normally stay up for minutes; if a
	// fresh connection drops in <30s we're almost certainly being kicked.
	SessionContentionMinUptime = 30 * time.Second

	// SessionContentionMaxShortLived is how many consecutive short-lived
	// connects we accept before concluding another client is logged in
	// with the same credentials. The server does not send a structured
	// kick notification — it just closes the socket — so we detect the
	// pattern heuristically and stop the reconnect loop rather than
	// ping-pong kicking the other session indefinitely.
	SessionContentionMaxShortLived = 2
)

Sleep durations for various game operations

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

Hull percentage thresholds

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

Fuel thresholds

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

Cargo capacity thresholds

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

Combat thresholds

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

	// PassiveSkillCheckInterval is how often the agent runner injects a
	// get_skills query to capture passive XP gains (e.g. Engineering when
	// the ship is fully power-loaded). Wall-clock based, not tick-based,
	// so reports can normalise to per-real-second or per-tick rates
	// regardless of server tick-rate variance.
	PassiveSkillCheckInterval = 20 * time.Minute
)

Timing constants

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

Client identity

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

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

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

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

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

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

TimestampFormat constants for consistent filename generation

View Source
const FreshnessFaction = 24 * time.Hour

FreshnessFaction is how long a stored faction record is considered current before the faction_info backfill will re-fetch it: 1 day.

View Source
const (
	MapCacheTTL = 1 * time.Hour // Map data changes infrequently; refresh at most once per hour
)

Cache durations

View Source
const MaxCraftBulkJobs = 50

MaxCraftBulkJobs is the server-enforced ceiling on jobs per bulk craft request.

View Source
const (
	MinimumPurchaseThreshold = 100.0 // Minimum credits to attempt any purchase
)

Credit thresholds

View Source
const ServerAPIVersion = "v0.112.0"

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

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

Shield percentage thresholds

Variables

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

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

Functions

func CanUpgradeAnyShip

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

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

func CheckOKResponseFields added in v0.2.0

func CheckOKResponseFields(payload map[string]any)

CheckOKResponseFields checks a TypeOK response for unknown actions or unknown fields. Exported so both WebSocket and MCP transports can use it.

func CountModulesInCargo

func CountModulesInCargo(state *State, itemID string) int

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

func CountModulesInstalled

func CountModulesInstalled(state *State, itemID string) int

CountModulesInstalled counts how many of a specific module type are installed

func DefaultEquipment

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

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

func DefaultReconnectGatePath added in v0.2.0

func DefaultReconnectGatePath() string

DefaultReconnectGatePath is the host-global gate file. All spacemolt clients on one host (and therefore one outbound IP) share it. Overridable via the SPACEMOLT_RECONNECT_GATE environment variable.

func DockAtStation

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

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

func EmpireHomeSystem

func EmpireHomeSystem(empire string) string

EmpireHomeSystem returns the home system for a given empire name.

func FindRouteByOreAndTarget

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

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

func FindStationID

func FindStationID(state *State) string

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

func FormatCaptainsLogForDisplay

func FormatCaptainsLogForDisplay(entry *AgentLog) string

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

func GenerateDataFilename

func GenerateDataFilename(name, timestamp, dataType string) string

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

Examples:

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

func GetCaptainsLogDir

func GetCaptainsLogDir(agentID string) string

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

func GetMarketPricesForCargo

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

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

Parameters:

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

Returns:

  • priceMap: Map of item_id to suggested price_each for selling

func HasModuleType added in v0.2.0

func HasModuleType(state *State, typeID string) bool

HasModuleType checks if any installed module has the specified type_id. This is used to check for module categories like survey scanners regardless of the specific module variant (survey_scanner_i, survey_scanner_ii, etc.)

func HasStation

func HasStation(state *State) bool

HasStation checks if the current system has a station

func InitializeAgent

func InitializeAgent(agentID string, logger *log.Logger, ctx context.Context, debug bool) (*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
  • debug: When true, enables verbose WebSocket debug logging; when false, debug output is suppressed

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, false)
if err != nil {
    log.Fatalf("Failed to initialize agent: %v", err)
}
defer client.Close()

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

func InitializeMCPAgent added in v0.2.0

func InitializeMCPAgent(agentID string, logger *log.Logger, ctx context.Context, debug bool, disablePolling bool) (GameClient, *Credentials, error)

InitializeMCPAgent creates and initializes an MCP game client for an autonomous agent. It uses direct HTTP to the MCP endpoint instead of WebSocket.

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:

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

func IsOreOrResource

func IsOreOrResource(itemID string) bool

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

func LootWreck

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

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

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

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

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

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

func POIFreshnessThreshold

func POIFreshnessThreshold(poiType string) int64

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

func PerformShipUpgrade

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

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

func SaveJSONToFile

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

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

Parameters:

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

Returns error if directory creation or file write fails

func SaveStructToFile

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

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

Example:

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

func SellAllLoot

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

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

func ShipMaxSlots

func ShipMaxSlots(ship ShipDef) int

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

func ShouldUpgrade

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

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

func StationActionCraftAndDeposit

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

StationActionCraftAndDeposit crafts items from cargo resources, then deposits everything

func StationActionCraftAndSell

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

StationActionCraftAndSell crafts items from cargo resources, then sells everything

func StationActionSellAll

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

StationActionSellAll simply sells all cargo without any crafting

func TryInstallAndSellExtras

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

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

func UndockFromStation

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

UndockFromStation undocks the client from the current station

func WithDocked

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

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

Example:

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

func WithResultSink added in v0.2.0

func WithResultSink(ctx context.Context, sink *protocol.Response) context.Context

WithResultSink returns a context that captures the terminal protocol.Response of any Submit awaited via (*Client).await into *sink. Interactive callers (the play_as REPL) use this to obtain the exact request_id-correlated frame for the command they issued, rather than reading the racy command-keyed latestRawJSON slot that a concurrent background command can clobber. The sink belongs to the caller's own context, so unrelated goroutines (background pollers) using their own contexts never write to it.

func WriteCaptainsLog

func WriteCaptainsLog(agentID string, entry *AgentLog) error

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

Example usage:

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

Types

type AgentLog

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

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

func ReadAllCaptainsLogs

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

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

Example usage:

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

func ReadLatestCaptainsLog

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

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

Example usage:

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

type BattleParticipant

type BattleParticipant struct {
	PlayerID  string  `json:"player_id"`
	Username  string  `json:"username"`
	ShipClass string  `json:"ship_class"`
	SideID    string  `json:"side_id"`
	Zone      string  `json:"zone"`
	Stance    string  `json:"stance"`
	Hull      float64 `json:"hull"`
	MaxHull   float64 `json:"max_hull"`
	Shield    float64 `json:"shield"`
	MaxShield float64 `json:"max_shield"`
	// Percentage + tactical fields as reported by get_battle_status / battle_update.
	HullPct   int    `json:"hull_pct"`
	ShieldPct int    `json:"shield_pct"`
	TargetID  string `json:"target_id,omitempty"`
	AutoPilot bool   `json:"auto_pilot,omitempty"`
}

BattleParticipant represents a participant in a tactical battle.

type BattleState

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

BattleState represents the current state of a tactical battle.

type BulkSellOrder

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

BulkSellOrder represents a single item to sell in a bulk order

func PrepareBulkSellOrder

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

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

Parameters:

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

Returns:

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

type CargoItem

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

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

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

func CargoItemFromAPI

func CargoItemFromAPI(ext serverapi.CargoItem) CargoItem

CargoItemFromAPI converts a serverapi CargoItem to an internal CargoItem.

type ChatMessage added in v0.2.0

type ChatMessage struct {
	ID        string
	Channel   string
	SenderID  string
	Sender    string
	Content   string
	TargetID  string
	Timestamp string
}

ChatMessage represents a chat message stored in game state.

type Classifier added in v0.2.0

type Classifier func(resp protocol.Response) bool

Classifier decides whether a given response should be delivered to a subscriber. Used by queries, pushes, and as the "match mine" gate for mutations. Zero allocations by convention: classifiers are cheap closures.

type Client

type Client struct {

	// Crafting configuration
	CraftingConfig *CraftingConfig

	// Structured call logger for request/response pairs
	CallLogger *calllog.Logger

	// XP observation tracking — fires whenever skill XP changes in state
	XPCallback XPCallbackFunc
	// contains filtered or unexported fields
}

Client represents a WebSocket client for the Spacemolt game

func NewClient

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

NewClient creates a new game client

func (*Client) AbandonMission

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

AbandonMission abandons an active mission.

func (*Client) AcceptMission

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

AcceptMission accepts a mission from the mission board.

func (*Client) AgentLogs added in v0.2.0

func (c *Client) AgentLogs(ctx context.Context, category, severity, message string, data map[string]any) error

AgentLogs submits an agent telemetry log entry. data is optional structured context. The action is write-only (no response body) and ack-terminated.

func (*Client) AnalyzeMarket

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

AnalyzeMarket gets actionable trading insights at the current station.

func (*Client) Attack

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

Attack attacks a target player or NPC

func (*Client) Battle

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

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

func (*Client) BrowseShips

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

BrowseShips browses ships listed for sale at a base. Blocks until the server responds.

func (*Client) Buy

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

Buy purchases items or modules at the current station

func (*Client) BuyInsurance

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

BuyInsurance purchases ship insurance for a number of ticks.

func (*Client) BuyListedShip

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

BuyListedShip purchases a ship listed by another player.

func (*Client) BuyShip

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

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

func (*Client) CancelCommission

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

CancelCommission cancels a pending or in-progress ship commission.

func (*Client) CancelOrder

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

CancelOrder cancels an active exchange order and returns escrow.

func (*Client) CancelShipListing

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

CancelShipListing removes a ship listing from the exchange.

func (*Client) CaptainsLogAdd

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

CaptainsLogAdd adds an entry to your captain's log.

func (*Client) CaptainsLogDelete added in v0.2.0

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

CaptainsLogDelete deletes a captain's-log entry by index. The server ack-terminates this action (not flagged x-is-mutation), so it uses the query terminator.

func (*Client) CaptainsLogGet

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

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

func (*Client) CaptainsLogList

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

CaptainsLogList lists all entries in your captain's log.

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context, catalogType string, page, pageSize int) error

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

func (*Client) Chat

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

Chat sends a chat message.

func (*Client) Citizenship added in v0.2.0

func (c *Client) Citizenship(ctx context.Context, action, empireID string) error

Citizenship performs a citizenship sub-action (e.g. petition, renounce, grant, list). empireID is optional depending on the action.

func (*Client) Claim

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

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

func (*Client) ClaimInsurance

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

ClaimInsurance views your active insurance policies.

func (*Client) ClearLastError

func (c *Client) ClearLastError()

ClearLastError clears the stored error

func (*Client) ClearRawJSON added in v0.2.0

func (c *Client) ClearRawJSON(key string)

ClearRawJSON drops the stored payload for key (no-op if absent). Callers use this to invalidate a stale slot before issuing a new request, so if the current response never lands (dropped, lost to a racing waiter, etc.) downstream consumers see nothing rather than the previous command's data.

func (*Client) Cloak

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

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

func (*Client) Close

func (c *Client) Close() error

Close closes the connection and cleans up all resources

func (*Client) CommissionQuote

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

CommissionQuote gets a cost estimate for commissioning a ship.

func (*Client) CommissionShip

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

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

func (*Client) CommissionStatus

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

CommissionStatus checks the status of ship commissions.

func (*Client) CompleteMission

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

CompleteMission completes a mission and claims rewards.

func (*Client) CompletedMissions added in v0.2.0

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

CompletedMissions lists the player's completed missions.

func (*Client) Connect

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

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

func (*Client) Craft

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

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

func (*Client) CraftBulk added in v0.2.0

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

CraftBulk queues many craft (or recycle) jobs in a single request. Each entry is a job object of the same shape the server documents for craft's "jobs" param: {recipe_id, quantity, facility_id?, preset?, deliver_to?}. Top-level recipe_id/quantity are ignored in bulk mode; each job is queued independently (partial success), so a single bad entry does not fail the others. Bulk mode is not compatible with dry_run. The server caps a request at MaxCraftBulkJobs.

func (*Client) CraftDryRun added in v0.2.0

func (c *Client) CraftDryRun(ctx context.Context, recipeID string, quantity int, facilityID string) (*serverapi.CraftDryRunResponse, error)

CraftDryRun quotes a craft job without queuing it: the server's authoritative fee (credits_total), duration, and have_inputs/have_credits preflight for crafting quantity output units of recipeID. facilityID may be "" to let the server auto-route to the local facility/workshop (the hand-craft path — Task 0 findings 2026-07-10 confirmed hand/workshop dry-run IS supported live and its facility_id in the response is the auto-resolved workshop instance id), or an explicit facility instance id (crafting requires being docked at that facility's station — a remote facility_id errors no_facility). Bulk mode is not compatible with dry_run (CraftBulk's doc comment), so this always submits a single-job payload, mirroring CraftWithOptions/CraftBulk's Submit/terminator pattern.

func (*Client) CraftItems added in v0.2.0

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

CraftItems queues crafting jobs for everything currently craftable from the station storage at the docked base. v0.389: crafting reads inputs from and delivers output to station storage, and runs asynchronously over ticks — so this deposits any cargo into storage, queries craftable recipes, and queues each one exactly once. It does NOT withdraw to cargo and does NOT re-issue a craft to "make progress" (that would double-spend). Output lands in storage over the following ticks; consumers can observe it via OnCraftingUpdate or `craft action=queue`. Returns the total output quantity queued.

func (*Client) CraftWithOptions added in v0.2.0

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

CraftWithOptions queues a crafting job. quantity is the number of output items wanted (server rounds up to whole runs). deliverTo may be "" (server default: station storage) or "faction" (faction storage; requires a Faction Workshop facility and manage-treasury permission, pulling inputs from faction storage). Crafting is async: the server replies with a single ok job frame and delivers output later via crafting_update; this method returns once the job is queued.

func (*Client) CraftWithQuantity

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

CraftWithQuantity queues a crafting job for the given recipe. quantity is the number of output items wanted; the server rounds it up to whole production runs. Inputs are escrowed from station storage and output is delivered there.

func (*Client) CreateBulkSellOrder

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

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

Example:

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

func (*Client) CreateBuyOrder

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

CreateBuyOrder places a buy offer on the station exchange.

func (*Client) CreateFaction

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

CreateFaction creates a new faction.

func (*Client) CreateNote

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

CreateNote creates a new note document.

func (*Client) CreateSellOrder

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

CreateSellOrder lists items for sale on the station exchange.

func (*Client) DeclineMission

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

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

func (*Client) DeleteNote added in v0.2.0

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

DeleteNote deletes a saved note by ID. The server ack-terminates this action (not flagged x-is-mutation), so it uses the query terminator.

func (*Client) DeployDrone added in v0.2.0

func (c *Client) DeployDrone(ctx context.Context, droneID string, all bool) error

DeployDrone launches a drone from the bay into the current location, or every in-bay drone when all is true (server-side bandwidth check still applies — drones that would exceed remaining bandwidth are silently skipped). Mirrors the RecallDrone signature; pass droneID="" with all=true for the bulk path.

func (*Client) DepositAllItems

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

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

Returns an error if:

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

Example:

err := client.DepositAllItems(ctx)

func (*Client) DepositItems

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

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

Parameters:

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

Returns an error if:

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

Example:

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

func (*Client) DepositItemsPayload added in v0.2.0

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

DepositItemsPayload sends a deposit_items command with the caller-supplied payload. See WithdrawItemsPayload for the source/target semantics. Skips the cargo-availability precheck that DepositItems does.

func (*Client) Disconnect

func (c *Client) Disconnect() error

Disconnect closes the WebSocket connection

func (*Client) DistressSignal added in v0.2.0

func (c *Client) DistressSignal(ctx context.Context, distressType string) error

DistressSignal broadcasts a distress signal to nearby players. v0.240: accepts optional distress_type ("fuel", "repair", "combat").

func (*Client) Dock

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

Dock docks at a station in the current system.

Terminates on either the legacy TypeDocked push event (no command field) or a TypeActionResult whose top-level command is "dock" — newer servers only emit the latter on completion.

func (*Client) EnsureConnected

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

EnsureConnected ensures the client is connected, reconnecting if necessary

func (*Client) Espionage added in v0.2.0

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

Espionage sends a spy to gather intelligence on the station the player is currently docked at, using the faction's Espionage HQ facility. Requires faction membership, an active Espionage HQ built anywhere by the faction, and being docked at the target station.

The operation blocks the player for ~90s server-side and no other action can be taken until it resolves, so it awaits on SleepEspionageMaxWait rather than the ordinary mutation timeout.

func (*Client) EstimatePurchase

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

EstimatePurchase previews what buying would cost without executing.

func (*Client) Facility

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

Facility manages facilities at stations. Both query-shaped sub-actions (list, types, upgrades, help, faction_list, etc.) and mutation-shaped sub-actions (build, toggle, personal_build, transfer, etc.) flow through here. Sync queries return type=ok inline; async mutations follow the pending ok → action_result/action_error pattern.

func (*Client) FactionAcceptAlly added in v0.2.0

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

FactionAcceptAlly accepts a pending alliance proposal, ratifying it on both sides.

func (*Client) FactionAcceptInvite added in v0.2.0

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

FactionAcceptInvite accepts a pending invitation to join a faction.

func (*Client) FactionAcceptPeace

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

FactionAcceptPeace accepts a peace proposal.

func (*Client) FactionCancelMission

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

FactionCancelMission cancels a posted faction mission and refunds escrowed rewards.

func (*Client) FactionCreateBuyOrder

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

FactionCreateBuyOrder creates a buy order on behalf of your faction.

func (*Client) FactionCreateRole

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

FactionCreateRole creates a custom faction role.

func (*Client) FactionCreateSellOrder

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

FactionCreateSellOrder creates a sell order on behalf of your faction.

func (*Client) FactionDeclareWar

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

FactionDeclareWar declares war on another faction.

func (*Client) FactionDeclineInvite

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

FactionDeclineInvite declines a faction invitation.

func (*Client) FactionDeleteRole

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

FactionDeleteRole deletes a custom faction role.

func (*Client) FactionDeleteRoom

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

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

func (*Client) FactionDepositCredits

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

FactionDepositCredits transfers credits from your wallet to faction storage.

func (*Client) FactionDepositItems

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

FactionDepositItems moves items from your cargo to faction storage.

func (*Client) FactionDepositItemsPayload added in v0.2.0

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

FactionDepositItemsPayload sends a faction_deposit_items command with the caller-supplied payload. Allows v2 source/target selectors (see WithdrawItemsPayload for semantics).

func (*Client) FactionEdit

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

FactionEdit updates faction description, charter, and colors.

func (*Client) FactionEditRole

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

FactionEditRole edits a custom faction role.

func (*Client) FactionGetInvites

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

FactionGetInvites views pending faction invitations.

func (*Client) FactionGift

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

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

func (*Client) FactionInfo

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

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

func (*Client) FactionIntelStatus

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

FactionIntelStatus views faction intel coverage statistics.

func (*Client) FactionInvite

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

FactionInvite invites a player to your faction.

func (*Client) FactionKick

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

FactionKick kicks a player from your faction.

func (*Client) FactionList

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

FactionList lists all factions.

func (*Client) FactionListMissions

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

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

func (*Client) FactionPostMission

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

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

func (*Client) FactionPromote

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

FactionPromote promotes or demotes a faction member.

func (*Client) FactionProposeAlly added in v0.2.0

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

FactionProposeAlly proposes a mutual alliance with another faction. The target's diplomacy-capable members must call FactionAcceptAlly to ratify.

func (*Client) FactionProposePeace

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

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

func (*Client) FactionQueryIntel

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

FactionQueryIntel queries your faction's intel database.

func (*Client) FactionQueryTradeIntel

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

FactionQueryTradeIntel searches your faction's market price database.

func (*Client) FactionRemoveAlly added in v0.2.0

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

FactionRemoveAlly dissolves an alliance with another faction. Idempotent: succeeds even if no alliance existed.

func (*Client) FactionRemoveEnemy added in v0.2.0

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

FactionRemoveEnemy removes a faction from this faction's enemy list.

func (*Client) FactionRooms

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

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

func (*Client) FactionSetEnemy

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

FactionSetEnemy marks another faction as enemy.

func (*Client) FactionSubmitIntel

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

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

func (*Client) FactionSubmitTradeIntel

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

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

func (*Client) FactionTradeIntelStatus

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

FactionTradeIntelStatus views faction trade intelligence coverage statistics.

func (*Client) FactionVisitRoom

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

FactionVisitRoom visits a room and reads its description.

func (*Client) FactionWithdrawCredits

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

FactionWithdrawCredits transfers credits from faction storage to your wallet.

func (*Client) FactionWithdrawInvite added in v0.2.0

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

FactionWithdrawInvite withdraws an invitation previously sent to a player.

func (*Client) FactionWithdrawItems

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

FactionWithdrawItems moves items from faction storage to your cargo.

func (*Client) FactionWithdrawItemsPayload added in v0.2.0

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

FactionWithdrawItemsPayload sends a faction_withdraw_items command with the caller-supplied payload. Allows v2 source/target selectors.

func (*Client) FactionWriteRoom

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

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

func (*Client) FindRoute

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

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

func (*Client) Fleet added in v0.2.0

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

Fleet manages player fleet operations (create, invite, accept, decline, leave, kick, disband, status). v0.240: new command.

func (*Client) ForumCreateThread

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

ForumCreateThread creates a new forum thread.

func (*Client) ForumDeleteReply

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

ForumDeleteReply deletes a forum reply.

func (*Client) ForumDeleteThread

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

ForumDeleteThread deletes a forum thread.

func (*Client) ForumGetThread

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

ForumGetThread gets a forum thread and its replies.

func (*Client) ForumList

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

ForumList lists forum threads.

func (*Client) ForumReply

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

ForumReply replies to a forum thread.

func (*Client) ForumUpvote

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

ForumUpvote upvotes a thread or reply.

func (*Client) GetActionLog added in v0.2.0

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

GetActionLog fetches recent server-side action log entries. The payload accepts server-supported filters (category, event_type, faction_id, page, page_size); pass nil for defaults.

func (*Client) GetActiveMissions

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

GetActiveMissions views your active missions and progress.

func (*Client) GetBase

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

GetBase gets docked base details.

func (*Client) GetBattleStatus

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

GetBattleStatus queries the current battle state (free query, no tick cost). Blocks until the server responds.

func (*Client) GetCargo

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

GetCargo gets the ship's cargo contents.

func (*Client) GetChatHistory

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

GetChatHistory gets chat message history.

func (*Client) GetCommands

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

GetCommands gets a structured list of all commands.

func (*Client) GetDrone added in v0.2.0

func (c *Client) GetDrone(ctx context.Context, droneID string) error

GetDrone fetches details for a single drone.

func (*Client) GetDrones

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

GetDrones fetches the drone bay summary and roster.

func (*Client) GetEmpireInfo added in v0.2.0

func (c *Client) GetEmpireInfo(ctx context.Context, empireID string) error

GetEmpireInfo fetches empire information. empireID is optional; when empty the server returns all empires.

func (*Client) GetGuide

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

GetGuide gets a detailed playstyle progression guide.

func (*Client) GetInsuranceQuote

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

GetInsuranceQuote gets a risk-based insurance quote for the current ship. It blocks until the quote response is received so callers (e.g. the play_as REPL) can read the stored payload immediately — get_insurance_quote returns type=ok with a "quote" key, like get_nearby.

func (*Client) GetLastError

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

GetLastError returns the most recent error response

func (*Client) GetListings

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

GetListings requests market listings for the current station. Blocks until the server responds.

func (*Client) GetMap

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

GetMap requests all systems with coordinates and connections. Map data is cached for MapCacheTTL since it changes infrequently. Pass force=true to bypass the cache and always fetch fresh data.

func (*Client) GetMarketListings

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

GetMarketListings returns the most recently fetched market listings

func (*Client) GetMissions

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

GetMissions gets available missions at the current base.

func (*Client) GetNearby

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

GetNearby gets other players at the current POI.

func (*Client) GetNotes

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

GetNotes lists all your note documents.

func (*Client) GetNotifications added in v0.2.0

func (c *Client) GetNotifications(_ context.Context) error

GetNotifications is a no-op for the WebSocket client.

The WS server rejects get_notifications ("not needed over WebSocket") because tick, chat, trade, combat, and other notifications are delivered as push events in real time (see handleResponse / TypeTick). Callers that poll this method for tick freshness (e.g., GameClock.syncLoop, agent runner) can rely on the pushed state instead; we return nil so shared code paths keep working without logging spurious errors.

func (*Client) GetPOI

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

GetPOI requests information about the current POI. Blocks until the server responds.

func (*Client) GetRawJSON

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

GetRawJSON retrieves the raw JSON payload for a given key

func (*Client) GetRecipes

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

GetRecipes gets available crafting recipes.

func (*Client) GetShip

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

GetShip gets detailed ship information.

func (*Client) GetShipListings

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

GetShipListings returns the most recently fetched ship listings

func (*Client) GetShips

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

GetShips requests ship listings from the current station. Blocks until the server responds.

func (*Client) GetSkills

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

GetSkills gets your skill progress.

func (*Client) GetState

func (c *Client) GetState() *State

GetState returns the current game state

func (*Client) GetStatus

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

GetStatus requests player status. Blocks until the server responds.

func (*Client) GetSystem

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

GetSystem requests information about the current system. Blocks until the server responds.

func (*Client) GetSystemAgents added in v0.2.0

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

GetSystemAgents gets all uncloaked online players in the current system (system-wide version of GetNearby).

func (*Client) GetTaxEstimate added in v0.2.0

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

GetTaxEstimate fetches the player's current tax assessment estimate.

func (*Client) GetTrades

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

GetTrades views pending trade offers.

func (*Client) GetVersion

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

GetVersion gets game version and release notes.

func (*Client) GetWrecks

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

GetWrecks lists all wrecks at the current POI.

func (*Client) Help

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

Help gets help for commands.

func (*Client) InstallMod

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

InstallMod installs a module on the ship.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is connected

func (*Client) Jettison

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

Jettison jettisons items from cargo into space.

func (*Client) JoinFaction

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

JoinFaction joins a faction via invitation.

func (*Client) Jump

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

Jump jumps to another system Jump jumps to another system. It blocks until the ship arrives in the new system or an error occurs. The returned JumpResult contains the destination system info.

func (*Client) LeaveFaction

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

LeaveFaction leaves your current faction.

func (*Client) ListPassengers added in v0.2.0

func (c *Client) ListPassengers(ctx context.Context) (*serverapi.ListPassengersResponse, error)

ListPassengers returns the passengers currently aboard the ship — each with its destination station and system, accommodation class, fare due on delivery, and fare-guarantee countdown — plus the ship's total passenger berths by class. This is a query (no tick cost). It is the basis for delivering already-boarded passengers across worker restarts: the ship's manifest is server-side, so a fresh worker can recover and finish a delivery instead of deadlocking on full berths.

func (*Client) ListShipForSale

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

ListShipForSale lists a stored ship for sale on the exchange.

func (*Client) ListShips

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

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

func (*Client) ListStationPassengers added in v0.2.0

func (c *Client) ListStationPassengers(ctx context.Context, station string) (*serverapi.ListStationPassengersResponse, error)

ListStationPassengers returns the passengers waiting for transport at station (its id or name). An empty station queries the currently docked station. This is a query (no tick cost).

func (*Client) LoadDrone added in v0.2.0

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

LoadDrone loads an item from cargo into the drone bay as a drone.

func (*Client) LoadPassenger added in v0.2.0

func (c *Client) LoadPassenger(ctx context.Context, destination string) (*serverapi.LoadPassengerResponse, error)

LoadPassenger boards every waiting passenger bound for the given destination station that fits the ship's berths, and returns who actually boarded plus the booked total fare. Fewer may board than were waiting (see LoadPassengerResponse).

func (*Client) Login

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

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

func (*Client) LootWreck

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

LootWreck loots items from a wreck.

func (*Client) Mine

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

Mine mines resources at the current location.

Wraps the execMutation error through maybeGoalReached so a cargo_full server error becomes a *GoalReachedError sentinel that the play_as loop recognises as a successful exit condition. Intermediate mining_yield push events have no "command" field so matchCommand("mine") correctly skips them.

func (*Client) ModifyOrder

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

ModifyOrder changes the price on an existing exchange order.

func (*Client) PassengerObserver added in v0.2.0

func (c *Client) PassengerObserver() PassengerObserver

PassengerObserver returns the currently registered observer (nil if none). Exposed for tests and runtime introspection to verify wiring without reaching into unexported fields.

func (*Client) Petition added in v0.2.0

func (c *Client) Petition(ctx context.Context, empireID, message string) error

Petition submits a citizenship petition message to an empire. The server ack-terminates this action (not flagged x-is-mutation), so it uses the query terminator.

func (*Client) PlayerObserver added in v0.2.0

func (c *Client) PlayerObserver() PlayerObserver

PlayerObserver returns the currently registered observer (nil if none). Exposed for external callers (notably tests and runtime introspection) to verify wiring without reaching into unexported fields.

func (*Client) QueryCraftableFromComponents added in v0.2.0

func (c *Client) QueryCraftableFromComponents(ctx context.Context, components []Component, config *CraftingConfig) (*CraftQueryResult, error)

QueryCraftableFromComponents queries the crafting MCP server to find what can be crafted from an explicit list of components and the player's current skills.

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) RawCommand added in v0.2.0

func (c *Client) RawCommand(ctx context.Context, command string, args map[string]any) error

RawCommand sends an arbitrary command to the server and blocks until its terminal response. terminateOnActionOrOK resolves immediately on a synchronous (non-pending) ok — the shape queries return — but waits through a pending:true ack for the real action_result terminal that deferred mutations deliver on the next tick. Blocking ensures the terminal payload has been received and cached by storeRawJSON before the caller reads it back: interactive callers like play_as look the response up by command name immediately after this returns, so a fire-and-forget send (or an ack-only wait, for a deferred mutation) would race and show nothing or the bare "pending" frame instead of the real result.

func (*Client) ReadNote

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

ReadNote reads a note document's contents.

func (*Client) Ready

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

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

func (*Client) RecallDrone added in v0.2.0

func (c *Client) RecallDrone(ctx context.Context, droneID string, all bool) error

RecallDrone recalls a deployed drone (or all drones when all is true).

func (*Client) Reconnect

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

Reconnect disconnects and reconnects to the server

func (*Client) Recycle added in v0.2.0

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

Recycle queues a recycling job: it consumes the recipe's outputs and returns a lossy fraction of its inputs over subsequent ticks. quantity is the number of output items to feed in (rounded up to whole recycling runs).

func (*Client) RecycleWithOptions added in v0.2.0

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

RecycleWithOptions queues a recycling job with an optional delivery target. deliverTo may be "" (server default: station storage) or "faction" (requires manage-treasury permission). Like craft, recycle is async-queued: the server replies with a single ok job frame and delivers reclaimed inputs later via crafting_update.

func (*Client) RefitShip added in v0.2.0

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

RefitShip refits the active ship to its latest class specifications.

func (*Client) Refuel

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

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

Wraps the Submit error through maybeGoalReached so a tank_full server error becomes a *GoalReachedError sentinel that the play_as loop recognizes as a successful exit condition.

func (*Client) RefuelShip added in v0.2.0

func (c *Client) RefuelShip(ctx context.Context, target string, quantity int) error

RefuelShip transfers fuel from this ship to target's ship (ship-to-ship, needs a refuel_rig fitted). quantity <= 0 lets the server pick its default.

func (*Client) Register

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

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

func (*Client) ReleaseTow

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

ReleaseTow releases a towed wreck at the current location.

func (*Client) Reload

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

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

func (*Client) Repair

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

Repair repairs the ship's hull. At station uses credits; in space uses repair kits. v0.240: optional params for item_id, quantity, and target (remote repair).

Wraps the Submit error through maybeGoalReached so a no_damage server error becomes a *GoalReachedError.

func (*Client) RepairWith added in v0.2.0

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

RepairWith repairs using specific options (repair kits, remote target, etc.).

func (*Client) RequestReconnect added in v0.2.0

func (c *Client) RequestReconnect() bool

RequestReconnect wakes the auto-reconnect handler to start a fresh reconnection burst if the client is disconnected and the handler has gone dormant after exhausting an earlier burst. It is a no-op (returning false) when connected, when a burst is already running, or when no *ReconnectingHandler is installed. Intended to be called from an interactive loop on user input.

func (*Client) SalvageWreck

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

SalvageWreck salvages a wreck for raw materials.

func (*Client) Scan

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

Scan scans the current area

func (*Client) ScanTarget

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

ScanTarget scans a specific target player. Note: the server command type is "scan" (same as Scan), not "scan_target".

func (*Client) ScrapShip added in v0.2.0

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

ScrapShip scraps a ship, moving its cargo and modules to storage.

func (*Client) ScrapWreck

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

ScrapWreck scraps a towed wreck for salvage materials.

func (*Client) SearchChangelog

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

SearchChangelog searches release notes and version history.

func (*Client) SearchSystems

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

SearchSystems searches for systems by name.

func (*Client) SelfDestruct

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

SelfDestruct destroys your own ship.

func (*Client) Sell

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

Sell sells items from cargo at the current station

func (*Client) SellAll

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

SellAll sells all cargo items at the current station

func (*Client) SellAllBulk

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

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

Parameters:

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

Returns error if not docked or if API call fails.

func (*Client) SellShip

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

SellShip sells a stored ship at the current station.

func (*Client) SellWreck

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

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

func (*Client) Send

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

Send is a thin public wrapper around the private send primitive. It exists only for the small set of callers that legitimately need fire-and-forget without response correlation:

  • pkg/observe/session.go (generic relay: responses are dispatched to a WS client by message type, not correlated to a specific command — incompatible with Submit's exclusive subscription).
  • cmd/tools/server-cmd and cmd/debug/play-simple (debug REPLs that manage their own response handlers and intentionally collect zero-or-many unsolicited responses).

All other code MUST use Submit / subscribePush. Direct Send loses response correlation, the per-action lock, and the in-flight cap.

func (*Client) SendGift

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

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

func (*Client) SetAnonymous

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

SetAnonymous sets anonymous mode.

func (*Client) SetColors

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

SetColors sets your ship colors.

func (*Client) SetDebugLogging added in v0.2.0

func (c *Client) SetDebugLogging(enabled bool)

SetDebugLogging controls whether the game client logs WebSocket messages. When disabled, the debug logger output is discarded; when enabled, it is restored to the writer the logger was constructed with. Safe to call at runtime to toggle debug logging on and off.

func (*Client) SetDebugPayloadMaxLen added in v0.2.0

func (c *Client) SetDebugPayloadMaxLen(n int)

SetDebugPayloadMaxLen configures how much of each received response's payload is emitted on the "Response Payload:" debug line. Pass 0 to disable truncation (log the full payload regardless of length). Negative values are treated as 0. The default is 200.

func (*Client) SetDroneName added in v0.2.0

func (c *Client) SetDroneName(ctx context.Context, droneID, name string) error

SetDroneName assigns a display name to a drone you own (max 32 chars; same character rules as ship names). Pass an empty name to clear. Not a mutation — no tick cost.

func (*Client) SetHandler

func (c *Client) SetHandler(handler MessageHandler)

SetHandler sets the message handler

func (*Client) SetHomeBase

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

SetHomeBase sets the home base for respawning.

func (*Client) SetOnChatMessage added in v0.2.0

func (c *Client) SetOnChatMessage(fn func(msg serverapi.ChatMessage))

SetOnChatMessage registers a callback that fires when a real-time chat push event is received from the server. This allows packages like mbox to capture chat messages without polling.

func (*Client) SetOnCraftingUpdate added in v0.2.0

func (c *Client) SetOnCraftingUpdate(fn func(ev serverapi.CraftingUpdateEvent))

SetOnCraftingUpdate registers a callback that fires when a crafting_update push event is received (server v0.389.0+). This lets consumers track async crafting job progress and storage deposits without polling.

func (*Client) SetOnStorageUpdate added in v0.2.0

func (c *Client) SetOnStorageUpdate(fn func(resp StorageUpdateEvent))

SetOnStorageUpdate registers a callback that fires when a view_storage response is received. This allows automatic storage snapshot recording without modifying individual agent code.

func (*Client) SetPassengerObserver added in v0.2.0

func (c *Client) SetPassengerObserver(fn PassengerObserver)

SetPassengerObserver registers a callback that fires when handleResponse parses a payload containing passenger records. Used by consumers (play_as REPL, agent runners) to persist the passenger catalog into a knowledge base.

func (*Client) SetPlayerObserver added in v0.2.0

func (c *Client) SetPlayerObserver(fn PlayerObserver)

SetPlayerObserver registers a callback that fires when handleResponse parses a payload containing player records. Used by consumers (play_as REPL, agent runners) to persist sightings into a knowledge base.

func (*Client) SetPlayerStatus

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

SetPlayerStatus sets your status message and clan tag.

func (*Client) SetQuietEventTypes added in v0.2.0

func (c *Client) SetQuietEventTypes(types []string)

SetQuietEventTypes replaces the set of server response types whose receive-side debug logging is suppressed. Pass nil or an empty slice to clear. Type names are matched verbatim against protocol.Response.Type (e.g. "mining_yield"). State updates and downstream handlers still run normally; only the "=== Game Client Receive Debug ===" block and the matching "Stored raw JSON for ..." line are silenced.

func (*Client) SetTickProvider added in v0.2.0

func (c *Client) SetTickProvider(fn func() int64)

SetTickProvider installs a function returning the authoritative current game tick. When set, Travel/Jump use it for StartTick instead of the possibly-stale state.CurrentTick. Pass nil to clear.

func (*Client) SetXPCallback added in v0.2.0

func (c *Client) SetXPCallback(fn XPCallbackFunc)

SetXPCallback installs an XP observation callback. Passing nil disables callbacks. Safe to call before or after Connect.

func (*Client) Shipping added in v0.2.0

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

Shipping sends a /shipping action with the given payload (the action is injected). The reply is cached under "shipping_<action>" (storeRawJSON); read it with GetRawJSON and unmarshal into the matching serverapi struct.

func (*Client) ShippingAccept added in v0.2.0

func (c *Client) ShippingAccept(ctx context.Context, shipmentID, carrier string) error

ShippingAccept accepts a contract as the given carrier (player|faction). The package lands in the carrier's storage at origin. Reply: shipping_accept.

func (*Client) ShippingCancel added in v0.2.0

func (c *Client) ShippingCancel(ctx context.Context, shipmentID string) error

ShippingCancel cancels a contract (breach-avoidance escape hatch). Reply: shipping_cancel.

func (*Client) ShippingDeliver added in v0.2.0

func (c *Client) ShippingDeliver(ctx context.Context, shipmentID string) error

ShippingDeliver settles a delivered contract. Reply: shipping_deliver.

func (*Client) ShippingGet added in v0.2.0

func (c *Client) ShippingGet(ctx context.Context, shipmentID string) error

ShippingGet fetches one contract by id. Reply: shipping_get.

func (*Client) ShippingList added in v0.2.0

func (c *Client) ShippingList(ctx context.Context, sort string) error

ShippingList fetches the current station's freight board (docked-only). sort ∈ {reward,distance,age} (empty = server default reward). Reply: shipping_list.

func (*Client) ShippingPayDebt added in v0.2.0

func (c *Client) ShippingPayDebt(ctx context.Context, amount int64) error

ShippingPayDebt pays freight debt (amount ≤ 0 pays the full balance). Reply: shipping_pay_debt.

func (*Client) ShippingProfile added in v0.2.0

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

ShippingProfile fetches this actor's carrier standing, capacity, progression and debts. Reply: shipping_profile.

func (*Client) ShippingReturn added in v0.2.0

func (c *Client) ShippingReturn(ctx context.Context, shipmentID string) error

ShippingReturn returns a contract to its origin (breach-avoidance escape hatch). Reply: shipping_return.

func (*Client) ShippingTrack added in v0.2.0

func (c *Client) ShippingTrack(ctx context.Context, shipmentID string, limit int) error

ShippingTrack fetches a contract plus its beacon custody events (limit ≤ 200; 0 = server default). Reply: shipping_track.

func (*Client) Submit added in v0.2.0

func (c *Client) Submit(ctx context.Context, msg protocol.Message, opts ...SubmitOption) (*RequestHandle, error)

Submit sends msg with a fresh request_id and returns a handle for retrieving the ack and terminal response. Blocks while acquiring the in-flight slot and (for mutations) the per-action lock.

Concurrency: queries (WithAckOnly) acquire only the in-flight slot. Mutations acquire in-flight then per-action lock; release in reverse order on resolution.

On send-failure, Submit returns (h, nil) — never (nil, err). The underlying send error is delivered via h.Result() as a *ServerError with Code="send_failed". Callers MUST call h.Result() to observe success or failure; checking the Submit return error alone is not sufficient.

func (*Client) SurveySystem

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

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

func (*Client) SwitchShip

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

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

func (*Client) TowWreck

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

TowWreck attaches a tow line to a wreck for hauling.

func (*Client) TradeAccept

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

TradeAccept accepts a trade offer.

func (*Client) TradeCancel

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

TradeCancel cancels your trade offer.

func (*Client) TradeDecline

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

TradeDecline declines a trade offer.

func (*Client) TradeOffer

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

TradeOffer offers a trade to another player.

func (*Client) Travel

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

func (*Client) Undock

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

Undock undocks from the current station.

Terminates on either the legacy TypeUndocked push event (no command field) or a TypeActionResult whose top-level command is "undock" — newer servers only emit the latter on completion.

func (*Client) UninstallMod

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

UninstallMod uninstalls a module from the ship.

func (*Client) UnloadDrone added in v0.2.0

func (c *Client) UnloadDrone(ctx context.Context, droneID string) error

UnloadDrone unloads a drone from the bay back into cargo.

func (*Client) UnloadPassenger added in v0.2.0

func (c *Client) UnloadPassenger(ctx context.Context, nameOrID string) error

UnloadPassenger puts a passenger off at the current station (it must be docked). If the station is the passenger's destination they are delivered and pay; other- wise they are stranded here for no fare and a small reputation hit. Pass "all" to unload every aboard passenger at once. Used as the deadlock safety valve: when an aboard passenger's destination is unroutable, stranding frees the berths rather than holding them hostage forever.

func (*Client) UploadDroneScript added in v0.2.0

func (c *Client) UploadDroneScript(ctx context.Context, droneID, script string) error

UploadDroneScript uploads an automation script to a deployed drone.

func (*Client) Uptime added in v0.2.0

func (c *Client) Uptime() time.Duration

Uptime returns how long the current connection has been alive. Zero if the client has never connected. Used by ReconnectingHandler to detect the session-contention pattern (rapid back-to-back reconnects).

func (*Client) UseItem

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

UseItem uses a consumable item from cargo.

func (*Client) ViewFactionStorage

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

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

func (*Client) ViewFactionStorageAt added in v0.2.0

func (c *Client) ViewFactionStorageAt(ctx context.Context, stationID string) error

ViewFactionStorageAt views your faction's shared storage at a specific station. As of v0.299.0, you can query remotely with station_id as long as you're a faction member.

func (*Client) ViewInsurance added in v0.2.0

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

ViewInsurance lists the player's active insurance policies.

func (*Client) ViewMarket

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

ViewMarket views the order book at the current station. The payload accepts server-supported filters (item_id, category, etc.); pass nil to fetch the full market.

func (*Client) ViewOrders

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

ViewOrders views your own orders at the current station.

func (*Client) ViewStorage

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

ViewStorage views your storage at the current station.

func (*Client) ViewStorageAt added in v0.2.0

func (c *Client) ViewStorageAt(ctx context.Context, stationID string) error

ViewStorageAt views your storage at a specific station (without needing to be docked).

func (*Client) WaitForReady

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

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

func (*Client) WithdrawItems

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

WithdrawItems moves items from station storage to cargo.

func (*Client) WithdrawItemsPayload added in v0.2.0

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

WithdrawItemsPayload sends a withdraw_items command with the caller-supplied payload. Use this when you need the v2 source/target selectors:

source: "cargo" (default), "storage" (personal→faction), "faction" (faction→personal)
target: "self" (default), "faction", "faction:TAG", or a player name (gift)

Skips the cargo-availability precheck that WithdrawItems does, since non-default source/target moves don't read from cargo.

func (*Client) WriteNote

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

WriteNote edits an existing note document.

type Component

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

Component represents a crafting component

type ConnectionClosed added in v0.2.0

type ConnectionClosed struct {
	Code   websocket.StatusCode
	Reason string
}

ConnectionClosed signals that the WebSocket received a close frame while a request was outstanding, and the close-code policy (see close_codes.go) was fail-fast rather than replay. Callers can inspect Code/Reason via errors.As.

func (*ConnectionClosed) Error added in v0.2.0

func (e *ConnectionClosed) Error() string

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

type ConnectionLost struct {
	Cause error
}

ConnectionLost signals that the WebSocket disconnected and the client failed to re-establish a working session (network down, auth failed during reconnect, etc.). The Cause is the last reconnect-attempt error.

func (*ConnectionLost) Error added in v0.2.0

func (e *ConnectionLost) Error() string

func (*ConnectionLost) Unwrap added in v0.2.0

func (e *ConnectionLost) Unwrap() error

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

	// Navigation
	Undock(ctx context.Context) error
	Dock(ctx context.Context) error
	Travel(ctx context.Context, targetPOI string) (*TravelResult, error)
	Jump(ctx context.Context, targetSystem string) (*JumpResult, error)

	// Mining & Scanning
	Mine(ctx context.Context) error
	Scan(ctx context.Context) error
	ScanTarget(ctx context.Context, targetID string) error

	// Combat
	Attack(ctx context.Context, targetID string) error
	Cloak(ctx context.Context, enable bool) error
	Battle(ctx context.Context, action string, payload map[string]any) error
	GetBattleStatus(ctx context.Context) error
	Reload(ctx context.Context, weaponInstanceID, ammoItemID string) error

	// Commerce
	Sell(ctx context.Context, itemID string, quantity float64) error
	SellAllBulk(ctx context.Context, reservedItems []string) error
	Buy(ctx context.Context, itemID string, quantity float64) error
	GetListings(ctx context.Context) error
	GetTrades(ctx context.Context) error
	EstimatePurchase(ctx context.Context, itemID string, quantity int) error
	CancelOrder(ctx context.Context, payload map[string]any) error
	ModifyOrder(ctx context.Context, payload map[string]any) error
	TradeOffer(ctx context.Context, targetID string, payload map[string]any) error
	TradeAccept(ctx context.Context, tradeID string) error
	TradeCancel(ctx context.Context, tradeID string) error
	TradeDecline(ctx context.Context, tradeID string) error

	// Crafting
	CraftWithQuantity(ctx context.Context, recipeID string, quantity int) error
	CraftWithOptions(ctx context.Context, recipeID string, quantity int, deliverTo string) error
	CraftBulk(ctx context.Context, jobs []map[string]any) error
	CraftDryRun(ctx context.Context, recipeID string, quantity int, facilityID string) (*serverapi.CraftDryRunResponse, error)
	GetRecipes(ctx context.Context) error
	Recycle(ctx context.Context, recipeID string, quantity int) error
	RecycleWithOptions(ctx context.Context, recipeID string, quantity int, deliverTo string) error

	// Ship Maintenance
	Refuel(ctx context.Context) error
	// RefuelShip transfers fuel to another player's ship (requires a fitted
	// refuel_rig; target is the in-game username, not the on-disk alias).
	RefuelShip(ctx context.Context, target string, quantity int) error
	Repair(ctx context.Context) error
	RepairWith(ctx context.Context, payload map[string]any) error
	RefitShip(ctx context.Context) error
	InstallMod(ctx context.Context, moduleID string) error
	UninstallMod(ctx context.Context, moduleID string) error
	BuyShip(ctx context.Context, shipClass string) error
	BuyListedShip(ctx context.Context, listingID string) error
	BrowseShips(ctx context.Context, payload map[string]any) error
	BuyInsurance(ctx context.Context, ticks int) error
	ClaimInsurance(ctx context.Context) error
	ListShipForSale(ctx context.Context, shipID string, price float64) error
	CommissionQuote(ctx context.Context, shipClass string) error
	CommissionStatus(ctx context.Context, baseID string) error
	CancelCommission(ctx context.Context, commissionID string) error
	CommissionShip(ctx context.Context, shipClass string, provideMaterials bool) error

	// Cargo & Storage
	DepositItems(ctx context.Context, itemID string, quantity float64) error
	DepositItemsPayload(ctx context.Context, payload map[string]any) error
	DepositAllItems(ctx context.Context) error
	WithdrawItems(ctx context.Context, itemID string, quantity float64) error
	WithdrawItemsPayload(ctx context.Context, payload map[string]any) error
	ViewStorage(ctx context.Context) error
	ViewStorageAt(ctx context.Context, stationID string) error

	// Cargo Operations
	Jettison(ctx context.Context, itemID string, quantity float64) error

	// Wrecks
	GetWrecks(ctx context.Context) error
	LootWreck(ctx context.Context, wreckID, itemID string, quantity float64) error
	SalvageWreck(ctx context.Context, wreckID string) error
	TowWreck(ctx context.Context, wreckID string) error
	UseItem(ctx context.Context, itemID string, quantity int) error

	// Queries
	GetSystem(ctx context.Context) error
	GetStatus(ctx context.Context) error
	GetNotifications(ctx context.Context) error
	GetShip(ctx context.Context) error
	GetCargo(ctx context.Context) error
	GetSkills(ctx context.Context) error
	GetPOI(ctx context.Context) error
	GetBase(ctx context.Context) error
	GetMap(ctx context.Context, force ...bool) error
	GetNearby(ctx context.Context) error
	GetSystemAgents(ctx context.Context) error
	GetVersion(ctx context.Context) error
	GetCommands(ctx context.Context) error
	GetActiveMissions(ctx context.Context) error
	GetInsuranceQuote(ctx context.Context) error
	Help(ctx context.Context, payload map[string]any) error

	// Data collection
	FactionInfo(ctx context.Context) error
	CaptainsLogList(ctx context.Context) error
	CaptainsLogGet(ctx context.Context, index int) error
	Catalog(ctx context.Context, catalogType string, page, pageSize int) error
	SearchSystems(ctx context.Context, query string) error
	GetGuide(ctx context.Context, guide string) error

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

	// Faction
	CreateFaction(ctx context.Context, payload map[string]any) error
	JoinFaction(ctx context.Context, factionID string) error
	LeaveFaction(ctx context.Context) error
	FactionInvite(ctx context.Context, playerID string) error
	FactionKick(ctx context.Context, playerID string) error
	FactionPromote(ctx context.Context, playerID, roleID string) error
	FactionList(ctx context.Context, limit, offset int) error
	FactionEdit(ctx context.Context, payload map[string]any) error
	FactionGetInvites(ctx context.Context) error
	FactionDeclineInvite(ctx context.Context, factionID string) error
	FactionDeclareWar(ctx context.Context, targetFactionID, reason string) error
	FactionProposePeace(ctx context.Context, targetFactionID, terms string) error
	FactionAcceptPeace(ctx context.Context, targetFactionID string) error
	FactionProposeAlly(ctx context.Context, targetFactionID string) error
	FactionAcceptAlly(ctx context.Context, targetFactionID string) error
	FactionRemoveAlly(ctx context.Context, targetFactionID string) error
	FactionSetEnemy(ctx context.Context, targetFactionID string) error
	FactionDepositCredits(ctx context.Context, amount float64) error
	FactionWithdrawCredits(ctx context.Context, amount float64) error
	FactionDepositItems(ctx context.Context, itemID string, quantity int) error
	FactionDepositItemsPayload(ctx context.Context, payload map[string]any) error
	FactionWithdrawItems(ctx context.Context, itemID string, quantity int) error
	FactionWithdrawItemsPayload(ctx context.Context, payload map[string]any) error
	ViewFactionStorage(ctx context.Context) error
	ViewFactionStorageAt(ctx context.Context, stationID string) error
	FactionCreateBuyOrder(ctx context.Context, itemID string, priceEach float64, quantity int) error
	FactionCreateSellOrder(ctx context.Context, itemID string, priceEach float64, quantity int) error
	FactionCreateRole(ctx context.Context, name string, priority int, permissions map[string]any) error
	FactionEditRole(ctx context.Context, roleID string, payload map[string]any) error
	FactionDeleteRole(ctx context.Context, roleID string) error
	FactionSubmitIntel(ctx context.Context, systems []map[string]any) error
	Espionage(ctx context.Context) error
	FactionQueryIntel(ctx context.Context, payload map[string]any) error
	FactionQueryTradeIntel(ctx context.Context, payload map[string]any) error
	FactionIntelStatus(ctx context.Context) error
	FactionTradeIntelStatus(ctx context.Context) error
	FactionRooms(ctx context.Context) error
	FactionVisitRoom(ctx context.Context, roomID string) error
	FactionWriteRoom(ctx context.Context, payload map[string]any) error
	FactionDeleteRoom(ctx context.Context, roomID string) error
	FactionListMissions(ctx context.Context) error
	FactionCancelMission(ctx context.Context, templateID string) error
	FactionAcceptInvite(ctx context.Context, factionID string) error
	FactionWithdrawInvite(ctx context.Context, playerID string) error
	FactionRemoveEnemy(ctx context.Context, targetFactionID string) error

	// Empire & citizenship
	Citizenship(ctx context.Context, action, empireID string) error
	GetEmpireInfo(ctx context.Context, empireID string) error
	Petition(ctx context.Context, empireID, message string) error

	// Fleet (v0.240)
	Fleet(ctx context.Context, action string, playerID string) error

	// Distress (v0.240)
	DistressSignal(ctx context.Context, distressType string) error

	// Communication
	Chat(ctx context.Context, channel, content string, targetID string) error
	GetChatHistory(ctx context.Context, channel string, payload map[string]any) error
	SetPlayerStatus(ctx context.Context, payload map[string]any) error
	SetHomeBase(ctx context.Context, baseID string) error
	SendGift(ctx context.Context, payload map[string]any) error
	SetAnonymous(ctx context.Context, anonymous bool) error
	SetColors(ctx context.Context, primaryColor, secondaryColor string) error

	// Forum
	ForumList(ctx context.Context, page int) error
	ForumCreateThread(ctx context.Context, title, content string, category string) error
	ForumGetThread(ctx context.Context, threadID string) error
	ForumReply(ctx context.Context, threadID, content string) error
	ForumUpvote(ctx context.Context, threadID string, replyID string) error
	ForumDeleteThread(ctx context.Context, threadID string) error
	ForumDeleteReply(ctx context.Context, replyID string) error

	// Notes
	CreateNote(ctx context.Context, title, content string) error
	WriteNote(ctx context.Context, noteID, content string) error
	ReadNote(ctx context.Context, noteID string) error
	GetNotes(ctx context.Context) error

	// State
	GetState() *State
	GetMarketListings() []MarketListing
	GetRawJSON(key string) []byte

	// Ship Management
	ListShips(ctx context.Context) error
	SwitchShip(ctx context.Context, shipID string) error
	SellShip(ctx context.Context, shipID string) error

	// Drones
	GetDrone(ctx context.Context, droneID string) error
	GetDrones(ctx context.Context) error
	LoadDrone(ctx context.Context, itemID string) error
	UnloadDrone(ctx context.Context, droneID string) error
	RecallDrone(ctx context.Context, droneID string, all bool) error
	UploadDroneScript(ctx context.Context, droneID, script string) error
	DeployDrone(ctx context.Context, droneID string, all bool) error
	SetDroneName(ctx context.Context, droneID, name string) error

	// Economy & ship management
	GetTaxEstimate(ctx context.Context) error
	ViewInsurance(ctx context.Context) error
	ScrapShip(ctx context.Context, shipID string) error

	// Exchange
	CreateSellOrder(ctx context.Context, payload map[string]any) error
	CreateBuyOrder(ctx context.Context, payload map[string]any) error
	ViewMarket(ctx context.Context, payload map[string]any) error
	ViewOrders(ctx context.Context) error

	// Action Log
	GetActionLog(ctx context.Context, payload map[string]any) error

	// Missions
	GetMissions(ctx context.Context) error
	AcceptMission(ctx context.Context, missionID string) error
	CompleteMission(ctx context.Context, missionID string) error
	AbandonMission(ctx context.Context, missionID string) error
	DeclineMission(ctx context.Context, templateID string) error
	CompletedMissions(ctx context.Context) error
	DeleteNote(ctx context.Context, noteID string) error
	CaptainsLogDelete(ctx context.Context, index int) error
	AgentLogs(ctx context.Context, category, severity, message string, data map[string]any) error

	// Survey
	SurveySystem(ctx context.Context) error

	// Captain's Log
	CaptainsLogAdd(ctx context.Context, entry string) error

	// Station Facilities
	Facility(ctx context.Context, payload map[string]any) error

	// Passengers
	ListStationPassengers(ctx context.Context, station string) (*serverapi.ListStationPassengersResponse, error)
	LoadPassenger(ctx context.Context, destination string) (*serverapi.LoadPassengerResponse, error)
	ListPassengers(ctx context.Context) (*serverapi.ListPassengersResponse, error)
	UnloadPassenger(ctx context.Context, nameOrID string) error

	// Generic passthrough for commands without explicit methods.
	RawCommand(ctx context.Context, command string, args map[string]any) error

	// Shipping (freight contracts)
	Shipping(ctx context.Context, action string, payload map[string]any) error
	ShippingList(ctx context.Context, sort string) error
	ShippingGet(ctx context.Context, shipmentID string) error
	ShippingAccept(ctx context.Context, shipmentID, carrier string) error
	ShippingDeliver(ctx context.Context, shipmentID string) error
	ShippingReturn(ctx context.Context, shipmentID string) error
	ShippingCancel(ctx context.Context, shipmentID string) error
	ShippingTrack(ctx context.Context, shipmentID string, limit int) error
	ShippingProfile(ctx context.Context) error
	ShippingPayDebt(ctx context.Context, amount int64) error

	// Callbacks
	SetOnChatMessage(fn func(msg serverapi.ChatMessage))
}

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

type GameClock added in v0.2.0

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

GameClock tracks the game server's tick count. It increments locally every 10 seconds and re-synchronizes with the server every 5 minutes via get_notifications.

func NewGameClock added in v0.2.0

func NewGameClock(ctx context.Context, client GameClient, logger *log.Logger) (*GameClock, error)

NewGameClock creates a GameClock, performs an initial sync via get_notifications, and starts background goroutines to increment and periodically re-sync.

func (*GameClock) Stop added in v0.2.0

func (gc *GameClock) Stop()

Stop shuts down the background goroutines.

func (*GameClock) Tick added in v0.2.0

func (gc *GameClock) Tick() int64

Tick returns the current estimated game tick.

type GoalReachedError added in v0.2.0

type GoalReachedError struct {
	Command string // the command that reached its goal, e.g. "mine"
	Code    string // server error code, e.g. "no_cargo_space"
	Message string // server's human-readable message
}

GoalReachedError signals that a command's natural goal has been achieved (e.g. cargo hold is full after mine, fuel tank is full after refuel). It is distinct from:

  • nil (success, may be repeated)
  • a plain error (failure)

The play_as loop executor treats *GoalReachedError as "exit the innermost enclosing loop cleanly with overall success". Standalone callers treat it as success with a friendly message.

func (*GoalReachedError) Error added in v0.2.0

func (e *GoalReachedError) Error() string

type JumpResult added in v0.2.0

type JumpResult struct {
	SystemID   string // ID of the system jumped to
	SystemName string // Human-readable system name
	POI        string // POI arrived at in the new system
	Canceled   bool   // True if jump was interrupted
}

JumpResult contains the outcome of a completed Jump() call.

type MCPClient

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

MCPClient represents a client for communicating with MCP servers over stdio

func NewMCPClient

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

NewMCPClient creates a new MCP client for the specified server executable

func (*MCPClient) CallTool

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

CallTool invokes a tool on the MCP server

func (*MCPClient) Close

func (m *MCPClient) Close() error

Close closes all connections and stops the server

func (*MCPClient) Start

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

Start starts the MCP server process and establishes stdio communication

func (*MCPClient) Stop

func (m *MCPClient) Stop() error

Stop gracefully shuts down the MCP server

type MCPCraftQueryResponse

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

MCPCraftQueryResponse is the raw response from the crafting MCP server

type MCPGameClient added in v0.2.0

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

MCPGameClient implements the GameClient interface using direct HTTP calls to the game server's MCP endpoint (Streamable HTTP transport).

func NewMCPGameClient added in v0.2.0

func NewMCPGameClient(serverURL, username, password string, logger *log.Logger) *MCPGameClient

NewMCPGameClient creates a new MCP game client.

func (*MCPGameClient) AbandonMission added in v0.2.0

func (m *MCPGameClient) AbandonMission(ctx context.Context, missionID string) error

func (*MCPGameClient) AcceptMission added in v0.2.0

func (m *MCPGameClient) AcceptMission(ctx context.Context, missionID string) error

func (*MCPGameClient) AgentLogs added in v0.2.0

func (m *MCPGameClient) AgentLogs(ctx context.Context, category, severity, message string, data map[string]any) error

AgentLogs submits an agent telemetry log entry.

func (*MCPGameClient) Attack added in v0.2.0

func (m *MCPGameClient) Attack(ctx context.Context, targetID string) error

func (*MCPGameClient) Battle added in v0.2.0

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

func (*MCPGameClient) BrowseShips added in v0.2.0

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

func (*MCPGameClient) Buy added in v0.2.0

func (m *MCPGameClient) Buy(ctx context.Context, itemID string, quantity float64) error

func (*MCPGameClient) BuyInsurance added in v0.2.0

func (m *MCPGameClient) BuyInsurance(ctx context.Context, ticks int) error

func (*MCPGameClient) BuyListedShip added in v0.2.0

func (m *MCPGameClient) BuyListedShip(ctx context.Context, listingID string) error

func (*MCPGameClient) BuyShip added in v0.2.0

func (m *MCPGameClient) BuyShip(ctx context.Context, shipClass string) error

func (*MCPGameClient) CancelCommission added in v0.2.0

func (m *MCPGameClient) CancelCommission(ctx context.Context, commissionID string) error

func (*MCPGameClient) CancelOrder added in v0.2.0

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

func (*MCPGameClient) CaptainsLogAdd added in v0.2.0

func (m *MCPGameClient) CaptainsLogAdd(ctx context.Context, entry string) error

func (*MCPGameClient) CaptainsLogDelete added in v0.2.0

func (m *MCPGameClient) CaptainsLogDelete(ctx context.Context, index int) error

CaptainsLogDelete deletes a captain's-log entry by index.

func (*MCPGameClient) CaptainsLogGet added in v0.2.0

func (m *MCPGameClient) CaptainsLogGet(ctx context.Context, index int) error

func (*MCPGameClient) CaptainsLogList added in v0.2.0

func (m *MCPGameClient) CaptainsLogList(ctx context.Context) error

func (*MCPGameClient) Catalog added in v0.2.0

func (m *MCPGameClient) Catalog(ctx context.Context, catalogType string, page, pageSize int) error

func (*MCPGameClient) Chat added in v0.2.0

func (m *MCPGameClient) Chat(ctx context.Context, channel, content string, targetID string) error

func (*MCPGameClient) Citizenship added in v0.2.0

func (m *MCPGameClient) Citizenship(ctx context.Context, action, empireID string) error

Citizenship performs a citizenship sub-action.

func (*MCPGameClient) ClaimInsurance added in v0.2.0

func (m *MCPGameClient) ClaimInsurance(ctx context.Context) error

func (*MCPGameClient) Cloak added in v0.2.0

func (m *MCPGameClient) Cloak(ctx context.Context, enable bool) error

func (*MCPGameClient) Close added in v0.2.0

func (m *MCPGameClient) Close() error

Close stops the background poller and cleans up.

func (*MCPGameClient) CommissionQuote added in v0.2.0

func (m *MCPGameClient) CommissionQuote(ctx context.Context, shipClass string) error

func (*MCPGameClient) CommissionShip added in v0.2.0

func (m *MCPGameClient) CommissionShip(ctx context.Context, shipClass string, provideMaterials bool) error

func (*MCPGameClient) CommissionStatus added in v0.2.0

func (m *MCPGameClient) CommissionStatus(ctx context.Context, baseID string) error

func (*MCPGameClient) CompleteMission added in v0.2.0

func (m *MCPGameClient) CompleteMission(ctx context.Context, missionID string) error

func (*MCPGameClient) CompletedMissions added in v0.2.0

func (m *MCPGameClient) CompletedMissions(ctx context.Context) error

CompletedMissions lists the player's completed missions.

func (*MCPGameClient) Connect added in v0.2.0

func (m *MCPGameClient) Connect(ctx context.Context) error

Connect performs the MCP initialize handshake and starts the background poller.

func (*MCPGameClient) CraftBulk added in v0.2.0

func (m *MCPGameClient) CraftBulk(ctx context.Context, jobs []map[string]any) error

func (*MCPGameClient) CraftDryRun added in v0.2.0

func (m *MCPGameClient) CraftDryRun(ctx context.Context, recipeID string, quantity int, facilityID string) (*serverapi.CraftDryRunResponse, error)

CraftDryRun quotes a craft job without queuing it, via the MCP bridge.

func (*MCPGameClient) CraftWithOptions added in v0.2.0

func (m *MCPGameClient) CraftWithOptions(ctx context.Context, recipeID string, quantity int, deliverTo string) error

func (*MCPGameClient) CraftWithQuantity added in v0.2.0

func (m *MCPGameClient) CraftWithQuantity(ctx context.Context, recipeID string, quantity int) error

func (*MCPGameClient) CreateBuyOrder added in v0.2.0

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

func (*MCPGameClient) CreateFaction added in v0.2.0

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

func (*MCPGameClient) CreateNote added in v0.2.0

func (m *MCPGameClient) CreateNote(ctx context.Context, title, content string) error

func (*MCPGameClient) CreateSellOrder added in v0.2.0

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

func (*MCPGameClient) DeclineMission added in v0.2.0

func (m *MCPGameClient) DeclineMission(ctx context.Context, templateID string) error

func (*MCPGameClient) DeleteNote added in v0.2.0

func (m *MCPGameClient) DeleteNote(ctx context.Context, noteID string) error

DeleteNote deletes a saved note by ID.

func (*MCPGameClient) DeployDrone added in v0.2.0

func (m *MCPGameClient) DeployDrone(ctx context.Context, droneID string, all bool) error

DeployDrone launches a drone from the bay into the current location, or every in-bay drone when all is true. Server-side bandwidth check still applies — drones that would exceed remaining bandwidth are silently skipped.

func (*MCPGameClient) DepositAllItems added in v0.2.0

func (m *MCPGameClient) DepositAllItems(ctx context.Context) error

func (*MCPGameClient) DepositItems added in v0.2.0

func (m *MCPGameClient) DepositItems(ctx context.Context, itemID string, quantity float64) error

func (*MCPGameClient) DepositItemsPayload added in v0.2.0

func (m *MCPGameClient) DepositItemsPayload(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) DistressSignal added in v0.2.0

func (m *MCPGameClient) DistressSignal(ctx context.Context, distressType string) error

func (*MCPGameClient) Dock added in v0.2.0

func (m *MCPGameClient) Dock(ctx context.Context) error

func (*MCPGameClient) Espionage added in v0.2.0

func (m *MCPGameClient) Espionage(ctx context.Context) error

func (*MCPGameClient) EstimatePurchase added in v0.2.0

func (m *MCPGameClient) EstimatePurchase(ctx context.Context, itemID string, quantity int) error

func (*MCPGameClient) Facility added in v0.2.0

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

func (*MCPGameClient) FactionAcceptAlly added in v0.2.0

func (m *MCPGameClient) FactionAcceptAlly(ctx context.Context, targetFactionID string) error

func (*MCPGameClient) FactionAcceptInvite added in v0.2.0

func (m *MCPGameClient) FactionAcceptInvite(ctx context.Context, factionID string) error

FactionAcceptInvite accepts a pending invitation to join a faction.

func (*MCPGameClient) FactionAcceptPeace added in v0.2.0

func (m *MCPGameClient) FactionAcceptPeace(ctx context.Context, targetFactionID string) error

func (*MCPGameClient) FactionCancelMission added in v0.2.0

func (m *MCPGameClient) FactionCancelMission(ctx context.Context, templateID string) error

func (*MCPGameClient) FactionCreateBuyOrder added in v0.2.0

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

func (*MCPGameClient) FactionCreateRole added in v0.2.0

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

func (*MCPGameClient) FactionCreateSellOrder added in v0.2.0

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

func (*MCPGameClient) FactionDeclareWar added in v0.2.0

func (m *MCPGameClient) FactionDeclareWar(ctx context.Context, targetFactionID, reason string) error

func (*MCPGameClient) FactionDeclineInvite added in v0.2.0

func (m *MCPGameClient) FactionDeclineInvite(ctx context.Context, factionID string) error

func (*MCPGameClient) FactionDeleteRole added in v0.2.0

func (m *MCPGameClient) FactionDeleteRole(ctx context.Context, roleID string) error

func (*MCPGameClient) FactionDeleteRoom added in v0.2.0

func (m *MCPGameClient) FactionDeleteRoom(ctx context.Context, roomID string) error

func (*MCPGameClient) FactionDepositCredits added in v0.2.0

func (m *MCPGameClient) FactionDepositCredits(ctx context.Context, amount float64) error

func (*MCPGameClient) FactionDepositItems added in v0.2.0

func (m *MCPGameClient) FactionDepositItems(ctx context.Context, itemID string, quantity int) error

func (*MCPGameClient) FactionDepositItemsPayload added in v0.2.0

func (m *MCPGameClient) FactionDepositItemsPayload(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) FactionEdit added in v0.2.0

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

func (*MCPGameClient) FactionEditRole added in v0.2.0

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

func (*MCPGameClient) FactionGetInvites added in v0.2.0

func (m *MCPGameClient) FactionGetInvites(ctx context.Context) error

func (*MCPGameClient) FactionInfo added in v0.2.0

func (m *MCPGameClient) FactionInfo(ctx context.Context) error

func (*MCPGameClient) FactionIntelStatus added in v0.2.0

func (m *MCPGameClient) FactionIntelStatus(ctx context.Context) error

func (*MCPGameClient) FactionInvite added in v0.2.0

func (m *MCPGameClient) FactionInvite(ctx context.Context, playerID string) error

func (*MCPGameClient) FactionKick added in v0.2.0

func (m *MCPGameClient) FactionKick(ctx context.Context, playerID string) error

func (*MCPGameClient) FactionList added in v0.2.0

func (m *MCPGameClient) FactionList(ctx context.Context, limit, offset int) error

func (*MCPGameClient) FactionListMissions added in v0.2.0

func (m *MCPGameClient) FactionListMissions(ctx context.Context) error

func (*MCPGameClient) FactionPromote added in v0.2.0

func (m *MCPGameClient) FactionPromote(ctx context.Context, playerID, roleID string) error

func (*MCPGameClient) FactionProposeAlly added in v0.2.0

func (m *MCPGameClient) FactionProposeAlly(ctx context.Context, targetFactionID string) error

func (*MCPGameClient) FactionProposePeace added in v0.2.0

func (m *MCPGameClient) FactionProposePeace(ctx context.Context, targetFactionID, terms string) error

func (*MCPGameClient) FactionQueryIntel added in v0.2.0

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

func (*MCPGameClient) FactionQueryTradeIntel added in v0.2.0

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

func (*MCPGameClient) FactionRemoveAlly added in v0.2.0

func (m *MCPGameClient) FactionRemoveAlly(ctx context.Context, targetFactionID string) error

func (*MCPGameClient) FactionRemoveEnemy added in v0.2.0

func (m *MCPGameClient) FactionRemoveEnemy(ctx context.Context, targetFactionID string) error

FactionRemoveEnemy removes a faction from this faction's enemy list.

func (*MCPGameClient) FactionRooms added in v0.2.0

func (m *MCPGameClient) FactionRooms(ctx context.Context) error

func (*MCPGameClient) FactionSetEnemy added in v0.2.0

func (m *MCPGameClient) FactionSetEnemy(ctx context.Context, targetFactionID string) error

func (*MCPGameClient) FactionSubmitIntel added in v0.2.0

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

func (*MCPGameClient) FactionTradeIntelStatus added in v0.2.0

func (m *MCPGameClient) FactionTradeIntelStatus(ctx context.Context) error

func (*MCPGameClient) FactionVisitRoom added in v0.2.0

func (m *MCPGameClient) FactionVisitRoom(ctx context.Context, roomID string) error

func (*MCPGameClient) FactionWithdrawCredits added in v0.2.0

func (m *MCPGameClient) FactionWithdrawCredits(ctx context.Context, amount float64) error

func (*MCPGameClient) FactionWithdrawInvite added in v0.2.0

func (m *MCPGameClient) FactionWithdrawInvite(ctx context.Context, playerID string) error

FactionWithdrawInvite withdraws an invitation previously sent to a player.

func (*MCPGameClient) FactionWithdrawItems added in v0.2.0

func (m *MCPGameClient) FactionWithdrawItems(ctx context.Context, itemID string, quantity int) error

func (*MCPGameClient) FactionWithdrawItemsPayload added in v0.2.0

func (m *MCPGameClient) FactionWithdrawItemsPayload(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) FactionWriteRoom added in v0.2.0

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

func (*MCPGameClient) FindRoute added in v0.2.0

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

func (*MCPGameClient) Fleet added in v0.2.0

func (m *MCPGameClient) Fleet(ctx context.Context, action string, playerID string) error

func (*MCPGameClient) ForumCreateThread added in v0.2.0

func (m *MCPGameClient) ForumCreateThread(ctx context.Context, title, content string, category string) error

func (*MCPGameClient) ForumDeleteReply added in v0.2.0

func (m *MCPGameClient) ForumDeleteReply(ctx context.Context, replyID string) error

func (*MCPGameClient) ForumDeleteThread added in v0.2.0

func (m *MCPGameClient) ForumDeleteThread(ctx context.Context, threadID string) error

func (*MCPGameClient) ForumGetThread added in v0.2.0

func (m *MCPGameClient) ForumGetThread(ctx context.Context, threadID string) error

func (*MCPGameClient) ForumList added in v0.2.0

func (m *MCPGameClient) ForumList(ctx context.Context, page int) error

func (*MCPGameClient) ForumReply added in v0.2.0

func (m *MCPGameClient) ForumReply(ctx context.Context, threadID, content string) error

func (*MCPGameClient) ForumUpvote added in v0.2.0

func (m *MCPGameClient) ForumUpvote(ctx context.Context, threadID string, replyID string) error

func (*MCPGameClient) GetActionLog added in v0.2.0

func (m *MCPGameClient) GetActionLog(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) GetActiveMissions added in v0.2.0

func (m *MCPGameClient) GetActiveMissions(ctx context.Context) error

func (*MCPGameClient) GetBase added in v0.2.0

func (m *MCPGameClient) GetBase(ctx context.Context) error

func (*MCPGameClient) GetBattleStatus added in v0.2.0

func (m *MCPGameClient) GetBattleStatus(ctx context.Context) error

func (*MCPGameClient) GetCargo added in v0.2.0

func (m *MCPGameClient) GetCargo(ctx context.Context) error

func (*MCPGameClient) GetChatHistory added in v0.2.0

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

func (*MCPGameClient) GetCommands added in v0.2.0

func (m *MCPGameClient) GetCommands(ctx context.Context) error

func (*MCPGameClient) GetDrone added in v0.2.0

func (m *MCPGameClient) GetDrone(ctx context.Context, droneID string) error

GetDrone fetches details for a single drone.

func (*MCPGameClient) GetDrones added in v0.2.0

func (m *MCPGameClient) GetDrones(ctx context.Context) error

GetDrones fetches the drone bay summary and roster.

func (*MCPGameClient) GetEmpireInfo added in v0.2.0

func (m *MCPGameClient) GetEmpireInfo(ctx context.Context, empireID string) error

GetEmpireInfo fetches empire information.

func (*MCPGameClient) GetGuide added in v0.2.0

func (m *MCPGameClient) GetGuide(ctx context.Context, guide string) error

func (*MCPGameClient) GetInsuranceQuote added in v0.2.0

func (m *MCPGameClient) GetInsuranceQuote(ctx context.Context) error

func (*MCPGameClient) GetListings added in v0.2.0

func (m *MCPGameClient) GetListings(ctx context.Context) error

func (*MCPGameClient) GetMap added in v0.2.0

func (m *MCPGameClient) GetMap(ctx context.Context, force ...bool) error

func (*MCPGameClient) GetMarketListings added in v0.2.0

func (m *MCPGameClient) GetMarketListings() []MarketListing

GetMarketListings returns cached market listings from the last GetListings call.

func (*MCPGameClient) GetMissions added in v0.2.0

func (m *MCPGameClient) GetMissions(ctx context.Context) error

func (*MCPGameClient) GetNearby added in v0.2.0

func (m *MCPGameClient) GetNearby(ctx context.Context) error

func (*MCPGameClient) GetNotes added in v0.2.0

func (m *MCPGameClient) GetNotes(ctx context.Context) error

func (*MCPGameClient) GetNotifications added in v0.2.0

func (m *MCPGameClient) GetNotifications(ctx context.Context) error

func (*MCPGameClient) GetPOI added in v0.2.0

func (m *MCPGameClient) GetPOI(ctx context.Context) error

func (*MCPGameClient) GetRawJSON added in v0.2.0

func (m *MCPGameClient) GetRawJSON(key string) []byte

GetRawJSON returns cached raw JSON for the given key, if available.

func (*MCPGameClient) GetRecipes added in v0.2.0

func (m *MCPGameClient) GetRecipes(ctx context.Context) error

func (*MCPGameClient) GetShip added in v0.2.0

func (m *MCPGameClient) GetShip(ctx context.Context) error

func (*MCPGameClient) GetSkills added in v0.2.0

func (m *MCPGameClient) GetSkills(ctx context.Context) error

func (*MCPGameClient) GetState added in v0.2.0

func (m *MCPGameClient) GetState() *State

GetState returns a deep copy of the current game state.

func (*MCPGameClient) GetStatus added in v0.2.0

func (m *MCPGameClient) GetStatus(ctx context.Context) error

func (*MCPGameClient) GetSystem added in v0.2.0

func (m *MCPGameClient) GetSystem(ctx context.Context) error

func (*MCPGameClient) GetSystemAgents added in v0.2.0

func (m *MCPGameClient) GetSystemAgents(ctx context.Context) error

func (*MCPGameClient) GetTaxEstimate added in v0.2.0

func (m *MCPGameClient) GetTaxEstimate(ctx context.Context) error

GetTaxEstimate fetches the player's current tax assessment estimate.

func (*MCPGameClient) GetTrades added in v0.2.0

func (m *MCPGameClient) GetTrades(ctx context.Context) error

func (*MCPGameClient) GetVersion added in v0.2.0

func (m *MCPGameClient) GetVersion(ctx context.Context) error

func (*MCPGameClient) GetWrecks added in v0.2.0

func (m *MCPGameClient) GetWrecks(ctx context.Context) error

func (*MCPGameClient) Help added in v0.2.0

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

func (*MCPGameClient) InstallMod added in v0.2.0

func (m *MCPGameClient) InstallMod(ctx context.Context, moduleID string) error

func (*MCPGameClient) IsConnected added in v0.2.0

func (m *MCPGameClient) IsConnected() bool

IsConnected returns whether the client has an active session.

func (*MCPGameClient) Jettison added in v0.2.0

func (m *MCPGameClient) Jettison(ctx context.Context, itemID string, quantity float64) error

func (*MCPGameClient) JoinFaction added in v0.2.0

func (m *MCPGameClient) JoinFaction(ctx context.Context, factionID string) error

func (*MCPGameClient) Jump added in v0.2.0

func (m *MCPGameClient) Jump(ctx context.Context, targetSystem string) (*JumpResult, error)

func (*MCPGameClient) LeaveFaction added in v0.2.0

func (m *MCPGameClient) LeaveFaction(ctx context.Context) error

func (*MCPGameClient) ListPassengers added in v0.2.0

ListPassengers returns the passengers currently aboard via the MCP bridge.

func (*MCPGameClient) ListShipForSale added in v0.2.0

func (m *MCPGameClient) ListShipForSale(ctx context.Context, shipID string, price float64) error

func (*MCPGameClient) ListShips added in v0.2.0

func (m *MCPGameClient) ListShips(ctx context.Context) error

func (*MCPGameClient) ListStationPassengers added in v0.2.0

func (m *MCPGameClient) ListStationPassengers(ctx context.Context, station string) (*serverapi.ListStationPassengersResponse, error)

ListStationPassengers returns passengers waiting at a station via the MCP bridge.

func (*MCPGameClient) LoadDrone added in v0.2.0

func (m *MCPGameClient) LoadDrone(ctx context.Context, itemID string) error

LoadDrone loads an item from cargo into the drone bay as a drone.

func (*MCPGameClient) LoadPassenger added in v0.2.0

func (m *MCPGameClient) LoadPassenger(ctx context.Context, destination string) (*serverapi.LoadPassengerResponse, error)

LoadPassenger boards passengers bound for destination via the MCP bridge.

func (*MCPGameClient) Login added in v0.2.0

func (m *MCPGameClient) Login(ctx context.Context) error

Login authenticates with the game server via the MCP login tool.

func (*MCPGameClient) LootWreck added in v0.2.0

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

func (*MCPGameClient) Mine added in v0.2.0

func (m *MCPGameClient) Mine(ctx context.Context) error

func (*MCPGameClient) ModifyOrder added in v0.2.0

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

func (*MCPGameClient) Petition added in v0.2.0

func (m *MCPGameClient) Petition(ctx context.Context, empireID, message string) error

Petition submits a citizenship petition message to an empire.

func (*MCPGameClient) RawCommand added in v0.2.0

func (m *MCPGameClient) RawCommand(ctx context.Context, command string, args map[string]any) error

func (*MCPGameClient) ReadNote added in v0.2.0

func (m *MCPGameClient) ReadNote(ctx context.Context, noteID string) error

func (*MCPGameClient) Ready added in v0.2.0

func (m *MCPGameClient) Ready() <-chan struct{}

Ready returns a channel that is closed when the client is ready (after login).

func (*MCPGameClient) RecallDrone added in v0.2.0

func (m *MCPGameClient) RecallDrone(ctx context.Context, droneID string, all bool) error

RecallDrone recalls a deployed drone (or all drones when all is true).

func (*MCPGameClient) Recycle added in v0.2.0

func (m *MCPGameClient) Recycle(ctx context.Context, recipeID string, quantity int) error

func (*MCPGameClient) RecycleWithOptions added in v0.2.0

func (m *MCPGameClient) RecycleWithOptions(ctx context.Context, recipeID string, quantity int, deliverTo string) error

func (*MCPGameClient) RefitShip added in v0.2.0

func (m *MCPGameClient) RefitShip(ctx context.Context) error

func (*MCPGameClient) Refuel added in v0.2.0

func (m *MCPGameClient) Refuel(ctx context.Context) error

func (*MCPGameClient) RefuelShip added in v0.2.0

func (m *MCPGameClient) RefuelShip(ctx context.Context, target string, quantity int) error

func (*MCPGameClient) Register added in v0.2.0

func (m *MCPGameClient) Register(ctx context.Context, empire, registrationCode string) error

Register creates a new account and logs in.

func (*MCPGameClient) Reload added in v0.2.0

func (m *MCPGameClient) Reload(ctx context.Context, weaponInstanceID, ammoItemID string) error

func (*MCPGameClient) Repair added in v0.2.0

func (m *MCPGameClient) Repair(ctx context.Context) error

func (*MCPGameClient) RepairWith added in v0.2.0

func (m *MCPGameClient) RepairWith(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) SalvageWreck added in v0.2.0

func (m *MCPGameClient) SalvageWreck(ctx context.Context, wreckID string) error

func (*MCPGameClient) Scan added in v0.2.0

func (m *MCPGameClient) Scan(ctx context.Context) error

func (*MCPGameClient) ScanTarget added in v0.2.0

func (m *MCPGameClient) ScanTarget(ctx context.Context, targetID string) error

func (*MCPGameClient) ScrapShip added in v0.2.0

func (m *MCPGameClient) ScrapShip(ctx context.Context, shipID string) error

ScrapShip scraps a ship, moving its cargo and modules to storage.

func (*MCPGameClient) SearchSystems added in v0.2.0

func (m *MCPGameClient) SearchSystems(ctx context.Context, query string) error

func (*MCPGameClient) Sell added in v0.2.0

func (m *MCPGameClient) Sell(ctx context.Context, itemID string, quantity float64) error

func (*MCPGameClient) SellAllBulk added in v0.2.0

func (m *MCPGameClient) SellAllBulk(ctx context.Context, reservedItems []string) error

func (*MCPGameClient) SellShip added in v0.2.0

func (m *MCPGameClient) SellShip(ctx context.Context, shipID string) error

func (*MCPGameClient) SendGift added in v0.2.0

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

func (*MCPGameClient) SetAnonymous added in v0.2.0

func (m *MCPGameClient) SetAnonymous(ctx context.Context, anonymous bool) error

func (*MCPGameClient) SetColors added in v0.2.0

func (m *MCPGameClient) SetColors(ctx context.Context, primaryColor, secondaryColor string) error

func (*MCPGameClient) SetDebugLogging added in v0.2.0

func (m *MCPGameClient) SetDebugLogging(enabled bool)

SetDebugLogging enables or disables debug logging for raw responses.

func (*MCPGameClient) SetDroneName added in v0.2.0

func (m *MCPGameClient) SetDroneName(ctx context.Context, droneID, name string) error

SetDroneName assigns a display name to a drone you own.

func (*MCPGameClient) SetHandler added in v0.2.0

func (m *MCPGameClient) SetHandler(handler MessageHandler)

SetHandler sets the message handler for lifecycle events. Only OnConnected and OnDisconnected are called; OnMessage is not used.

func (*MCPGameClient) SetHomeBase added in v0.2.0

func (m *MCPGameClient) SetHomeBase(ctx context.Context, baseID string) error

func (*MCPGameClient) SetOnChatMessage added in v0.2.0

func (m *MCPGameClient) SetOnChatMessage(fn func(msg serverapi.ChatMessage))

SetOnChatMessage registers a callback that fires for each chat notification returned by get_notifications. MCP has no server-push channel, so delivery latency is bounded by the poll interval (and by the 10s server throttle on get_notifications). Pass nil to disable.

func (*MCPGameClient) SetPlayerStatus added in v0.2.0

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

func (*MCPGameClient) SetPolling added in v0.2.0

func (m *MCPGameClient) SetPolling(enabled bool)

SetPolling enables or disables automatic get_status polling every 10 seconds. By default, polling is enabled to keep state fresh. Disable if you want to manually control when to refresh state.

func (*MCPGameClient) SetXPCallback added in v0.2.0

func (m *MCPGameClient) SetXPCallback(fn XPCallbackFunc)

SetXPCallback installs an XP observation callback. Passing nil disables callbacks. The callback fires after every successful mutation tool call once state has been refreshed from get_skills (which provides the XP values MCP mutation responses omit).

func (*MCPGameClient) Shipping added in v0.2.0

func (m *MCPGameClient) Shipping(ctx context.Context, action string, payload map[string]any) error

Shipping sends a /shipping action with the given payload via the MCP bridge. The reply is cached under "shipping_<action>"; read it with GetRawJSON and unmarshal into the matching serverapi struct.

func (*MCPGameClient) ShippingAccept added in v0.2.0

func (m *MCPGameClient) ShippingAccept(ctx context.Context, shipmentID, carrier string) error

ShippingAccept accepts a contract as the given carrier (player|faction). The package lands in the carrier's storage at origin. Reply: shipping_accept.

func (*MCPGameClient) ShippingCancel added in v0.2.0

func (m *MCPGameClient) ShippingCancel(ctx context.Context, shipmentID string) error

ShippingCancel cancels a contract (breach-avoidance escape hatch). Reply: shipping_cancel.

func (*MCPGameClient) ShippingDeliver added in v0.2.0

func (m *MCPGameClient) ShippingDeliver(ctx context.Context, shipmentID string) error

ShippingDeliver settles a delivered contract. Reply: shipping_deliver.

func (*MCPGameClient) ShippingGet added in v0.2.0

func (m *MCPGameClient) ShippingGet(ctx context.Context, shipmentID string) error

ShippingGet fetches one contract by id. Reply: shipping_get.

func (*MCPGameClient) ShippingList added in v0.2.0

func (m *MCPGameClient) ShippingList(ctx context.Context, sort string) error

ShippingList fetches the current station's freight board (docked-only). sort ∈ {reward,distance,age} (empty = server default reward). Reply: shipping_list.

func (*MCPGameClient) ShippingPayDebt added in v0.2.0

func (m *MCPGameClient) ShippingPayDebt(ctx context.Context, amount int64) error

ShippingPayDebt pays freight debt (amount ≤ 0 pays the full balance). Reply: shipping_pay_debt.

func (*MCPGameClient) ShippingProfile added in v0.2.0

func (m *MCPGameClient) ShippingProfile(ctx context.Context) error

ShippingProfile fetches this actor's carrier standing, capacity, progression and debts. Reply: shipping_profile.

func (*MCPGameClient) ShippingReturn added in v0.2.0

func (m *MCPGameClient) ShippingReturn(ctx context.Context, shipmentID string) error

ShippingReturn returns a contract to its origin (breach-avoidance escape hatch). Reply: shipping_return.

func (*MCPGameClient) ShippingTrack added in v0.2.0

func (m *MCPGameClient) ShippingTrack(ctx context.Context, shipmentID string, limit int) error

ShippingTrack fetches a contract plus its beacon custody events (limit ≤ 200; 0 = server default). Reply: shipping_track.

func (*MCPGameClient) SurveySystem added in v0.2.0

func (m *MCPGameClient) SurveySystem(ctx context.Context) error

func (*MCPGameClient) SwitchShip added in v0.2.0

func (m *MCPGameClient) SwitchShip(ctx context.Context, shipID string) error

func (*MCPGameClient) TowWreck added in v0.2.0

func (m *MCPGameClient) TowWreck(ctx context.Context, wreckID string) error

func (*MCPGameClient) TradeAccept added in v0.2.0

func (m *MCPGameClient) TradeAccept(ctx context.Context, tradeID string) error

func (*MCPGameClient) TradeCancel added in v0.2.0

func (m *MCPGameClient) TradeCancel(ctx context.Context, tradeID string) error

func (*MCPGameClient) TradeDecline added in v0.2.0

func (m *MCPGameClient) TradeDecline(ctx context.Context, tradeID string) error

func (*MCPGameClient) TradeOffer added in v0.2.0

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

func (*MCPGameClient) Travel added in v0.2.0

func (m *MCPGameClient) Travel(ctx context.Context, targetPOI string) (*TravelResult, error)

func (*MCPGameClient) Undock added in v0.2.0

func (m *MCPGameClient) Undock(ctx context.Context) error

func (*MCPGameClient) UninstallMod added in v0.2.0

func (m *MCPGameClient) UninstallMod(ctx context.Context, moduleID string) error

func (*MCPGameClient) UnloadDrone added in v0.2.0

func (m *MCPGameClient) UnloadDrone(ctx context.Context, droneID string) error

UnloadDrone unloads a drone from the bay back into cargo.

func (*MCPGameClient) UnloadPassenger added in v0.2.0

func (m *MCPGameClient) UnloadPassenger(ctx context.Context, nameOrID string) error

UnloadPassenger puts a passenger (or "all") off at the current station via the MCP bridge.

func (*MCPGameClient) UploadDroneScript added in v0.2.0

func (m *MCPGameClient) UploadDroneScript(ctx context.Context, droneID, script string) error

UploadDroneScript uploads an automation script to a deployed drone.

func (*MCPGameClient) UseItem added in v0.2.0

func (m *MCPGameClient) UseItem(ctx context.Context, itemID string, quantity int) error

func (*MCPGameClient) ViewFactionStorage added in v0.2.0

func (m *MCPGameClient) ViewFactionStorage(ctx context.Context) error

func (*MCPGameClient) ViewFactionStorageAt added in v0.2.0

func (m *MCPGameClient) ViewFactionStorageAt(ctx context.Context, stationID string) error

ViewFactionStorageAt views your faction's shared storage at a specific station. As of v0.299.0, you can query remotely with station_id as long as you're a faction member.

func (*MCPGameClient) ViewInsurance added in v0.2.0

func (m *MCPGameClient) ViewInsurance(ctx context.Context) error

ViewInsurance lists the player's active insurance policies.

func (*MCPGameClient) ViewMarket added in v0.2.0

func (m *MCPGameClient) ViewMarket(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) ViewOrders added in v0.2.0

func (m *MCPGameClient) ViewOrders(ctx context.Context) error

func (*MCPGameClient) ViewStorage added in v0.2.0

func (m *MCPGameClient) ViewStorage(ctx context.Context) error

func (*MCPGameClient) ViewStorageAt added in v0.2.0

func (m *MCPGameClient) ViewStorageAt(ctx context.Context, stationID string) error

func (*MCPGameClient) WithdrawItems added in v0.2.0

func (m *MCPGameClient) WithdrawItems(ctx context.Context, itemID string, quantity float64) error

func (*MCPGameClient) WithdrawItemsPayload added in v0.2.0

func (m *MCPGameClient) WithdrawItemsPayload(ctx context.Context, payload map[string]any) error

func (*MCPGameClient) WriteNote added in v0.2.0

func (m *MCPGameClient) WriteNote(ctx context.Context, noteID, content string) error

type MCPManager

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

MCPManager manages the lifecycle of MCP client connections

func NewMCPManager

func NewMCPManager(logger *log.Logger) *MCPManager

NewMCPManager creates a new MCP manager

func (*MCPManager) CloseAll

func (mgr *MCPManager) CloseAll() error

CloseAll closes all MCP clients

func (*MCPManager) GetClient

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

GetClient gets or creates an MCP client for the specified server

type MarketListing

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

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

  • get_listings (in payload.listings array)

func MarketListingFromAPI

func MarketListingFromAPI(ext serverapi.MarketListing) MarketListing

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

type MarketSnapshot

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

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

type MessageHandler

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

MessageHandler handles incoming game messages

type MiningLoopConfig

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

	// MiningType selects the resource type to mine: asteroid (default), gas, or ice.
	// This determines which POI types to target and which equipment to count.
	MiningType MiningType

	// 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 GameClient, 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-explorer, MiningStrategy, and other autonomous agents. It handles the complete mining workflow:

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

10. Check for upgrades (if configured)

The loop continues until:

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

Example usage:

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

type MiningType added in v0.2.0

type MiningType string

MiningType specifies the type of resource extraction to perform.

const (
	// MiningTypeAsteroid mines asteroid belts/fields using mining lasers.
	MiningTypeAsteroid MiningType = "asteroid"
	// MiningTypeGas harvests gas clouds using gas harvesters.
	MiningTypeGas MiningType = "gas"
	// MiningTypeIce harvests ice fields using ice harvesters.
	MiningTypeIce MiningType = "ice"
)

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"`
	TypeID      string `json:"type_id,omitempty"` // Module type ID (e.g., "survey_scanner_i")
}

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.

func ModuleDefinitionFromShipModule added in v0.2.0

func ModuleDefinitionFromShipModule(ext serverapi.ShipModule) ModuleDefinition

ModuleDefinitionFromShipModule converts a serverapi ShipModule 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 ObservedPassenger added in v0.2.0

type ObservedPassenger struct {
	CitizenID   string
	Name        string
	Citizenship string
	Bio         string
	Class       string

	Source string
	SeenAt time.Time
}

ObservedPassenger is a single passenger (citizen) record extracted from a passenger-bearing server response. It is the input to a PassengerObserver callback and the galaxy-wide passenger catalog.

Citizenship and Bio may be empty when the source doesn't carry them (e.g. an aboard manifest lacks citizenship); the recorder COALESCE-merges so a sparse source never wipes data already captured from a richer one.

type ObservedPlayer added in v0.2.0

type ObservedPlayer struct {
	PlayerID       string
	Username       string
	ShipClass      string
	FactionID      string
	FactionTag     string
	ClanTag        string
	PrimaryColor   string
	SecondaryColor string
	StatusMessage  string
	Anonymous      bool
	InCombat       bool

	SystemID string
	POIID    string
	Source   string
	SeenAt   time.Time
}

ObservedPlayer is a single player record extracted from a server response or push event. It is the input to a PlayerObserver callback.

Fields ShipClass, POIID may be empty when the source doesn't carry them (e.g. chat_message has no ship/POI). SystemID is empty when the observation has no spatial context (chat) — the recorder uses that to decide whether to write a sightings row.

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"`
	Class            string        `json:"class,omitempty"` // MK classification (e.g., "G2 V") or planet class
	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"`
	RevealDifficulty int           `json:"reveal_difficulty,omitempty"`
	ExpiresAt        string        `json:"expires_at,omitempty"` // ISO-8601 timestamp when POI expires (e.g., wormholes)
}

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

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

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

func FindJumpGate

func FindJumpGate(state *State) *POI

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

func FindMiningLocation

func FindMiningLocation(state *State) *POI

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

func FindPOIByType

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

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

func FindStation

func FindStation(state *State) *POI

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

func POIFromAPI

func POIFromAPI(ext serverapi.POI) POI

POIFromAPI converts a serverapi POI to an internal POI.

type POIResource

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

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

func POIResourceFromAPI

func POIResourceFromAPI(ext serverapi.POIResource) POIResource

POIResourceFromAPI converts a serverapi POIResource to an internal POIResource.

type PassengerObserver added in v0.2.0

type PassengerObserver func(obs []ObservedPassenger)

PassengerObserver receives batches of passenger observations as the game client parses incoming server messages. Implementations must not block — the callback is invoked from the response-handling goroutine.

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"`
	FactionTag        string             `json:"faction_tag,omitempty"` // readable faction tag (e.g. "YSMT"); not in player payload, captured from faction_info
	StatusMessage     string             `json:"status_message,omitempty"`
	ClanTag           string             `json:"clan_tag,omitempty"`
	PrimaryColor      string             `json:"primary_color,omitempty"`
	SecondaryColor    string             `json:"secondary_color,omitempty"`
	Anonymous         bool               `json:"anonymous"`
	IsCloaked         bool               `json:"is_cloaked"`
	Skills            map[string]Skill   `json:"skills"`
	SkillXP           map[string]float64 `json:"skill_xp,omitempty"` // Current XP toward next level
	Stats             PlayerStats        `json:"stats"`
	TowingWreckID     string             `json:"towing_wreck_id,omitempty"`
	Experience        int64              `json:"experience,omitempty"`
	DiscoveredSystems map[string]any     `json:"discovered_systems,omitempty"`
	LastActiveAt      string             `json:"last_active_at,omitempty"`
	LastLoginAt       string             `json:"last_login_at,omitempty"`
	CreatedAt         string             `json:"created_at,omitempty"`
}

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

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

func PlayerFromAPI

func PlayerFromAPI(ext serverapi.Player) Player

PlayerFromAPI converts a serverapi Player to an internal Player.

type PlayerObserver added in v0.2.0

type PlayerObserver func(obs []ObservedPlayer)

PlayerObserver receives batches of player observations as the game client parses incoming server messages. Implementations must not block — the callback is invoked from the response-handling goroutine.

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"`
	OreMined          int64 `json:"ore_mined"`
	CreditsEarned     int64 `json:"credits_earned"`
	CreditsSpent      int64 `json:"credits_spent"`
	TradesCompleted   int   `json:"trades_completed"`
	SystemsExplored   int   `json:"systems_explored"`
	ItemsCrafted      int   `json:"items_crafted"`
	MissionsCompleted int   `json:"missions_completed"`
	BasesDestroyed    int   `json:"bases_destroyed"`
	DistanceTraveled  int64 `json:"distance_traveled"`
	PiratesDestroyed  int   `json:"pirates_destroyed"`
	ShipsLost         int   `json:"ships_lost"`
	TimePlayed        int64 `json:"time_played"`
}

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

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

func PlayerStatsFromAPI

func PlayerStatsFromAPI(ext serverapi.PlayerStats) PlayerStats

PlayerStatsFromAPI converts a serverapi PlayerStats to an internal PlayerStats.

type Position

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

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

func PositionFromAPI

func PositionFromAPI(ext serverapi.Position) Position

PositionFromAPI converts a serverapi Position to an internal Position.

type ReconnectGate added in v0.2.0

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

ReconnectGate is a host-wide coordinator that prevents every client sharing one IP from reconnecting at the same instant. After a server restart all clients lose their socket together; without coordination they stampede the login endpoint and trip a per-IP rate-limit block that then *escalates* every time any client keeps probing it.

The gate is backed by a single small file (shared by every process on the host, across fleets) holding two timestamps:

  • last_attempt: when any client last dialed, so dials are spaced >= cooldown apart fleet-wide; and
  • blocked_until: a rate-limit block one client discovered, which ALL clients then honor so the block can expire instead of being re-triggered.

Access is serialized with an advisory file lock (flock), so the read-modify- write of the timestamps is atomic across processes.

func NewReconnectGate added in v0.2.0

func NewReconnectGate(path string, cooldown time.Duration) *ReconnectGate

NewReconnectGate returns a gate writing to path with the given minimum spacing between fleet-wide reconnect dials. A non-positive cooldown disables spacing (blocked_until is still honored).

func (*ReconnectGate) Acquire added in v0.2.0

func (g *ReconnectGate) Acquire(ctx context.Context) error

Acquire blocks until it is this process's turn to attempt a reconnect: it waits out any fleet-wide block, then waits until at least cooldown has passed since the last dial by any client, and finally claims the slot by stamping last_attempt. Returns ctx.Err() if the context ends while waiting.

func (*ReconnectGate) RecordBlock added in v0.2.0

func (g *ReconnectGate) RecordBlock(d time.Duration) error

RecordBlock publishes a fleet-wide rate-limit block lasting d from now, so every client honors it. A longer existing block is never shortened.

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)

func (*ReconnectingHandler) SetOnSessionContention added in v0.2.0

func (r *ReconnectingHandler) SetOnSessionContention(fn func(consecutiveShortLived int, lastUptime time.Duration))

SetOnSessionContention overrides the default behavior (process exit with code 2) that fires when SessionContentionMaxShortLived consecutive reconnects die in under SessionContentionMinUptime — the signature of another client fighting us for the same credentials. Tests set this to capture the event without killing the test process.

func (*ReconnectingHandler) SetReconnectGate added in v0.2.0

func (r *ReconnectingHandler) SetReconnectGate(g *ReconnectGate)

SetReconnectGate attaches a host-wide reconnect coordinator. Call it on the production agent path; leaving it unset keeps reconnects uncoordinated.

func (*ReconnectingHandler) TriggerReconnect added in v0.2.0

func (r *ReconnectingHandler) TriggerReconnect() bool

TriggerReconnect schedules a fresh reconnection burst if the client is disconnected and no reconnection is already in progress. It is safe to call repeatedly (e.g. from the REPL on every command) — the reconnecting CAS guard means a burst already running, or a live connection, makes this a no-op. Returns true when it actually started a new burst.

func (*ReconnectingHandler) WaitForShutdown added in v0.2.0

func (r *ReconnectingHandler) WaitForShutdown(timeout time.Duration) bool

WaitForShutdown waits for any active reconnection goroutine to complete. This should be called during graceful shutdown to ensure all goroutines exit cleanly.

type RequestHandle added in v0.2.0

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

RequestHandle is returned by Submit. Callers read Ack() for the pending:true ack (multi-tick mutations only) and Result() for the terminal action_result / error. Result is idempotent.

func (*RequestHandle) Ack added in v0.2.0

Ack waits for the server's pending:true ack. Multi-tick actions (travel, jump, dock, mine, attack, self_destruct) emit one; queries and instant mutations may not. Returns ctx.Err() on cancellation.

func (*RequestHandle) ID added in v0.2.0

func (h *RequestHandle) ID() string

ID returns the current request_id. May change across reconnect-replay.

func (*RequestHandle) Result added in v0.2.0

func (h *RequestHandle) Result(ctx context.Context) (protocol.Response, error)

Result waits for the terminal response. Idempotent: subsequent calls return the same value. Returns ctx.Err() on cancellation; the underlying subscription stays live so a late terminal does not become an orphan. If the submit-time context is cancelled, that cancellation is also surfaced regardless of the caller's ctx.

type Result added in v0.2.0

type Result struct {
	Response protocol.Response
	Err      error
}

Result wraps the terminal response or terminal error from a Submit.

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.

func (*SafeCommandBuilder) Buy

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

Buy safely buys items

func (*SafeCommandBuilder) BuyQueued

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

BuyQueued buys items.

func (*SafeCommandBuilder) CompleteMissionQueued

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

CompleteMissionQueued completes a mission.

func (*SafeCommandBuilder) CraftQueued

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

CraftQueued crafts an item.

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.

func (*SafeCommandBuilder) GetBaseQueued

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

GetBaseQueued gets base info.

func (*SafeCommandBuilder) GetCargoQueued

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

GetCargoQueued gets cargo contents.

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.

func (*SafeCommandBuilder) GetNearbyQueued

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

GetNearbyQueued gets nearby players.

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.

func (*SafeCommandBuilder) GetShipQueued

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

GetShipQueued gets ship info.

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.

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.

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.

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.

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.

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.

func (*SafeCommandBuilder) SellAllBulk

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

SellAllBulk safely sells all cargo

func (*SafeCommandBuilder) SellQueued

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

SellQueued sells items.

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.

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.

func (*SafeCommandBuilder) ViewStorageQueued

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

ViewStorageQueued views station storage.

func (*SafeCommandBuilder) WithdrawItemsQueued

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

WithdrawItemsQueued withdraws items from storage.

type ServerError added in v0.2.0

type ServerError struct {
	Code    string
	Message string
}

ServerError is a structured error returned by waitForActionResponse when the server replies with an `error` or `action_error` message. Holding Code separately (rather than only formatting into a string) lets callers classify without regexing the message text.

func (*ServerError) Error added in v0.2.0

func (e *ServerError) Error() string

Error returns the server's human-readable message, falling back to the code when no message was supplied.

type Ship

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

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

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

func ShipFromAPI

func ShipFromAPI(ext serverapi.Ship) Ship

ShipFromAPI converts a serverapi Ship to an internal Ship.

type ShipDef

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

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

func FilterShipsByEmpire

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

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

type SimpleHandler

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

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

func (*SimpleHandler) OnConnected

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

OnConnected logs successful connection events

func (*SimpleHandler) OnDisconnected

func (h *SimpleHandler) OnDisconnected(err error)

OnDisconnected logs disconnection events

func (*SimpleHandler) OnMessage

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

OnMessage logs informational and error messages from server

type Skill

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

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

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

func SkillFromAPI

func SkillFromAPI(ext serverapi.Skill) Skill

SkillFromAPI converts a serverapi Skill to an internal Skill.

type SkillDefinition

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

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

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

func SkillDefinitionFromAPI

func SkillDefinitionFromAPI(ext serverapi.SkillDefinition) SkillDefinition

SkillDefinitionFromAPI converts a serverapi SkillDefinition to an internal SkillDefinition.

type State

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

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

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

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

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

	// System data
	System          SystemData
	CurrentTick     int64
	ServerTimestamp int64 // Server UNIX timestamp from get_notifications
	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

	// Chat history (from get_chat_history response)
	LastChatHistory []ChatMessage

	// Last dock story (narrative description from dock response)
	LastDockStory string

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

State represents the current game state

func (*State) Clone

func (s *State) Clone() *State

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

func (*State) GetCredits

func (s *State) GetCredits() float64

GetCredits returns the current credits

func (*State) GetCurrentSystem

func (s *State) GetCurrentSystem() string

GetCurrentSystem returns the current system name

func (*State) GetFuel

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

GetFuel returns current and max fuel

func (*State) GetNearbyPlayers

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

GetNearbyPlayers returns the list of nearby players

func (*State) GetSystem

func (s *State) GetSystem() SystemData

GetSystem returns the current system data

func (*State) GetTick

func (s *State) GetTick() int64

GetTick returns the current game tick

func (*State) IsDocked

func (s *State) IsDocked() bool

IsDocked returns whether the ship is currently docked

type StationActionStrategy

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

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

type StorageUpdateEvent added in v0.2.0

type StorageUpdateEvent struct {
	BaseID  string
	Credits int
	Items   []serverapi.CargoItem
	Ships   []serverapi.StorageShip
}

StorageUpdateEvent is fired when a view_storage response is received. It contains the parsed storage data for use by callbacks.

type SubmitOption added in v0.2.0

type SubmitOption func(*submitConfig)

SubmitOption customizes Submit. See WithTerminator, WithTimeout, WithAckOnly.

func WithAckOnly added in v0.2.0

func WithAckOnly() SubmitOption

WithAckOnly marks this Submit as a query: the first response (any type) is treated as terminal. Skips the per-action lock entirely. Overrides any WithTerminator passed earlier or later.

func WithTerminator added in v0.2.0

func WithTerminator(t Terminator) SubmitOption

WithTerminator overrides the default terminateOnAction.

func WithTimeout added in v0.2.0

func WithTimeout(d time.Duration) SubmitOption

WithTimeout overrides the default SleepTick*3.

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)
	LastVisitedTick int64            `json:"last_visited_tick,omitempty"` // Game tick when we last had live data for this system (0 = never visited)
}

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

type Terminator func(resp protocol.Response) (done bool, err error)

Terminator reports whether a response resolves a mutation. It runs only against responses that have already passed the mutation's Classifier. done=true means the mutation is finished; err non-nil means it failed.

Implementations MUST be pure: execMutation evaluates the terminator twice against the same terminal response (once inside the router's dispatch and again on receive to surface the err the router discards). Side effects or non-deterministic logic will produce inconsistent outcomes.

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., "silicon_ore")
	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 TravelResult added in v0.2.0

type TravelResult struct {
	POI         string // Final POI ID arrived at
	POIName     string // Human-readable POI name (if available)
	Canceled    bool   // True if travel was interrupted (e.g., combat)
	ArrivalTick int64  // Server-reported arrival tick from the initial ACK (0 if unknown)
	StartTick   int64  // client.state.CurrentTick captured at the moment the server ACKed the travel
}

TravelResult contains the outcome of a completed Travel() call.

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_i", "pulse_laser_i")
	LogEmoji      string  // Emoji for logging
	Capacity      string  // Cargo/capability description for logging
	SuccessMsg    string  // Success message template
}

UpgradeTier defines a ship/equipment upgrade configuration

type XPCallbackFunc added in v0.2.0

type XPCallbackFunc func(action, target string, quantity int, before, after map[string]Skill, beforeXP, afterXP map[string]float64, gameTick int64)

XPCallbackFunc is the signature fired after a successful action that (potentially) affected player skill XP. It receives the before/after skill and SkillXP maps so observers can compute deltas.

type XPCallbackSetter added in v0.2.0

type XPCallbackSetter interface {
	SetXPCallback(fn XPCallbackFunc)
}

XPCallbackSetter is implemented by game clients that support XP observation callbacks. Both the WebSocket *Client and *MCPGameClient satisfy this interface, so observers can wire in regardless of transport.

Directories

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

Jump to

Keyboard shortcuts

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