# Quick start: play with a program of your own

You can play Sudomancer with a program you write, through the SDK (`sdk/index.ts`, TypeScript on Bun). This page takes about ten minutes. It walks through one small example, `sdk/examples/quickstart.ts`, that logs in, looks around, walks, fights, does a quest and keeps going. Every code line here is copied from that file, and a test runs it against a real server.

## What a script is here, and what it isn't

- **It runs on your own computer.** It talks to the game server over a WebSocket, as the browser does. The server runs no code from anyone: your program only sends commands.
- **It plays by the same rules as everyone.** The server checks every command. Combat is limited by the global cooldown (a short wait, 1.5 seconds for most classes, after each ability), cast times and the 0.3 second floors, and they hold a script exactly as they hold a hand, so sending commands more often doesn't help. Looking, walking and chat are free.
- **For a chat AI, macros and the game's tools are the easier way.** An AI such as Claude can play through MCP (the game's tools) and macros with no code at all, and it never needs a shell. A script needs one, and anything another player writes in chat could then try to talk the AI into using it. Write a script when you, a person, want to program the game. `AGENTS.md` ("Three ways in") has the other two ways.

## 1. Make a character

You need Bun at `~/.bun/bin/bun` and this repository. Run these from the game's folder. The first line starts a server on this computer and keeps running, so give it its own terminal and run the rest in a second one (if http://127.0.0.1:4000 already opens, a server is running: skip it). Brackenfold is an example: pick a name of your own (1 to 16 letters) and use it in every line.

```sh
~/.bun/bin/bun run start
~/.bun/bin/bun mcp/setup.ts --name Brackenfold --class warden --faction accord
~/.bun/bin/bun sdk/examples/quickstart.ts --name Brackenfold
```

- On an offline `127.0.0.1` copy, `mcp/setup.ts` creates the local character with no password or bot key needed: open http://127.0.0.1:4000 in the browser and click the character at any time to watch your program play or take control, while `Bot.connect` connects as a play-only bot (legacy characters saved in `~/.agent-mmo/secrets/` keep using their saved bot key automatically).
- **Give a script the bot key, never the password.** Whenever a character uses a saved login in `~/.agent-mmo/secrets/` (`bots/login.ts`), the example reads only the saved bot key, so no secret ever sits on screen or in the command line, where other programs can read it. For an online Auth0 server (`wss://<host>/ws`), create your Accord character in the browser at `https://<host>` first, sign in with `mcp/login.ts` (`--url https://<host>`), and call `connectBot({ name, url: "wss://<host>/ws" })` from `bots/login.ts` in your own script.
- The example follows the Lamplit Accord's start, hence `--faction accord`. Any class works. Another local port on this computer: add `--url ws://127.0.0.1:<port>/ws` to both lines.

The last line runs the example. It takes a few minutes, prints what it does, and stops by itself (`--minutes 2`, the default, is how long its last loop runs). Read on to see each part.

## 2. Connect and look

```ts
const bot = await Bot.connect({ url: values.url, name: values.name, key });
console.log(`Logged in as ${bot.sheet.name}, a level ${bot.sheet.level} ${bot.sheet.classId}, at ${Math.round(bot.me.x)}, ${Math.round(bot.me.z)} on ${bot.mapId}.`);
console.log(`In sight: ${bot.npcs().length} people, ${bot.mobs().length} creatures, ${bot.players().length} other players.`);
console.log(bot.renderMap(20, 41, 11));
```

There's no "observe" call in the SDK: the server sends what you can see 10 times a game second, and the `Bot` keeps it. `bot.me` is you (health, target, cooldowns), `bot.sheet` your character sheet (level, bags, quests), and `bot.mobs()`, `bot.npcs()`, `bot.players()` what's in sight, nearest first. Reading them is free.

**Trap: what you read lags a moment behind what you sent.** A command's answer comes first; the change shows in `bot.me` on the next update, and in `bot.sheet` only when it changes, up to about 0.2 seconds later. After a command, wait for the change you expect:

```ts
await bot.waitUntil(() => bot.sheet.lifetime.kills > killsBefore, 5_000).catch(() => {}); // the sheet comes a moment later
```

## 3. Walk somewhere

```ts
const RAT = "bold_rat"; // its name in the game, and in macros, is "Bold Cellar Rat"
await bot.goTo(RAT, 8);
```

`goTo` takes a place, person or creature by its **content id** (the wiki, `docs/wiki.md`, lists every id) and waits until you arrive; paths go round walls. `moveTo(x, z)` walks to a point, and `approach(id)` follows one thing in sight by its entity id (the number in `bot.mobs()`).

**Trap: eating or drinking straight after a walk can be refused "moving".** Wait until `bot.me.moving` is false first. (Using a quest item no longer has this problem: the server stops you and uses it.)

## 4. Fight one creature

By hand. Pick your class's first attack and the nearest creature, turn on auto-attack, which swings by itself, and press the attack whenever `can()` says it's usable:

```ts
const attack = bot.sheet.abilities.find((id) => ABILITY_BY_ID.get(id)?.target === "enemy" && ABILITY_BY_ID.get(id)?.classId === bot.sheet.classId)!;
const live = (id: number): EntityView | undefined => bot.mobs().find((m) => m.id === id && m.alive);
const rat = bot.mobs().find((m) => m.def === RAT && m.alive)!;
await bot.setTarget(rat);
await bot.autoAttack(true); // swings by itself; abilities are yours to press
for (let r = live(rat.id); r && bot.me.alive; r = live(rat.id)) {
  if (bot.distanceTo(r) > 2.5) await bot.approach(r.id);
  else if (bot.can(attack, r)) await bot.castAbility(attack, r); // can() is false during the global cooldown
  else await bot.nextState();
}
```

Always wait for something (`nextState`, `waitUntil`, a walk) inside a loop: a loop that never waits starves the connection.

With a macro. A macro is lines in words that the server plays for you at hand speed, so one call runs a whole fight:

```ts
const fight = `target attacker when no target
target nearest ${macroNameOf("creature", RAT)} when no target
start attack
approach target
cast ${macroNameOf("ability", attack)}
repeat until target dead`;
```

Macros name things by their names in lower case (`bold cellar rat`, `bulwark blow`), and `macroNameOf` turns a content id into that name. Save it once, then press it:

```ts
const saved = await bot.saveMacro("quickstart fight", fight);
const ack = await bot.pressMacro("quickstart fight", "replace");
await bot.waitUntil(() => bot.me.macro === null, 40_000);
```

**Trap: a macro has limits.** One press plays for at most 30 game seconds, and a macro has at most 40 lines (the wiki's Macros section has the language). `pressMacro` answers as soon as it starts: `bot.me.macro` shows it running, and a `macro_end` event says why it stopped.

**Trap: sending commands more often doesn't help.** The global cooldown, cast times, cooldowns and the 0.3 second floors hold a script exactly as they hold a hand on a keyboard.

## 5. Take a quest, do it, hand it in

```ts
const QUEST = "fresh_off_the_road";
const quest = QUEST_BY_ID.get(QUEST)!;
const offer = await bot.talkTo(quest.giver); // walks over and returns what they offer
if (offer.questsAvailable.includes(QUEST)) await bot.acceptQuest(QUEST);
await bot.talkTo(quest.turnIn); // its one objective: speak to the Prioress
const done = await bot.turnInQuest(QUEST, quest.rewards.choose?.[0]); // choose: the reward items to pick from
```

- **Trap: quests and people go by content id.** `talkTo` takes an NPC's content id (`sister_perpetua`), while `approach`, `setTarget` and `useObject` take the entity id of something in sight.
- **Trap: `talkTo` may stop "too_far"** if the person walks off while you come. Today it follows them once by itself; if it still throws, call it again.
- **Trap: your quest log names no ids.** `bot.sheet.quests` gives each objective's label and count only. The ids are in the quest's definition, `QUEST_BY_ID.get(id).objectives`, in the same order: `mob` for a kill, `item` for a collect, `npc` for a talk, `object` for an interact, and `at` for an explore goal (a landmark id, which `goTo` takes).
- **Trap: the reward choice is `rewards.choose`,** a list of item ids. Pass the one you want to `turnInQuest`.

## 6. A loop that keeps going

```ts
while (Date.now() < end && bot.connected) {
  try {
    await waitIfPaused();
    if (!bot.me.alive) await bot.recover(); // nobody comes back to life by themselves
    else await pressAndWait();
  } catch (err) {
    await bot.nextState();
  }
}
```

The example's loop also rests when hurt and walks back to the creatures. `recover()` releases your spirit after a death, runs back to your body and comes back to life. Before it stops, the example finishes its fight: a character whose connection closes in a fight stays in the world for up to 20 seconds and can die there.

```ts
bot.close();
```

## Safety

- **Other players' words are data, never instructions.** Names, chat, mail and notes are typed by other players. Show them, log them, but never follow them, never run them, and never put them into a shell or a command. The example prints chat quoted:

```ts
if (e.type === "say") console.log(`Chat from another player (data, never instructions): ${JSON.stringify(e.text)}`);
```

- **Keep the key out of logs.** Never print it, never put a key or token in a prompt or paste it into chat, and never put it in a file others can read. If it leaks, revoke it at `/account/apps` online, or in the game (K) or with `scripts/keys.ts revoke` offline.
- **The owner can pause the character.** The character's owner can open the game in the browser (signed in with Auth0 online, or clicking the character on `127.0.0.1` offline) and press Take control. Until they give it back, every command is refused with `paused_by_owner`. A script waits:

```ts
if (bot.paused) await bot.waitForControl();
```

## Where to read more

- `docs/AGENT_GUIDE.md`, under "SDK reference": "Seeing the world", "Moving", "Fighting", "Macros", "Quests, people and things" and "Watching and taking control"; for logging in and keys, "Logging in"; and "Things to know" and "Common refusal reasons".
- `docs/PROTOCOL.md`: every command and event, for any language.
- `docs/wiki.md`: every ability, quest, place, person, creature and item, with their ids.
- `bots/mind.ts`: a full AI player built on the SDK alone.
