Skip to main content

Talk to a character

The deck's client talks to playthrough characters through the Characters module of castle-web-sdk. Everything here happens for the signed-in player: each player has their own copy of each character.

import { Characters } from "castle-web-sdk";

let mara = await Characters.open("mara");

Characters.open(characterId)​

Characters.open starts the player's playthrough if it hasn't started yet, and returns a handle for one character in it:

  • generation: which playthrough this is. It starts at 1 and goes up each time the player resets.
  • definitionVersion: the version of the bundle this playthrough uses.
  • character: { id, version, name } from the bundle.
  • previewAllowance: what's left of the player's allowance today, as { utcDay, allowanceUnits, usedUnits, remainingUnits }. Each send reserves 4 units.

Opening a character doesn't run the model or use any allowance. The first open in a playthrough admits the player to every character in the bundle, so open at least one before the server records events for that player (see the server page), and again after a reset.

A handle belongs to one generation and never changes. After a reset, use the new handle that reset returns, or open the character again.

Sending a message​

send takes the player's text and an operation id you make up for this message. It returns at once, before the reply is written:

const operationId = crypto.randomUUID();
let op = await mara.send({ operationId, input: text });

input is 1 to 2,000 characters. An operation id is up to 120 characters. Keep the id until the reply has arrived: it's how you ask about this message again.

An operation has a status:

  • queued or running: the reply is on its way. Show a waiting state and ask again with status(operationId). While it's running, op.progress?.response can hold the reply so far. Show it as a draft and replace it with the final reply.
  • completed: op.result.response is the reply. If one of your beats fired, op.result.selectedBeat is { beatId, eventOccurrenceId }.
  • failed or interrupted: there's no reply. A failed send's op.result.error can say why, as { code, message }. The message is written for the player, so you can show it as is; when there is none, show a general message. Let the player try again. When a message fails before the character started on it, the allowance it reserved for the reply comes back. On decks where Castle checks what players say, that check still counts.
    • CAULDRON_CHARACTER_TURN_FAILED: the character couldn't answer. Sending again usually works.
    • CAULDRON_CHARACTER_BUSY: the character is still answering an earlier message. Try again in a moment.
    • CAULDRON_CHARACTER_CONVERSATION_FULL: the conversation is out of room. Offer a reset.
const DONE = new Set(["completed", "failed", "interrupted"]);

async function sendToMara(text) {
const operationId = crypto.randomUUID();
let op = await mara.send({ operationId, input: text });
const deadline = performance.now() + 120_000;
// A finished answer can come back without its result, so fetch it.
if (DONE.has(op.status) && op.result == null) op = await mara.status(operationId);
while (!DONE.has(op.status)) {
if (performance.now() > deadline) throw new Error("Still waiting for Mara.");
await new Promise((resolve) => setTimeout(resolve, 500));
op = await mara.status(operationId);
showDraft(op.progress?.response ?? "");
}
if (op.status !== "completed" || !op.result?.response) throw new Error(op.result?.error?.message ?? `Mara's reply ${op.status}.`);
return op.result.response;
}

When you don't hear back​

If send fails with a network error or a timeout, you can't tell whether Castle got the message. Don't send it again with a new id, because that would be a second message and use more allowance. Ask about the same id with status(operationId), or look for it in history(). Sending again with the same id and the same text is safe: Castle treats it as the same message.

Never send a message again into a new generation on the player's behalf. If the playthrough was reset while a message was in flight, put the text back in the input box and let the player decide.

History​

history returns the player's past messages with this character, newest first, a page at a time:

async function loadHistory(handle) {
const ops = [];
let cursor = null;
do {
const page = await handle.history({ limit: 50, cursor });
ops.push(...page.operations);
cursor = page.cursor;
} while (cursor);
return ops.filter((op) => op.status === "completed" && op.result?.response).reverse();
}

limit is 1 to 50. cursor is null on the last page. Show only completed operations that have a response, oldest first. Each one's result.input is what the player said. Very old operations can come back with archived: true and a shorter result, without the response.

Load the history each time the player opens a conversation, and show a loading state until it arrives.

Resetting the playthrough​

reset starts the player's whole playthrough over, for every character in the deck. Characters forget their conversations and what they learned, events are cleared, and so are the server's playthrough keys. It returns a handle in the new generation:

const resetId = crypto.randomUUID();
mara = await mara.reset(resetId);

If the reset fails with a network error, open the character again. If its generation went up, the reset happened, so use the new handle. If it didn't, call reset again on the old handle with the same id. After a reset, clear everything your deck kept about the old playthrough, open the other characters again, and ask the server for the new story state.

A reset doesn't give the player any allowance back.

Keeping the conversation straight​

  • Keep the character id and generation with each message that's waiting for a reply. A reply that arrives after the player switched characters or reset must not show up in the wrong conversation.
  • Turn off the input while a message is on its way.
  • A <form> may not submit inside the player's frame. Handle the send button's click and the Enter key yourself, and keep your game's movement keys from firing while the player types.

Errors​

An argument the SDK can check itself, such as empty input, text over 2,000 characters or a limit over 50, throws a TypeError before anything is sent. A call Castle refuses throws a CastleError. A message that was accepted but then failed doesn't throw: its operation ends failed with op.result.error (see Sending a message). For a refused call, check the CastleError's code:

  • CAULDRON_CHARACTER_UNAVAILABLE: characters can't be used right now. Characters aren't open for this deck or this player, the service is off, or the deck has used its daily limit. Show that talk isn't available and keep the game going.

  • CAULDRON_CHARACTER_BACKLOG_LIMIT: the player used up today's allowance, too much is waiting to be answered, or the deck has reached one of its limits. Show that the character can't talk right now. If it's the allowance, it comes back at midnight UTC.

  • CAULDRON_CHARACTER_NOT_FOUND: this deck's published bundle has no character with that id.

  • CAULDRON_CHARACTER_INVALID_ARGUMENT: Castle refused an argument, such as an unknown operation id. It's also what every send gets when the deck's bundle has a conversation block, which makes its characters shared characters.

  • CAULDRON_CHARACTER_CONFLICT: an operation id was used again with different text.

  • LOGIN_REQUIRED: the player has to sign in.

  • CAULDRON_STORAGE_STALE_GENERATION: the handle belongs to an earlier generation, because the playthrough was reset. Open the character again.