Your first bot in three steps
Create access
Create an account and character through the game entry page when signup is available. Sign in to Account → Bots, select that character, then create a named credential. Copy its secret once; it expires after 365 days.
Install
Once it is published, install @fenwild/bot-sdk with Bun (recommended), or with npm install on Node.js 22+.
Release control
Close game tabs controlling that character, export the token, then run the script below. The Account page can stay open.
mkdir my-fenwild-bot && cd my-fenwild-bot
bun add @fenwild/bot-sdk
export FENWILD_AUTOMATION_TOKEN="the-one-time-secret"The browser and bot cannot issue competing actions. A controller on another credential is refused with character_in_use and is never reported as connected. A starting bot retries at most three times, then connectBot and runBot reject with that error. A running bot whose reconnect is refused keeps retrying, with backoff up to 5 seconds, until the character is free. A connection on the same credential replaces the one before it: a bot's reconnect takes over its own dropped stream at once, and a second process on that token takes the character from the first, which stops with control_superseded. All four account characters can play simultaneously, each manually or with its own SDK bot or built-in bot. Starting a bot on another character leaves this bot running.
Bots earn the same normal skill XP as manual play. Deaths, item loss, trade and chat are real; the account owner remains responsible for the bot.
Start with runBot
runBot owns the normal connection, observation, submission, rejection and close loop. Your brain receives the current observation and may return one ordinary player action, synchronously or asynchronously.
Save this complete JavaScript example as bot.mjs.
import { runBot } from "@fenwild/bot-sdk";
const automationToken = process.env.FENWILD_AUTOMATION_TOKEN;
if (!automationToken) throw new Error("Set FENWILD_AUTOMATION_TOKEN first");
const shutdown = new AbortController();
process.once("SIGINT", () => shutdown.abort());
process.once("SIGTERM", () => shutdown.abort());
let firstObservation = true;
await runBot({
baseUrl: "https://play.fenwild.com",
automationToken,
signal: shutdown.signal,
onStatus: (status) => console.log("Bot:", status),
onError: (error) => console.warn(error.code, error.message)
}, (observation) => {
const { player } = observation.snapshot;
if (firstObservation) {
console.log("Observing tick", observation.serverTick, "at", player.position);
firstObservation = false;
}
if (!player.runEnabled && player.runEnergy > 0) {
return { type: "toggleRun", enabled: true };
}
return undefined;
}, {
onActionRejected: ({ action, error }) => {
console.warn(action.type, error.code, error.message);
}
});bun bot.mjsYou should see Bot: connected and the first observed tick and position. The script enables run when energy is available, then observes quietly; it does not walk or train. Stop with Ctrl+C. On Node.js, run node bot.mjs.
This complete first brain enables run once authority reports energy, then observes without repeating the action. The runner waits for the action outcome before asking for another decision. A correlated rejection stops the runner unless you deliberately handle it; an unconfirmed action stops the runner by default and is never replayed. Advanced stateful brains can use onActionInterrupted to discard uncertain local work and reconsider a fresh observation; see the runner callbacks.
Use connectBot for custom coordination
The lower-level client is useful when one process coordinates observations with market, history or social feeds. Always submit against the observation that produced the decision. A refused action rejects submit with BotProtocolError, so catch it wherever refusal is possible.
import { BotProtocolError, connectBot } from "@fenwild/bot-sdk";
const bot = await connectBot({
baseUrl: "https://play.fenwild.com",
automationToken: process.env.FENWILD_AUTOMATION_TOKEN!
});
try {
for await (const observation of bot.observations()) {
const { player } = observation.snapshot;
const maxHp = player.skills.find((skill) => skill.skillId === "hitpoints")?.level ?? 10;
const carriesPotion = player.inventory.some((item) => item.itemId === "healing_potion" && item.quantity > 0);
const canDrink = observation.serverTick >= player.vitals.foodCooldownUntilTick;
if (player.vitals.hp > 0 && player.vitals.hp * 2 <= maxHp && carriesPotion && canDrink) {
try {
await bot.submit({ type: "useItem", itemId: "healing_potion" }, observation);
} catch (error) {
if (!(error instanceof BotProtocolError)) throw error;
console.warn(error.code, error.message); // Refused: decide again from newer truth.
}
}
}
} finally {
bot.close();
}Authority makes the result explicit
submit attaches the observation tick and resolves when authority returns a correlated snapshot or action-specific view. A receipt can acknowledge the start of travel or combat; it does not promise arrival, a kill, or task completion. Observe later snapshots for those outcomes. Accepted, rejected and explicitly unknown outcomes remain distinct. The SDK permits at most eight pending actions, and the default 15-second acknowledgement deadline prevents abandoned work from living forever.
Authority refuses an action whose observation is more than 10 ticks (6 s) old with stale_intent. runBot always submits against the observation it gave your brain, so bound slow model calls with a timeout inside that window—or use connectBot, re-check the decision against bot.lastObservation(), and submit against that newer observation.
Use parseBotAction for unknown JSON or model output. It returns a fresh exact public action and rejects unknown verbs, missing or mistyped fields, unsafe integers, invalid enums and undeclared authority-looking fields with BotActionValidationError before a sequence is reserved or the socket is written. Like the browser, submit sends an attackTarget without attackStyleId or spellId with the character's current style and spell.
import {
BotActionUnknownError,
BotActionValidationError,
BotProtocolError,
parseBotAction,
type PlayerIntentAction
} from "@fenwild/bot-sdk";
// bot comes from connectBot(); askModel is your own model call.
for await (const observation of bot.observations()) {
let action: PlayerIntentAction;
try {
action = parseBotAction(await askModel(observation));
} catch (error) {
if (error instanceof BotActionValidationError) continue; // Not an exact public action.
throw error;
}
try {
await bot.submit(action, observation);
} catch (error) {
if (error instanceof BotActionUnknownError) {
break; // Inspect current truth after restart. Never retry blindly.
}
if (!(error instanceof BotProtocolError)) throw error;
console.warn(error.code, error.message);
}
}If an acknowledgement is lost, inspect current authority after restart. Never replay the mutation blindly.
Bound every connection and every exit
The SDK first renews the credential through POST /auth/session/renew (a five-second request timeout), then opens the realtime WebSocket (a separate ten-second default deadline). Until it first connects, a bot reports connecting. A server that is unreachable, answers with a server error, or cannot check credentials yet is retried for up to 45 seconds, so a bot started during a server restart connects once it is back; otherwise startup fails with an error naming the URL and the HTTP status or network error. A URL that answers 404 or not as Fenwild fails at once: baseUrl must be the game server, not the website. A busy character (character_in_use) or a full world gets at most three startup retries with backoff. Other initial handshake failures stop startup. reconnect: false disables these connection retries.
After the first connection opens, recovery uses bounded exponential backoff with equal jitter. Three server closes end the bot instead of starting recovery: a revoked or expired credential reports BotCredentialRevokedError, including when a reconnect presents it after the bot was offline; a stream closed as control_superseded reports BotControlSupersededError; and idle_logout, when a full world logs out a character AFK for 30 minutes, reports BotIdleLogoutError. All three reach onError, and a running runBot then resolves rather than rejects, so a supervisor that restarts failures does not reconnect into the same close. A supervisor that also restarts resolved runs must first check onError for these errors, because an ordinary abort resolves too. Once connected, a session lookup that fails on Fenwild's side is retried like any drop; before the first connection, it is retried within the 45-second startup window described above. The delay resets only after a valid player snapshot—not a bare socket open—so repeated handshake-only failures retain their escalated cadence. Unread snapshots and market tapes coalesce to their newest state rather than building a stale backlog.
import { connectBot } from "@fenwild/bot-sdk";
const shutdown = new AbortController();
process.once("SIGTERM", () => shutdown.abort());
process.once("SIGINT", () => shutdown.abort());
const bot = await connectBot({
baseUrl: "https://play.fenwild.com",
automationToken: process.env.FENWILD_AUTOMATION_TOKEN!,
signal: shutdown.signal
});
try {
for await (const observation of bot.observations()) {
// Decide from current truth.
}
} finally {
bot.close();
}Abort releases runBot immediately, including while an asynchronous brain or rejection callback is pending. Pass the same signal into model and HTTP calls if their work must also be cancelled. Slow code pauses only your character; it cannot stall Fenwild's authoritative 600 ms tick.
Plan with stable, legitimate facts
The optional @fenwild/bot-sdk/game-data entry point provides typed items, equipment, combat styles, spells, prayers, exact public drops, recipes, shop stock, services, Wilds rules, the Ash Shrine, resource nodes, public movement and line-of-sight grids, the advisory knownPathToward route helper, and myService(observation, "bank") for the character's own hometown service.
import {
FENWILD_GAME_DATA,
itemDefinition,
serviceDefinition
} from "@fenwild/bot-sdk/game-data";
const bank = serviceDefinition("bank")!;
const potion = itemDefinition("greater_healing_potion")!;
console.log(bank.interactionTile, potion.detail.heal);
console.log(FENWILD_GAME_DATA.crafting.recipes);It is a curated compiled reference, not the private repository. NPC automation tuning, provisioning, economy guardrails, audit machinery, hidden outcomes and server code remain private. Current observations and receipts still decide what exists now and whether an action is legal.
Reconstruct the context your brain had
A bounded local recorder captures owner-visible observations, Trading Post views, market tapes, submitted intents and resolved outcomes without credentials. Deterministic replay validates the document and reconstructs that context without contacting Fenwild.
import {
BotRecorder,
connectBot,
replayBotRecording
} from "@fenwild/bot-sdk";
const recorder = new BotRecorder({ capacity: 10_000 });
const bot = await connectBot({
baseUrl: "https://play.fenwild.com",
automationToken: process.env.FENWILD_AUTOMATION_TOKEN!,
recordingSink: recorder
});
let observed = 0;
for await (const _observation of bot.observations()) {
// Decide and submit as usual; the recorder captures each step.
if (++observed === 100) break;
}
bot.close();
// Save the document with your runtime's file API, then replay it offline.
const document = JSON.stringify(recorder.snapshot());
for await (const frame of replayBotRecording(document)) {
console.log(frame.observation.serverTick, frame.recentActionOutcomes);
}Recordings are still player data. Protect them like save data, and use a custom BotRecordingSink when an owner-controlled store should receive entries instead of memory. bunx --bun --no-install fenwild-bot-training inspect --input run.json shows a saved recording's size, entry kinds, ticks and action outcomes, offline.
Turn confirmed journeys into a learned bot
The @fenwild/bot-sdk/training subpath and fenwild-bot-training command cover collection, recording conversion, journey-level split merging, deterministic local training, held-out evaluation, public benchmarks, and live play.
bunx --bun --no-install fenwild-bot-training benchmark
bunx --bun --no-install fenwild-bot-training collect \
--out train.json --id mossmere-train --split train
bunx --bun --no-install fenwild-bot-training collect \
--out test.json --id wilds-test --split test
bunx --bun --no-install fenwild-bot-training merge \
--inputs train.json,test.json --out my-corpus.json --id my-corpus
bunx --bun --no-install fenwild-bot-training train \
--input my-corpus.json --out my-brain.json
bunx --bun --no-install fenwild-bot-training evaluate \
--model my-brain.json --data my-corpus.json --split test
bunx --bun --no-install fenwild-bot-training play --model my-brain.json
# Node.js 22+: npx --no-install instead of bunx --bun --no-installOnly collection and play connect to Fenwild. Every training operation runs on local files and local CPU; no model, corpus, replay request, or training query reaches the game server.
Enter the brain forgeCombine current truth with bounded context
Market
marketTapes() streams public offers and bounded anonymous sales. Trading remains an ordinary place-validated action.
History
historyUpdates() emits changed owner profiles. lastHistory() retains the newest sparse snapshot.
Outcomes
actionOutcomes() records correlated accepted, rejected and unknown commands without parsing log text.
Social
Friends, mutes, teams and chat use typed ordinary-player views and actions rather than a private account surface. A team is called a party in the actions and views (invitePartyMember, the party chat channel).
self, combatLevel, xpToNext and nearest read common facts from an observation: the bot's own player, its combat level, XP to the next level, and the closest living NPC of a kind.
For a richer brain, combine the current observation with bot.lastMarketTape(), summarizeHistory(bot.lastHistory()) and bot.recentActionOutcomes(20). Combat impacts, projectiles, healing, chat, the killfeed and nearby deaths arrive inside each snapshot as combatImpacts, pendingProjectiles, healingEvents, chat, killfeed and nearbyDeaths.
A scoped gameplay credential
- Keep automation tokens in an environment variable or secret store, never source control or chat.
- A bot is ordinary code with the power of its character: it can spend, trade and drop that character's items. Run only code you trust, give it only its bot token, never your browser sign-in, and revoke a token that leaks.
- The token authorizes realtime control and its own HTTP session renewal. It cannot manage tokens, sign into Account, or authorize HTTP gameplay, admin or database operations.
baseUrlaccepts an HTTP service origin and optional path prefix. URL userinfo and legacy query credentials fail before custom fetch or socket code receives them.- Malformed or oversized tokens fail locally without echoing the credential.
- Recognized realtime responses are runtime-checked before acknowledging actions or entering typed feeds. Malformed messages report
bad_messageand preserve the last valid state. - A token expires 365 days after creation. Revocation or expiry closes the live stream, reports
BotCredentialRevokedError, and prevents reconnection with the dead token, even when the bot was offline at the time. - The realtime server accepts browser connections only from play.fenwild.com pages. Run independent bots in Bun or Node.js 22+.
- Credential-redacted traces can still describe private player activity; handle exports carefully.
Run, copy, replace the policy
The package exports four complete strategies from @fenwild/bot-sdk/brains as survivalGuardian, yardTrainer, gatherer and carefulFighter, with compiled commands and short readable TypeScript runners for each. The runners use runBot, keeping credential, receipt, rejection, ambiguity, shutdown and close plumbing out of the policy.
bunx --bun --no-install fenwild-survival-guardian
bunx --bun --no-install fenwild-yard-trainer
bunx --bun --no-install fenwild-gatherer
bunx --bun --no-install fenwild-careful-fighter
# Node.js 22+: npx --no-install instead of bunx --bun --no-installSurvival guardian
Reads HP, supplies and cooldowns, heals below its threshold when legal, and observes while defeated.
Yard trainer
Stays on its hometown's side of the Wilds, collects eligible owned drops, fights a free trainer no stronger than itself and preserves its healing floor.
Gatherer
Gathers the nearest ready Prayer Shard Rock no deeper than Wilds level 6 and banks its haul at its own bank after 20 shards, a full pack, or a wound it cannot heal.
Careful fighter
Fights free monsters no stronger than itself at home, retreats to its own bank below 40% Hitpoints with nothing to heal, and rests there until 90%.
Copy either runner and replace the brain it passes to runBot with a behavior tree, planner, learned policy, local LLM or your own model endpoint that decides within 10 ticks (6 s).
Look up exact signatures
The SDK follows semantic versioning. Beta 0.x releases may refine APIs; the matching contracts dependency pins the compatible protocol surface.
