Five public entry points
@fenwild/bot-sdkRuntime and contracts
Connection, runner, client, actions, outcomes, recording, owner helpers, errors, and all re-exported public protocol types.
@fenwild/bot-sdk/game-dataStable world reference
Versioned content, map facts, lookup helpers, and the types that describe them.
@fenwild/bot-sdk/brainsReference brains
Small readable policies for survival, safe-yard training, gathering and careful fighting that can be composed into an independent bot.
@fenwild/bot-sdk/browserBrowser session renewal
SessionRenewal without the bot runtime, for pages that keep a game session alive. The realtime server accepts browser connections only from play.fenwild.com pages.
@fenwild/bot-sdk/trainingOffline brain forge
Identity-minimized datasets, deterministic training, held-out evaluation, benchmarks, artifacts, and local brain execution.
Choose the level of control
runBot
runBot(options, brain, callbacks?): Promise<void>Runs the supervised one-observation, one-decision loop and owns connection cleanup.
connectBot
connectBot(options): Promise<FenwildBot>Connects the lower-level client for custom coordination across observations and auxiliary feeds.
parseBotAction
parseBotAction(input: unknown): PlayerIntentActionRuntime-checks unknown input and returns a fresh exact public action.
summarizeHistory
summarizeHistory(history): BotHistorySummary | undefinedProjects a bounded owner-history snapshot into stable aggregate strategy context.
loadBotRecording
loadBotRecording(input): BotRecordingValidates and loads a versioned recording document.
replayBotRecording
replayBotRecording(input): AsyncGenerator<BotReplayFrame>Reconstructs the context available at each recorded observation without contacting the server.
Observation helpers
self(observation)The bot's own player.
combatLevel(skills, floor?)Combat level from skill stacks or a level map, as the game shows it.
xpToNext(observation, skill)XP still needed for the next level of a skill; 0 at level 99.
nearest(observation, kind | test)The closest living NPC in the bot's area of a kind, such as trainer or monster, or that a test function accepts.
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 15 seconds.
maxPendingActionsnumberLocal pending ceiling up to the authoritative maximum of eight.
reconnectbooleanEnabled by default: startup retries (up to 45 seconds for an unreachable or restarting server, three for a busy character) and recovery after an established session drops. A revoked or expired credential, an explicit control_superseded close or an idle_logout always ends the bot.
reconnectInitialDelayMsnumberInitial recovery backoff delay.
reconnectMaxDelayMsnumberMaximum recovery backoff delay.
traceCapacitynumberBounded credential-redacted trace capacity.
actionHistoryCapacitynumberBounded recent action-outcome capacity.
recordingSinkBotRecordingSinkReceives owner-visible recording events.
fetchtypeof fetchCustom HTTP adapter for scoped POST /auth/session/renew. Defaults to global fetch; separate from socketFactory.
socketFactoryBotSocketFactoryCustom standards-compatible WebSocket adapter.
onStatus(status) => voidReceives each change to connected, reconnecting or closed; a new bot is connecting, which status() reports, until its first connection.
onError(error) => voidReceives protocol errors from Fenwild, including the revoked, superseded or idle-logout verdict that ends a bot, 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 runBot is brain(observation, bot). Return one action or undefined, synchronously or asynchronously. The optional third argument contains these callbacks:
onActionRejected({ bot, observation, action, error })Handle a correlated authority rejection, then continue from later observations. Without this callback, the rejection stops the runner.
onActionInterrupted({ bot, 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, an idle_logout 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 runBot. 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.
character()The character this session started as, its id and hometown, from its first observation.
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. 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 → BotSuccessResolve with correlation fields plus any receipt or action-specific view: market, friends, mutes or weaponChronicle.
Errors preserve what authority actually knows
BotActionValidationErrorThe proposed action does not match an exact public action variant, or is an attack sent before any observation names the character's attack style.
BotProtocolErrorAuthority rejected the action, for example as stale_intent, refused the connection, for example as character_in_use, or the recognized protocol message was invalid.
BotActionUnknownErrorAn in-flight action lost authoritative confirmation and must not be replayed blindly.
BotBackpressureErrorThe configured pending-action ceiling is already full.
BotCredentialRevokedErrorFenwild no longer accepts the token because it was revoked or expired, while connected or at a reconnect; start again with a new token only.
BotControlSupersededErrorAuthority replaced this character’s control; the bot stopped instead of reconnecting into that replacement. Bots on sibling characters run independently.
BotIdleLogoutErrorA full world logged this character out after 30 minutes AFK to make room; the bot stopped instead of reconnecting into the slot it gave up.
BotDisconnectedErrorThe connection ended before an operation could complete, or startup failed; a startup failure names the URL and the HTTP status or network error.
An ambiguous in-flight mutation may already have settled. Restart from a fresh observation and do not replay it blindly.
Bounded local evidence
BotRecorderIn-memory bounded BotRecordingSink with snapshot() and clear().
BotRecordingVersioned document containing ordered owner-visible recording entries.
BotRecordingEventObservation, intent, outcome, Trading Post, market-tape or reserved event-batch entry.
BotRecordingSinkInterface for an owner-controlled recording destination.
BotReplayFrameReconstructed observation with market, history and recent outcomes; its event list stays empty today.
BOT_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 bot authority.
projectBotTrainingObservation(observation)Build an identity-minimized learning input from an ordinary player snapshot.
createBotTrainingDatasetFromRecording(recording, options)Convert only authority-confirmed local demonstrations into a versioned dataset.
mergeBotTrainingDatasets(datasets, options)Combine independent journey-level splits while rejecting duplicate scenario and frame IDs.
trainBotModel(dataset, options?)Fit the deterministic bounded multiclass linear-softmax reference model on local CPU.
evaluateBotModel(model, dataset, options?)Report accuracy, per-label results, and confusion evidence for one split or the full corpus.
predictBotAction(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.
referenceBotCandidates(observation)The public baseline candidates: observe, the best-fitting carried heal, below half HP the trip to the character's own Bank (inside it, observing in place heals faster), enable run, loot visible ground items, gather ready resources, or attack the nearest living NPC.
referenceBotTeacher(observation)The deliberately simple default teacher that collect uses without --teacher.
createTrainedBotBrain(model)Load an artifact as a normal BotBrain for runBot; it chooses among referenceBotCandidates.
loadBotTrainingDataset(input)Fail closed while loading a versioned dataset document.
loadBotModelArtifact(input)Fail closed on incompatible features, labels, weights, versions, or metadata.
loadBotBenchmarkManifest(input)Validate public benchmark identity, thresholds, and reference reports.
Primary training types and limits
BotTrainingObservationBotTrainingDatasetBotTrainingFrameBotTrainingManifestBotTrainingScenarioBotModelArtifactBotEvaluationReportBotBenchmarkManifestBotTrainingOptionsRecordingDatasetOptionsMergeTrainingDatasetOptionsBOT_TRAINING_MAX_FRAMESBOT_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.
myService(observation, role)The character's own hometown service for a role such as bank: the one the server lets it use.
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 fence or a low wall.
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
BotGameDataBotGameHometownBotGameServiceRoleBotKnownPathBotGameItemBotGameItemDetailBotGameNPCBotGameServiceBotGameRecipeBotGameAttackStyleBotGameSpellBotGamePrayerBotGameRiskBotGameObjectBotGamePositionBotGameAshShrineBotGameFrontierResourceNodeObservations 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.
BotObservationBotCharacterBotSuccessBotActionOutcomeBotHistorySnapshotBotHistorySummaryBotBrainBotRunnerCallbacksBotStatusBotTraceEntryBotSocketFactory