Five public entry points
@fenwild/pilot-sdkRuntime and contracts
Connection, runner, client, actions, outcomes, recording, owner helpers, errors, and all re-exported public protocol types.
@fenwild/pilot-sdk/game-dataStable world reference
Versioned content, map facts, lookup helpers, and the types that describe them.
@fenwild/pilot-sdk/brainsReference brains
Small readable policies for survival and safe-yard training that can be composed into an independent pilot.
@fenwild/pilot-sdk/browserBrowser client contract
An optional module shape for player-owned browser hosts. The realtime server accepts browser connections only from play.fenwild.com pages, and Fenwild's in-game Resident Pilot uses its separate Go/WASM runtime.
@fenwild/pilot-sdk/trainingOffline brain forge
Identity-minimized datasets, deterministic training, held-out evaluation, benchmarks, artifacts, and local brain execution.
Choose the level of control
runPilot
runPilot(options, brain, callbacks?): Promise<void>Runs the supervised one-observation, one-decision loop and owns connection cleanup.
connectPilot
connectPilot(options): Promise<FenwildPilot>Connects the lower-level client for custom coordination across observations and auxiliary feeds.
parsePilotAction
parsePilotAction(input: unknown): PlayerIntentActionRuntime-checks unknown input and returns a fresh exact public action.
summarizeHistory
summarizeHistory(history): PilotHistorySummary | undefinedProjects a bounded owner-history snapshot into stable aggregate strategy context.
loadPilotRecording
loadPilotRecording(input): PilotRecordingValidates and loads a versioned recording document.
replayPilotRecording
replayPilotRecording(input): AsyncGenerator<PilotReplayFrame>Reconstructs the context available at each recorded observation without contacting the server.
Connection and bounded-work options
baseUrlstringRequired Fenwild HTTP service origin with an optional path prefix.
automationTokenstringRequired named Bot access credential.
signalAbortSignalStops startup, the live client, or a supervised runner.
connectTimeoutMsnumberWebSocket attempt deadline; defaults to 10 seconds, after a separate renewal request of up to 5 seconds.
actionTimeoutMsnumberAuthority acknowledgement deadline; defaults to 10 seconds.
maxPendingActionsnumberLocal pending ceiling up to the authoritative maximum of eight.
reconnectbooleanEnabled by default: bounded startup retries for transient failures and a busy character, and recovery after an established session drops. A revoked or expired credential or an explicit control_superseded close always ends the pilot.
reconnectInitialDelayMsnumberInitial recovery backoff delay.
reconnectMaxDelayMsnumberMaximum recovery backoff delay.
traceCapacitynumberBounded credential-redacted trace capacity.
eventCapacitynumberBounded unread capacity of the reserved events() feed.
actionHistoryCapacitynumberBounded recent action-outcome capacity.
recordingSinkPilotRecordingSinkReceives owner-visible recording events.
fetchtypeof fetchCustom HTTP adapter for scoped POST /auth/session/renew. Defaults to global fetch; separate from socketFactory.
socketFactoryPilotSocketFactoryCustom standards-compatible WebSocket adapter.
onStatus(status) => voidReceives each change to connected, reconnecting or closed; a new pilot starts as connecting, which status() reports.
onEvent(event) => voidReserved for event batches; the current server sends none, so it is not called.
onError(error) => voidReceives protocol errors from Fenwild, including the revoked or superseded verdict that ends a pilot, and a local recording_failed error when recordingSink throws. Socket failures are recorded in trace().
Choose how the brain handles interruptions
The second argument to runPilot is brain(observation, pilot). Return one action or undefined, synchronously or asynchronously. The optional third argument contains these callbacks:
onActionRejected({ pilot, observation, action, error })Handle a correlated authority rejection, then continue from later observations. Without this callback, the rejection stops the runner.
onActionInterrupted({ pilot, observation, error })Discard uncertain local work after a timeout or disconnect and reconsider a fresh observation. Never retry the interrupted action or label it rejected. Without this callback the runner stops. Revocation, an explicit control_superseded close and deliberate shutdown still end the run.
submit acceptance may start travel, combat or crafting. Check later snapshots for arrival or completion; the acknowledgement is not a completed journey.
The connected client
Most brains need only runPilot. Use these methods when a process must coordinate several public feeds or explicitly own submission timing.
Connection
ready()Wait for Fenwild to admit the connection with its first realtime frame. A revoked credential or a character_in_use refusal never resolves it; the first snapshot may follow.
status()Read connecting, connected, reconnecting or closed.
close(code?, reason?)Close feeds, reject pending work as unknown, and stop reconnecting.
Current world
lastObservation()Read the newest projected player observation, if available.
observations()Iterate current snapshots; unread values coalesce to the newest truth.
events()Reserved event-batch feed that stays empty today. Snapshots carry combat impacts, healing, chat, killfeed and nearby deaths.
Markets and social
markets()Iterate correlated Trading Post transaction views.
lastMarketTape() / marketTapes()Read or iterate the global public market tape.
lastFriends() / friends()Read or iterate the newest friends view.
lastMutes() / mutes()Read or iterate the newest chat-mute view.
History and outcomes
lastHistory() / historyUpdates()Read the newest owner profile or iterate meaningful changes.
actionOutcomes()Iterate correlated accepted, rejected and explicitly unknown actions.
recentActionOutcomes(limit?)Read the newest bounded outcomes, ordered oldest to newest.
trace()Read the bounded, credential-redacted local diagnostic trace.
Authority
submit(action, observation?)Validate and submit one ordinary player action against observed authority. An observation more than 10 ticks (6 s) old is refused as stale_intent.
submit → PilotSuccessResolve with correlation fields plus any receipt or action-specific view: market, friends, mutes or weaponChronicle.
Errors preserve what authority actually knows
PilotActionValidationErrorThe proposed action does not match an exact public action variant.
PilotProtocolErrorAuthority rejected the action, for example as stale_intent, refused the connection, for example as character_in_use, or the recognized protocol message was invalid.
PilotActionUnknownErrorAn in-flight action lost authoritative confirmation and must not be replayed blindly.
PilotBackpressureErrorThe configured pending-action ceiling is already full.
PilotCredentialRevokedErrorFenwild no longer accepts the token because it was revoked or expired, while connected or at a reconnect; start again with a new token only.
PilotControlSupersededErrorAuthority replaced this character’s control; the pilot stopped instead of reconnecting into that replacement. Bots on sibling characters run independently.
PilotDisconnectedErrorThe connection ended before an operation could complete.
An ambiguous in-flight mutation may already have settled. Restart from a fresh observation and do not replay it blindly.
Bounded local evidence
PilotRecorderIn-memory bounded PilotRecordingSink with snapshot() and clear().
PilotRecordingVersioned document containing ordered owner-visible recording entries.
PilotRecordingEventObservation, intent, outcome, Trading Post, market-tape or reserved event-batch entry.
PilotRecordingSinkInterface for an owner-controlled recording destination.
PilotReplayFrameReconstructed observation with market, history and recent outcomes; its event list stays empty today.
PILOT_RECORDING_VERSIONCurrent recording document version.
Local learning and artifact contracts
These functions perform no network or server work. The versioned action candidates remain exact PlayerIntentAction values, and every live result still runs through normal pilot authority.
projectPilotTrainingObservation(observation)Build an identity-minimized learning input from an ordinary player snapshot.
createPilotTrainingDatasetFromRecording(recording, options)Convert only authority-confirmed local demonstrations into a versioned dataset.
mergePilotTrainingDatasets(datasets, options)Combine independent journey-level splits while rejecting duplicate scenario and frame IDs.
trainPilotModel(dataset, options?)Fit the deterministic bounded multiclass linear-softmax reference model on local CPU.
evaluatePilotModel(model, dataset, options?)Report accuracy, per-label results, and confusion evidence for one split or the full corpus.
predictPilotAction(model, observation, candidates?)Score the supplied candidates (the reference set by default) by learned action type and return the best one. Candidates are parse-checked, not legality-checked.
referencePilotCandidates(observation)The public baseline candidates: observe, the best-fitting carried heal, below half HP a rest inside the character's own Bank or the trip there, enable run, loot visible ground items, gather ready resources, or attack the nearest living NPC.
referencePilotTeacher(observation)The deliberately simple default teacher that collect uses without --teacher.
createTrainedPilotBrain(model)Load an artifact as a normal PilotBrain for runPilot; it chooses among referencePilotCandidates.
loadPilotTrainingDataset(input)Fail closed while loading a versioned dataset document.
loadPilotModelArtifact(input)Fail closed on incompatible features, labels, weights, versions, or metadata.
loadPilotBenchmarkManifest(input)Validate public benchmark identity, thresholds, and reference reports.
Primary training types and limits
PilotTrainingObservationPilotTrainingDatasetPilotTrainingFramePilotTrainingManifestPilotTrainingScenarioPilotModelArtifactPilotEvaluationReportPilotBenchmarkManifestPilotTrainingOptionsRecordingDatasetOptionsMergeTrainingDatasetOptionsPILOT_TRAINING_MAX_FRAMESPILOT_TRAINING_MAX_COMPUTE_UNITSToken management for trusted interfaces
Running bots need only their issued automation token. These helpers require a separate browser-session credential and exist for trusted owner interfaces.
createAutomationToken(options, label)Create a named token from a trusted browser-owner interface and return its secret once; it expires after 365 days.
listAutomationTokens(options)List documented public token metadata for the owning character.
revokeAutomationToken(options, tokenId)Revoke a named token and terminate its live realtime access.
Lookups over canonical public facts
Map helpers accept authoritative signed world coordinates. Use FENWILD_GAME_DATA.area.origin with its width and height when iterating the grid; northern Mossmere rows have negative y values.
FENWILD_GAME_DATAThe complete versioned public reference document.
itemDefinition(itemId)Look up a public item and exact player-facing detail.
npcDefinition(npcId)Look up a public NPC definition and exact drop table.
serviceDefinition(serviceId)Look up a public service location and interaction range.
recipeDefinition(recipeId)Look up an Artifice recipe.
attackStyleDefinition(attackStyleId)Look up a combat style.
isKnownWalkable(position)Query a signed world coordinate against the public movement grid.
isKnownLineOfSightBlocked(position)Query a signed world coordinate against the public line-of-sight grid.
isKnownMovementEdgeBlocked(origin, target)Report whether one tile step would cross a closed barrier edge.
knownPathToward(origin, target, options?)Plan an advisory route with authority's movement rules; submit the final moveTo destination, not each step.
knownWildernessLevel(y)Derive the public Wilds level from a map row.
Primary data types
PilotGameDataPilotKnownPathPilotGameItemPilotGameItemDetailPilotGameNPCPilotGameServicePilotGameRecipePilotGameAttackStylePilotGameSpellPilotGamePrayerPilotGameRiskPilotGameObjectPilotGamePositionPilotGameAshShrinePilotGameFrontierResourceNodeObservations and actions share one protocol
The main entry point re-exports @fenwild/contracts, including PlayerWorldSnapshot, PlayerIntentAction, ActionReceipt, event, market, trading, friends, mutes and Masterwork Chronicle views, realtime message types, and protocol constants.
PilotObservationPilotSuccessPilotActionOutcomePilotHistorySnapshotPilotHistorySummaryPilotBrainPilotRunnerCallbacksPilotStatusPilotTraceEntryPilotSocketFactory