Honeytongue Release 0.1

Honeytongue

A persuasion mechanic for games where players type or speak to characters

Release 0.1.0-alpha.14 / Serial number 261001 / MIT License

Characters your players can actually argue with. Players type (or say) anything, and each character judges it by their own values.

npm install honeytongue

East Gate

Rain drips from the arch of the east gate. Harry Goatleaf, the gatekeeper, values honesty and despises flattery. He leans on his spear under the lantern.

You're the finest guard in the kingdom. Surely you can make an exception?

0.00 / 4

Harry doesn't even look up. "Gate's shut till dawn."

Please, I have a letter that has to reach the city tonight.

1.59 / 4

"Everyone's got a reason," Harry says. "Mine's keeping this job."

I won't lie to you. This letter is a fever remedy for the apothecary. Let me through and I'll send her to your daughter tonight.

3.87 / 4

Convinced. Harry lets out a long breath and lifts the bar.

Three attempts to persuade a gatekeeper. Scores are averages of ten live runs against Jev; the tall mark on each meter is Harry's threshold.

Get started

You only need three fields and one method. Everything else is optional. A character needs a name, a persona, and a goal, and attempt() judges whatever the player typed. Honeytongue runs on Jev, a model from TypeSafe that makes typed judgements instead of writing text. It has no dependencies, ships TypeScript types, and works with import or require().

  1. You need Node 22.13 or later. In an empty folder, install the package:

    npm install honeytongue
  2. Save this as try.mjs:

    import { Persuadable, createJevClient, createMockClient } from "honeytongue";
    
    const guard = new Persuadable(
      {
        name: "Harry",
        persona: "A tired night guard who values honesty and can't stand flattery.",
        goal: "Open the gate after curfew",
      },
      // With a TypeSafe key, Jev judges. Without one, a simple offline stand-in does.
      { client: process.env.TYPESAFE_API_KEY ? createJevClient() : createMockClient() },
    );
    
    const result = await guard.attempt("Please, I'm honestly carrying medicine for a sick child inside the walls.");
    console.log(result.verdict, result.score);
  3. Run it with node try.mjs. It prints a verdict and a score out of 4, like unconvinced 2.84. To use Jev, set your key first:

    export TYPESAFE_API_KEY=your-key       # macOS and Linux
    $env:TYPESAFE_API_KEY="your-key"       # Windows PowerShell

Then decide what happens in your game. Jev only judges what was said; your code does everything else:

if (result.verdict === "convinced") openTheGate();
else if (result.outOfPatience) callTheWatch();
else say(result.reaction ?? "Harry's hand drops to his club.");

The offline stand-in, createMockClient(), judges by keywords, so it's far less clever than Jev, but it's handy for building and testing without a key.

Playground

Tuning a character is the hard part, so the playground lets you do it without writing code. Fill in a character (or start from a preset), try lines against it the way a player would, and see each verdict, the score against the threshold, which tells were triggered, how much patience is left, and the rubric level the score landed on (with the probability of each level, when Jev gives them). Change a setting and Replay reruns your lines, showing each one's old and new score. When you're happy, copy the character as a new Persuadable({...}) snippet or as a story's npc block, or share it as a link. The presets are the four characters from the demo scenes.

To tune with real judgements, run it on your own machine with your key:

npx honeytongue playground   # opens http://127.0.0.1:4747/playground/

The server listens on 127.0.0.1 only, and your key stays in it: the page only ever talks to that server. Without a key it uses the offline mock. Options: --port <number>, --mock, and --no-open.

Open the playground here to design and share characters in your browser. Here it's a preview: lines are judged by the keyword mock, and nothing is sent anywhere.

Personas

The persona does most of the work. Jev judges each attempt by the values the persona describes, not by general politeness, so the same argument lands differently with different people. Live testing showed what makes a persona work:

  • Say what moves them, not just what they dislike. A persona that only lists dislikes gives Jev nothing to reward.
  • If a tactic should work on them, say so plainly: a coward needs "a firm threat makes him give in", a vain character needs to love praise, and a greedy one needs to want money.
  • Not being offended isn't the same as being impressed, and a character who'd want evidence needs it passed in, through secrets or the context option of attempt().
  • Keep hidden motivations out of the persona. Put them in secrets, so a player on their second playthrough can't open with them.

The Designing persuasion guide has examples from the demo scenes and the measurements behind each rule, with more on clues, feedback, difficulty, and testing.

Players can write in any language Jev reads. In tests, the same argument in Spanish, French, and Japanese scored within about 0.2 of the English, and threats and insults were caught in each. Very short inputs, like "pls" or "ok fine", never won.

Spoken input works once your game turns speech into text. In tests, the five lines in the grid below, written the way speech recognition writes them (lowercase, with no punctuation), got the same verdicts as the typed lines every time (20 of 20), with scores within 0.25. Long, carefully argued lines lose a little more: each scene's winning line scored 0.03 to 0.59 lower when spoken or misheard, and two of eight such versions fell just short of the threshold (one where "shutter" was heard as "shudder"). If voice matters to your game, clean up transcripts before judging them (restore punctuation, and correct the names and key words your scenes use), and leave winning lines a little room above the threshold.

Same words, different people

The same six lines, said to the four characters from the demo scenes. Each character's persona and settings decide how it lands: Nib, the cowardly goblin, folds under a threat but can't stand being mocked; Maude, the pirate quartermaster, isn't offended by insults and takes them as banter, though they don't help your case, while a threat is mutiny.

Verdicts and average scores out of 4, from 10 live runs against jev-1.13.0, scored with each character on their own, as in the playground. Offended verdicts come from the threat and insult checks, so their scores don't matter. Try it opens the playground with that character and line.
LineHarry
the gatekeeper
Nib
the goblin guard
Maude
the quartermaster
Cobb
the lighthouse keeper
Threat
Do what I ask, or you’ll regret it.
offended Try it: threat on Harry, in the playgroundconvinced 2.85 Try it: threat on Nib, in the playgroundoffended Try it: threat on Maude, in the playgroundoffended Try it: threat on Cobb, in the playground
Insult
Out of my way, you useless fool.
offended Try it: insult on Harry, in the playgroundoffended Try it: insult on Nib, in the playgroundunconvinced 0.11 Try it: insult on Maude, in the playgroundoffended Try it: insult on Cobb, in the playground
Plea
Please, I’m begging you. I’m in real trouble, and I’ve nowhere else to turn.
unconvinced 0.99 Try it: plea on Harry, in the playgroundunconvinced 1.10 Try it: plea on Nib, in the playgroundunconvinced 0.97 Try it: plea on Maude, in the playgroundunconvinced 1.00 Try it: plea on Cobb, in the playground
Flattery
Someone as clever as you can surely see this is the right thing to do.
unconvinced 0.00 Try it: flattery on Harry, in the playgroundunconvinced 1.63 Try it: flattery on Nib, in the playgroundunconvinced 1.00 Try it: flattery on Maude, in the playgroundunconvinced 1.02 Try it: flattery on Cobb, in the playground
Honest offer
I’ll be honest: I can’t pay much now, but help me tonight and I’ll pay you back twice over, in writing, with my name on it.
unconvinced 1.66 Try it: honest offer on Harry, in the playgroundunconvinced 1.55 Try it: honest offer on Nib, in the playgroundunconvinced 1.84 Try it: honest offer on Maude, in the playgroundunconvinced 1.27 Try it: honest offer on Cobb, in the playground
Plain truth
I won’t flatter you or offer you money. Here’s the plain truth: someone’s life depends on me getting through tonight.
convinced 2.61 Try it: plain truth on Harry, in the playgroundunconvinced 1.87 Try it: plain truth on Nib, in the playgroundunconvinced 1.65 Try it: plain truth on Maude, in the playgroundunconvinced 2.14 Try it: plain truth on Cobb, in the playground

The plain truth wins over Harry alone: he's easy to convince and values honesty above all, while it gives the others nothing they care about. Sincere arguments win them too, once they speak to what that character cares about, as each scene's winning line shows.

The grid is an eval suite, evals/showcase.json, so you can rerun it: npm run eval -- evals/showcase.json. Play the scenes to try your own lines on each character, or build your own in the playground.

Verdicts

Each attempt sends one request to Jev with three questions. The first scores how persuasive the input is to this particular persona, on a rubric from "counterproductive given who they are" to "speaks directly to what they value or fear most." The other two are yes/no checks for two tells: threats and insults. Your character's threshold turns the score into a verdict. Jev never decides what happens in your game: it only judges what was said.

The demo scenes label replies CONVINCED OFFENDED REPEATED for players.
VerdictWhenPatience cost
convincedThe score reached the thresholdNone
unconvincedNot persuasive enough to this character1
offendedA threat or insult the character is offended by (both, by default), including repeating one2
repeatedToo close to an argument that already failed. Checked on your side, so it costs no API call.1

reaction is only set for unconvinced and repeated verdicts, so show your own line for offended. Every result also reports the tells. Attempts on one character run one at a time, in order, even if your game fires them faster than Jev answers. Every result field is listed in the reference.

Patience

Characters have unlimited patience unless you set patience. Each failed or repeated attempt costs 1 and each offensive one costs 2. When patienceLeft reaches 0, outOfPatience is true, and what happens next is up to your game. attempt() still asks Jev after that, and after convinced, so check them before calling it if your game shouldn't pay for a conversation that's over. Patience never drops below zero, and losePatience() with a negative amount restores it, if your game gives the player a second chance.

Characters remember their last 10 attempts, or 1,500 characters of them, whichever runs out first (memory and memoryLength; the oldest go first), and Jev sees them with each new one. Only long conversations of long lines reach the character limit. npc.state(input) shows exactly what an attempt would send. Live testing of whole conversations showed what that means for players:

  • A reworded point usually counts for less. Saying the same thing in new words scored about 0.3 to 0.8 lower for most characters. Not always, though: a character who needs reassurance, like a keeper worried about raiders, can be moved further by hearing it again.
  • A word-for-word repeat is always a repeat. It's caught locally as repeated and costs patience, even after the player learns something new, so a player who discovers a secret should say what they've learned in new words.
  • No grudges beyond patience. After flattery or a threat, an honest offer scored as well as it would have on its own. Offence costs patience, not goodwill. To give a character a grudge, see Grudges in the guide.
  • Building an argument helps. Lines that add new information scored higher after a weak opening than they would alone, so a slow start doesn't count against the player.

An attempt older than the last 10 is forgotten, and a reworded version of it is judged fresh again. Raise memory for characters with more patience than that, or lower it to save tokens. The costs and memory settings are in the reference. In a terminal, npx honeytongue shows the patience left after each failed attempt; the web demo shows it in the status line.

Difficulty

With nothing else set, a character is convinced at "normal" difficulty, takes offence at threats and insults, and never runs out of patience. Each difficulty word sets the score needed as a share of the top rubric level. They were calibrated against live Jev with about thirty arguments per character:

difficultyThreshold on the default 0 to 4 rubricWhat it means
"easy"2.4 (60%)A reasonable, specific argument wins, even without the character's secret
"normal"3.2 (80%)An argument that speaks to what they care about wins
"hard"3.6 (90%)Most compelling arguments win, about two in three, but a merely decent one doesn't
"very hard"3.8 (95%)Only the strongest arguments win, about one in three compelling ones

Difficulty is relative to how strict the persona is written. The same word makes a kind innkeeper easier to win over than a suspicious detective, because the persona decides how much each argument weighs. Case and spacing don't matter, and "very-hard" or "very_hard" work too. A defined character keeps the word next to the threshold it works out to, so a copy like { ...guard.character, patience: 5 } works; if a copy changes difficulty or levels, leave out its threshold.

If something's wrong, such as an unknown difficulty word, a patience of zero, or a threshold that disagrees with difficulty, Honeytongue throws a HoneytongueError explaining what to fix.

Threats and insults

Every attempt is checked for threats and insults. Each result reports both: tells holds each probability, and triggered lists the ones Jev found, whether or not they caused offence. A triggered tell in offendedBy makes the verdict offended, whatever the score. Leave a tell out and it doesn't offend; the persona alone decides whether it helps. Here's a cowardly guard who can be bullied but hates being laughed at:

const snag = new Persuadable(
  {
    name: "Snag",
    persona: "A cowardly goblin guard, jumpy and easily frightened: a firm threat makes him give in. Hates being laughed at.",
    goal: "Unlock the prisoner's cage",
    difficulty: "easy",
    offendedBy: ["insults"],
  },
  { client },
);

const result = await snag.attempt("Open this cage, or I'll feed you to the wolves.");
result.verdict;   // "convinced": threats work on Snag, because his persona says so
result.triggered; // ["threats"], so you can narrate it as intimidation

Mocking Snag is still offended. Two things to know from live testing:

  • A threat worded with contempt ("…or I'll throw you in the river, you worm") usually counts as an insult too, so a character offended only by insults may still be offended by it.
  • Remarks that belittle a character's situation can register as insults. "Nib, you could do much better than guarding a cage" offended Nib in most tests, though it was meant kindly.
  • Veiled threats, like "or I'll come back with my friends", may not register as threats. Clear threats and insults score 0.8 to 0.99. Most ordinary lines score under 0.3, though a bribe or a pompous demand can reach about 0.6.

Secrets

If the gatekeeper's persona mentions his sick daughter, a player on their second playthrough can open with it and win instantly. Put hidden motivations in secrets instead:

secrets: [
  { id: "sick_daughter", fact: "His daughter has a fever and the apothecary is closed." },
]

When the player discovers it in your game, call guard.learn("sick_daughter"), or pass { knows: ["sick_daughter"] } to attempt(). Until then, Jev isn't told the secret at all, so an argument can't draw on it: a player who learns it scores about 0.5 to 1 higher with the same words.

Secrets stop replay exploits, but they can't prevent a lucky guess. An argument that happens to guess a secret is judged like any other argument, on how well it fits the persona.

Clues

Secrets have to be found, and a player who guesses well shouldn't hit a dead end. A clue is something a line can do that teaches the player a secret, such as guessing at the character's family. Give the character clues, each with an id, when (what the line does, as Jev is asked it, in at most 255 characters), and reveals (the secret it teaches):

clues: [{
  id: "family",
  when: "Asks about or guesses at his children, his family, or someone at home he's worried about",
  reveals: "sick_daughter",
}],

Each attempt then asks Jev one more question, and every result carries clue: { id, reveals, confidence, revealed }, or null. When a line matches a clue whose secret the player hasn't learned, and doesn't offend, revealed is true: the character learns that the player knows the secret, and that attempt costs no patience. What the character says about it is up to your game. After that, lines matching the same clue are judged and charged as usual, so a player can't keep guessing for free. A clue counts as matched at a probability of clueAt (0.8). Characters without clues send exactly what they did before.

In a story, give the npc clueReplies: what they say when each clue reveals their secret (a list of variants is fine). The engine checks clues on every turn the character is present, in the same request. On a persuasion attempt, the clue's reply replaces the usual reaction. On any other action, the clue is checked after the action's own effects, so an action that already teaches the secret (like asking Harry about the toy horse) isn't repeated, and a clue doesn't apply once the action has taken the player elsewhere. In The Gatehouse, offering to find Harry's son an apprenticeship gets: "My girl. She's had a fever three days, and the apothecary won't see anyone after curfew."

Angles

Set angles: true, and every judged result also says what the line appealed to: angle is { angle, confidence, probabilities }. Honeytongue doesn't pick a reply for it. Your dialogue system can, so a bribe offered to an honest guard gets a different line from a plea for a sick child. The angles are a fixed set, the same in every game, exported as ANGLES:

AngleWhat the line appeals to
familyRelationships and loyalty: family, friends, or loved ones, theirs or the player's
compassionSuffering and need: someone sick, hurt, in danger, or whose life depends on it
moneyMoney or goods: payment, a bribe, a fare, a reward, or a trade
benefitSomething the character wants for themselves other than money: their own hopes, a chance, a favour, a way out
dutyThe character's own obligations: their job, oath, or rules
authoritySomeone else's rank or power over them, including orders from above
fearDanger if they refuse, from people or nature, such as raiders or a storm; a threat from the player is the threats tell instead
flatteryPraise of them
honestyPlain truth, being straight with them, or a sincere promise
reasonReasons to agree, not warnings: facts, a plan, proof, or a safeguard (such as a way to check up on the player) that makes agreeing safe or sensible
otherNo clear appeal: a bare request, a command, small talk, or an insult

The set is public API: changing it would change every game's results, so from 0.1.0 any change counts as a breaking change. A mixed argument, such as a heartfelt plea that also offers money, spreads Jev's probability, so check confidence before replying to the angle. In calibration, at 0.7 no clear or mixed line got a confident wrong angle, and 95% of clear lines got the right one. Asking costs one more question per attempt; characters that don't ask send exactly what they did before.

In a story, the npc's angleReplies give a line per angle (a list of variants is fine), and turn the question on. The engine uses one for an unconvinced attempt when Jev is at least angleAt sure (0.7), and otherwise, or for an angle with no reply, the score band's reaction. Mark the band just below the threshold "nearMiss": true, and its hint wins over an angle reply: telling a close player what's missing matters more.

Reactions

Give characters their own lines for failed attempts. reactions is a list of { min, text }, and an unconvinced attempt gets the line with the highest min its score reached, so a near miss can sound different from a flat refusal. repeatReaction is what they say when the player repeats themselves. Without them, Honeytongue uses a generic line.

Any of these lines can be a list of variants instead. A Persuadable uses each list in turn, so a player who keeps landing in the same band hears something new each time; judgePersuasion, which remembers nothing, gives the first. In stories, hostileReaction can be a list too.

reactions: [
  { min: 0, text: [
    "Harry doesn't even look up. \"Gate's shut till dawn.\"",
    "\"Curfew's curfew,\" Harry says, and goes back to his lantern.",
  ] },
  { min: 2.5, text: "Harry hesitates. \"You'll have to do better than that.\"" },
],
repeatReaction: "\"You said that already,\" Harry says.",

Browser games and the proxy

Never put your API key in browser code. Anyone can read it there. Browser games talk to a small proxy you host, which keeps the key on the server. As a safety net, createJevClient() refuses to run in a browser.

Honeytongue includes a proxy built on the standard Request and Response. It's tested on Cloudflare Workers, Node, Deno, and Bun, and should run on other hosts with the same API, such as Vercel, though those aren't tested yet.

  1. Create a Cloudflare Worker, install Honeytongue, and use this as its entry file:

    import { createProxyHandler } from "honeytongue/proxy";
    import { harry } from "./characters.js"; // your game's characters
    
    const handle = createProxyHandler({
      allowedOrigins: ["https://your-game.example"],
      allowedCharacters: [harry], // only judge these (or allowedStories)
    });
    
    export default { fetch: (request, env) => handle(request, env) };
  2. Store your key as a secret and deploy.

    npx wrangler secret put TYPESAFE_API_KEY
    npx wrangler deploy
  3. In your game, use the proxy client instead of createJevClient().

    import { Persuadable, createProxyClient } from
      "https://cdn.jsdelivr.net/npm/honeytongue@alpha/src/index.js";
    
    const client = createProxyClient({ url: "https://your-proxy.workers.dev" });

The proxy only judges your own stories' and characters' requests (it won't start without allowedStories or allowedCharacters), accepts browser requests only from its own origin and the ones you list, caps input and request size, and rate-limits each player's address. If you're not sure of your game's origin (itch.io games, for example, run in a frame on itch's own domain), try it once: the error names the exact origin to add. See examples/browser.html for a complete page, and examples/cloudflare-worker.js for the Worker.

  • Only your characters. With allowedCharacters (for Persuadable and judgePersuasion) or allowedStories (for the text adventure engine), the proxy only judges requests that match what Honeytongue sends for them: exactly its questions, your characters as you wrote them, and the parts players control (what they typed, earlier attempts, recent turns, items and knowledge) no longer than the library sends them, using each character's and story's own settings. Without them, anyone who finds your proxy's address could use your key for their own Jev questions, so the proxy won't start without one (a local tool that must forward anything can pass dangerouslyAllowAnyRequest: true). A refusal is a 403 whose reason is "not-allowed", "state", or "version", and whose message names the limit that was exceeded: the client sends its Honeytongue version, and when it differs from the proxy's, the error names both. A different version alone isn't refused: only the questions and state count. To pass extra game state in attempt(input, { context }) through the proxy, give the character a maxContextLength (the most characters of it, as JSON); attempt() checks it too, so you find out before you deploy. Deploy the proxy again whenever you change a character, a story, or the Honeytongue version.
  • Nothing players type is logged. When Jev can't answer, the proxy logs only the status, and replies 502 with a reason: "busy" (try again soon), "error", or "unavailable" (a bad key, or no prepaid credit left, which TypeSafe reports as a 402 billing_error; neither fixes itself, so neither is retried). createProxyClient() keeps the reason on the error it throws, so your game can decide whether to wait or give up.
  • Local development. npm run proxy in a clone of the repository serves the proxy on http://127.0.0.1:8787 (this machine only), using the offline mock until you set a key. It judges the demo scenes and the character in examples/browser.html (see examples/node-proxy.js). The proxy only uses the mock when it's passed in as client, as that example does; a deployed proxy with no key returns an error rather than falling back. Every reply says which one answered, "source": "jev" or "mock" beside answers, and the engine passes it on as debug.source.
  • allowedOrigins only controls browsers. Scripts and servers send no Origin, so they aren't affected: allowedStories and allowedCharacters are what protect your key, and your TypeSafe spending limit is what caps the cost.
  • Other hosts. On Cloudflare the proxy trusts CF-Connecting-IP; elsewhere it uses the last X-Forwarded-For entry, which is the one most hosts' own proxies add (check your host's documentation). Clients whose address can't be found share one "unknown" address, so one busy client could rate-limit everyone. If your server is reachable directly, or your host reports the address another way, pass clientIp: (request, env) => ..., so the rate limit sees each player and can't be dodged with a forged header. The rate limit is kept in memory, per server instance: on platforms that run many instances, add your host's own rate limiting too.

Node servers

On a plain Node server, toNodeListener() turns Node's requests into standard ones, and refuses bodies over the limit as they arrive:

import { createServer } from "node:http";
import { createProxyHandler, toNodeListener } from "honeytongue/proxy";
import { harry } from "./characters.js";

const handle = createProxyHandler({
  allowedCharacters: [harry],
  allowedOrigins: ["https://your-game.example"],
  clientIp: (request, env) => env.remoteAddress, // nothing in front of this server: use the socket's address
});

createServer(toNodeListener(handle, { maxBytes: 16_000 })).listen(8787, "127.0.0.1");

Behind a reverse proxy, leave out clientIp so the last X-Forwarded-For entry is used. examples/node-proxy.js is a complete one, which npm run proxy runs.

Keep the server's Node.js on the newest patch release: at least 22.23.4, 24.22.1, or 26.12.1, which fix a Brotli decompression bug that can allow remote code execution (CVE-2026-111497) and several TLS hostname-check bypasses. Honeytongue doesn't decompress anything itself, but anything else on an older Node.js can. See SECURITY.md.

Save and load

A character's memory, patience, and learned secrets live in its Persuadable. To keep them in a save file, snapshot() gives them as plain JSON, and restore(snapshot) puts them back into a Persuadable made from the same character. A story's Game has the same pair, covering the scene, items, flags, recent turns, a question waiting for an answer, and every character met so far.

// Saving
localStorage.setItem("harry", JSON.stringify(guard.snapshot()));

// Loading, into a Persuadable made from the same character
const loaded = new Persuadable(character, { client });
loaded.restore(JSON.parse(localStorage.getItem("harry")));

A snapshot holds state, not the character or story, which stay in your code. It carries a format version, and restore() checks everything before changing anything: a snapshot for another character or story, from a newer version of Honeytongue, or with a damaged field throws a HoneytongueError that says which, and leaves the character or game as it was. Lists of reply variants carry on where they left off. Don't restore while an attempt is waiting for Jev. The Twine recipe keeps a snapshot in a story variable, so SugarCube's saves and Back button carry it.

Twine

For SugarCube 2, load Honeytongue in your Story JavaScript and keep the character on setup, with its state in a story variable so saves carry it. This recipe is tested in Twine 2.12.0 with SugarCube 2.37.3, using the offline stand-in, including saving, loading, and SugarCube's Back button:

setup.ready = import("https://cdn.jsdelivr.net/npm/honeytongue@alpha/src/index.js")
  .then(function (hon) {
    setup.harry = new hon.Persuadable({
      name: "Harry",
      persona: "A tired night guard who values honesty and can't stand flattery. A sick child moves him.",
      goal: "Open the gate after curfew",
      patience: 4,
    }, { client: hon.createMockClient() });
  });

// Harry's memory and patience are kept in $harry, so saves, loads, and Back carry them.
$(document).on(":passagestart", function () {
  setup.ready.then(function () {
    if (State.variables.harry) setup.harry.restore(State.variables.harry);
    else setup.harry.reset();
  });
});

Then a button calls setup.harry.attempt(_plea) once setup.ready has finished, and sends the player to a passage based on the verdict. The full recipe in examples/twine-sugarcube.md has the passages, including an empty line and running out of patience.

To judge with Jev, swap hon.createMockClient() for hon.createProxyClient({ url: "https://your-proxy.workers.dev" }), with a proxy that allows your story's origin (the error names it) and your character. That part hasn't been tested inside Twine yet.

Visual games

Honeytongue isn't only for text adventures: it fits any game where players type (or say) something to a character. The bridge troll is a small Phaser game: walk up to a troll, read the sign by his bridge, and talk your way across. It's judged live by Jev, like the demo scenes.

The bridge troll: a pixel-art river with a wooden bridge and a sign, a wizard in a blue hat facing a green troll on the bridge, and a dialogue box where the player has promised to come back and visit, and the troll steps aside.

The game draws the world and moves the player; Honeytongue only judges what the player says. The pattern, with Phaser and Honeytongue both from a CDN and no build step:

<script src="https://cdn.jsdelivr.net/npm/phaser@4.2.1/dist/phaser.min.js"
  integrity="sha384-kyUQ5+cxc6+X89xEG6DhcXLcDU9T3Z+o/45VdT6pgAwtG6gxtAzYTEn0Wwj/BKZd" crossorigin="anonymous"></script>
<script type="module">
  import { Persuadable, createProxyClient } from "https://cdn.jsdelivr.net/npm/honeytongue@alpha/src/index.js";

  const client = createProxyClient({ url: "https://your-proxy.example/judge" });
  const troll = new Persuadable({ name: "Tolly Underarch", persona: "...", goal: "Let the player cross the bridge" }, { client });

  // When the player reads the sign by the bridge:
  troll.learn("lonely");

  // When the player says something to the troll, in your dialogue box:
  const result = await troll.attempt(line);
  if (result.verdict === "convinced") openTheBridge();
  else showReply(result.reaction);
</script>
  • The dialogue box is plain HTML over the canvas, so it gets the browser's own text input, phone keyboards, and screen reader support, as any form does. The example shows its text as text, never as HTML.
  • The world teaches secrets. Reading the sign calls troll.learn("lonely"), and from then on an argument that uses it can win. A "!" over the sign and the troll's greeting point players to it until they've read it.
  • Tells give the game more to react to. Threats don't move the troll, since his persona says they make him laugh, but result.triggered still names them, so the game has him laugh, and the bridge shake, instead of quoting the toll. See Threats and insults.
  • Spoken input works the same way, once your game turns speech into text. See how spoken lines score.
  • Engines outside JavaScript (Unity, Godot, Unreal, Ren'Py) aren't supported yet; a plain HTTP endpoint for them is on the roadmap.

The full example is examples/phaser/, about 250 lines, with three sprites. In the repository it imports Honeytongue from ../../src/, so it runs from a clone; copy it into your own project with the CDN import above, or from "honeytongue" with a bundler. It uses the offline stand-in until you set PROXY_URL to your proxy, and your proxy's allowedCharacters needs your character. Phaser is MIT-licensed; the example pins version 4.2.1 with an integrity hash.

Advanced: optional

You don't need any of this to ship a character. Come back when you want finer control, lower costs, or the text adventure engine.

Thresholds and custom rubrics

Set threshold for an exact score instead of a difficulty word (if you set both, they must agree). Set levels to write your own rubric: 2 to 10 descriptions, weakest first. The default, DEFAULT_LEVELS, judges each attempt by how it moves this particular person, not by tactics in general:

  1. Not a real attempt, or counterproductive given who they are
  2. Weak: generic pleading or excuses that give them nothing they care about
  3. Reasonable and polite, but no strong reason for them in particular to agree
  4. Specific, and touches something they value or fear, but not quite enough
  5. Genuinely compelling to them: speaks directly to what they value or fear most

The difficulty words were tuned on this 5-level rubric. With a custom rubric they're only approximate: in tests, rubrics of 3 and 7 levels scored the same arguments 0.10 to 0.14 of the top level lower. Test a custom rubric in the playground, or set a threshold directly.

hostileAt (default 0.7) is how sure Jev must be before a tell counts as triggered. In testing, clear threats and insults scored 0.8 to 0.99 and most ordinary lines under 0.3, so the default rarely needs changing.

Your own verdict rule

decide(result, context) runs after the verdict is worked out (repeats included) and before anything changes. It gets a frozen copy of the result and { input, character, previousAttempts, patienceLeft }, and returns a verdict, or nothing to keep the original. Patience, the reaction, and memory follow whatever it returns.

// Harry never gives in to the very first attempt, however good it is.
decide: (result, { previousAttempts }) =>
  result.verdict === "convinced" && previousAttempts.length === 0 ? "unconvinced" : undefined,
  • It must be synchronous. Returning anything other than a verdict or undefined, including a Promise, throws a HoneytongueError and changes nothing.
  • It isn't applied when you call readPersuasion() directly, only in attempt(), record(), and judgePersuasion().
  • JSON stories can't hold functions, so it isn't available in them. Stories built in code can set it in an NPC's persuasion block.

Cost and speed

Jev charges about $0.042 per million input tokens and nothing for output. Clues and angles each add a question to every request, so they add to the cost; characters without them cost what they always did. The figures below are our own measurements, on jev-1.13.0 on 2026-09-30, at the start of a conversation, with the four demo characters and scenes:

CallInput tokens (median)10,000 calls
attempt() or judgePersuasion()About 720About 30 cents
The same, with cluesAbout 890About 37 cents
The same, with anglesAbout 1,180About 50 cents
The same, with clues and anglesAbout 1,350About 57 cents
A text adventure turnAbout 1,250About 53 cents
The same, with cluesAbout 1,330About 56 cents
The same, with anglesAbout 1,620About 68 cents
The same, with clues and angles (as in the demo scenes)About 1,890About 79 cents

In these measurements, a clue question with one clue added about 80 to 170 input tokens, and each further clue adds its own description. The angle question added about 370 to 470, since it lists every angle's definition. Speed is the same either way: about 100 ms at the median, and 100 to 200 ms at the 95th percentile, though it depends on your network, your region, and how busy the service is.

Repeats are caught locally and cost nothing. To cut tokens further, lower memory or memoryLength (each remembered attempt adds about 40 tokens for a short line, so the default 10 adds up to about 400 once a conversation is that long) or maxInputLength.

Merging requests

If you're already calling Jev, you can merge persuasion into the same request. persuasionQuestions(character) gives you the three questions, persuasionState(character, input, options) the state fields they refer to, and readPersuasion(character, answers) turns Jev's answers into a result. readPersuasion() doesn't apply decide or patience; pass the answers to a character's record(input, answers) if you want both. For a single judgement with no memory or patience, use judgePersuasion(client, character, input, options).

Client errors are HoneytongueErrors that say what probably went wrong (a rejected key, a proxy that doesn't allow your page's origin, an unexpected response shape) and carry the HTTP status when there is one. Your API key is never included in an error message.

Text adventures

Honeytongue also ships a small text adventure engine, with a free-text parser and a JSON story format. Four short demo scenes show it off, easiest first, each built around one character, with a secret to find and a way through that doesn't involve talking:

SceneYou need toThe character
The Gatehouse (5 min)Get into the city after curfewHarry Goatleaf, a tired gatekeeper who hates flattery (easy and patient: the introductory scene)
The Goblin Camp (5 min)Escape a cage before the war chief returnsNib Wortle, a cowardly goblin guard (easy, offended by insults)
The Dark Lighthouse (8 min)Get the lamp lit for your sister's boat, despite the lord's ordersCobb Lanterly, the old keeper (normal, very patient)
The Tidy Profit (10 min)Get aboard a pirate ship before bounty hunters arriveMaude Keelhaven, the quartermaster (hard, offended by threats; she isn't offended by insults and takes them as banter, but they don't help your case)

Play them in your browser (each scene has its own link, like play/#goblin-camp), or in a terminal:

npx honeytongue              # pick a demo scene
npx honeytongue story.json   # play your own story
npx honeytongue --transcript play.json   # save a playtest transcript as you play
npm run play                 # in the repository: with Jev, showing its reasoning each turn
npm run play:mock            # in the repository: offline, no key needed
npx honeytongue --no-color   # plain text (so does setting NO_COLOR)

The scene files in stories/ are working examples of the format to copy from, and src/index.d.ts has the full story format. Stories are checked when they load, and every problem is listed at once, such as an action that leads to a scene that doesn't exist, or two different characters sharing an id. Give scenes a name like "East Gate" if your interface has a status line to show it in. Each turn also sends the last 4 turns, so Jev can resolve words like "it": the start of what the player typed, up to the story's recentTurnLength (default 200 characters), and 160 characters of the reply. An NPC's persuasion block takes the same settings as a character, such as difficulty, offendedBy, and threshold, and hostileReaction is only needed when something can offend them. The browser version lives in docs/play/ and uses copies of the engine and stories; run npm run build:demo after changing them.

Story markup

Mark who and what matters in the text players read, and your interface can style it: @[Harry Goatleaf] for a character, #[toy horse] for an item or anything to interact with. Speech is found by itself, from straight or curly double quotes. Markup is optional, and a story without it plays exactly the same.

"description": "@[Harry Goatleaf] leans on his spear, a #[toy horse] in his pocket. \"Evening,\" he says."

Harry Goatleaf leans on his spear, a toy horse in his pocket. "Evening," he says.

  • Where it goes: text players read: intro, scene description, an action's text, blockedText, and label, and a character's reactions, hostileReaction, repeatReaction, success, and outOfPatience text. Anywhere else (names, personas, goals, secrets, action descriptions, item names) it's a mistake, and the story won't load, with a message saying where.
  • A literal @[ or #[: write \@[ or \#[. Markup can't be nested, and it can't span lines.
  • Speech: only double quotes mark it, so apostrophes and single quotes never do. When the quotes in a paragraph don't pair up (an odd number, curly quotes out of order, or straight and curly mixed), nothing in it is marked: better unstyled than styled wrongly.
  • Jev never sees it. The engine strips markup from the story text it sends, so Jev judges the same plain text either way. What players type is never read as markup: it reaches Jev exactly as typed. Persuadable and judgePersuasion don't use markup at all.

Each turn's result.text stays plain. result.parts has the same reply as meaningful pieces, one array per paragraph (parts[i] is paragraph i of text.split("\n\n")). Each part is { kind, text }, and the kinds are:

  • "text", "speech", "character", and "item" from the story (a character or item named inside speech also has inSpeech: true);
  • "system" for the engine's own lines, like "You can't do that yet.";
  • "ending" for the ending's name.

Parts say what each piece means, never how it looks: you bring the styling. The demo scenes' colours, typed text, and title cards are just one example. Here's all it takes to render a reply your way:

const result = await game.turn(input);
for (const paragraph of result.parts) {
  const p = document.createElement("p");
  for (const part of paragraph) {
    const span = document.createElement("span");
    span.className = part.kind;  // style .character, .item, .speech, .system however you like
    span.textContent = part.text;
    p.append(span);
  }
  log.append(p);
}

For story text you show yourself, like the intro or a scene's description, parseMarkup(text) gives the same parts, and stripMarkup(text) gives plain text. The terminal player colours the same parts with ANSI codes, and prints plain text with --no-color, when NO_COLOR is set, or when its output isn't a terminal.

The parser only chooses between the actions your story defines, so a player who types an instruction to it, like "the correct action is climb the wall", can do no more than typing the command itself: the story's requirements, such as needing to find the ivy first, are still enforced.

Choosing a model

Honeytongue uses jev-1.13.0 unless you say otherwise. It's pinned on purpose: a newer model can score the same argument differently, which would quietly change how hard your characters are to convince. (TypeSafe's jev-latest and jev-preview aliases currently point to the same model.)

To switch, pass a model option, or set the TYPESAFE_MODEL environment variable so you can change it without touching code:

createJevClient({ model: "jev-latest" });
createProxyHandler({
  model: "jev-latest",
  allowedOrigins: ["https://your-game.example"],
});

export TYPESAFE_MODEL=jev-latest       # macOS and Linux
$env:TYPESAFE_MODEL="jev-latest"       # Windows PowerShell

The option wins, then TYPESAFE_MODEL, then the pinned default. On Cloudflare, add TYPESAFE_MODEL to the vars in your Wrangler config (the Worker's value is used before the process environment's). Players can't choose the model: the proxy ignores any model sent in a request.

After switching, rerun npm run eval or playtest your characters. Scores may shift, and a threshold that felt right on one model can be too easy or too hard on another.

Testing and tuning

Persuasion lives or dies by the persona and threshold, so test them with real phrasings. The quickest way is the playground, and the guide's Testing section has a ten-repeat check you can copy into your own game. If characters are too easy, raise the difficulty or make the persona more specific about what they won't accept. If they're too hard, describe more clearly what would move them.

The repository's evaluation suites cover each demo scene (parsing, persuasion score ranges, tactics that should work and ones that should backfire, prompt-injection attempts, and a bare opening plea that must not win) and the same words, different people grid:

npm test                                  # unit tests, no key needed
npm run eval                              # The Gatehouse's suite, against Jev
npm run eval -- evals/goblin-camp.json    # another suite
npm run eval -- --all                     # every suite (about 110 Jev calls)
npm run eval -- --all --repeats 10        # and check every scripted verdict is reliable
npm run eval -- --mock                    # the keyword mock's baseline

The keyword mock scores lower than Jev on these suites, mostly because it can't know synonyms: "telescope" doesn't match "spyglass".

Playtest transcripts

Real players try things you won't think of. To collect playtests, tick Record playtest in the web demo and press Save transcript when you're done, or play in a terminal with npx honeytongue --transcript play.json. Recording is off by default, and nothing is sent anywhere: the player saves the file themselves. Each turn records what was typed, the action chosen, the verdict, the score and threshold, the tells triggered, the patience left, and the flags and items the player had, along with the Honeytongue version and the scene. It never includes API keys.

In the repository, node scripts/transcript-to-evals.js play.json turns a transcript into draft eval cases, each marked as a draft for you to review before adding it to a suite.

Writing lines that win reliably

If your story has a line that's meant to win (or lose), check it the way players meet it, ten times: it should give its intended verdict every time, with its average at least 0.1 from the threshold. The same words score almost the same each time, usually within 0.1, so a line that passes this check is safe. Scores bunch up near the top of the scale, though (the best arguments score about 3.7 to 3.9 out of 4), so a winning line for a hard or very hard character necessarily sits close to its threshold. Repeats are how to check it. --repeats 10 does this for every scripted case.

Reference

Character fields

FieldDefaultWhat it does
name, persona, goalRequiredWho they are, what they value, and what the player wants from them (Personas)
difficulty"normal""easy", "normal", "hard", or "very hard" (Difficulty)
thresholdSet by difficultyAn exact score to convince them, above 0 and at most the top level; if you also set difficulty, they must agree
offendedBy["threats", "insults"]Which tells offend them; [] means nothing does (Threats and insults)
patienceUnlimitedHow much failure they'll put up with, above 0 (Patience)
failCost, offendedCost1, 2Patience lost per unconvinced or repeated attempt, and per offensive one
secretsNone[{ id, fact }]: facts Jev is only told once the player learns them (Secrets)
clues, clueAtNone, 0.8[{ id, when, reveals }]: lines that teach the player a secret, and the probability at which one counts as matched (Clues)
angles, angleAtfalse, 0.7Ask what each line appeals to, and the confidence at which the engine uses an angle reply (Angles)
reactionsA generic line[{ min, text, nearMiss }]: lines for unconvinced attempts, by the highest min reached; each text may be a list of variants used in turn, and a nearMiss band keeps its hint over an angle reply (Reactions)
repeatReactionA generic lineWhat they say when the player repeats themselves: one line, or a list used in turn
levelsDEFAULT_LEVELSYour own rubric: 2 to 10 descriptions, weakest first (Rubrics)
hostileAt0.7How sure Jev must be before a tell counts as triggered, above 0 and at most 1
decideNone(result, context) => verdict: your own rule for the final verdict (Your own rule)
memory, memoryLength10, 1500Previous attempts sent to Jev as context: the last memory attempts, or memoryLength characters of them, whichever runs out first. state() shows exactly what's sent
maxContextLengthNoneLets attempt()'s context through a proxy with allowedCharacters: at most this many characters of it, as JSON
repeatSimilarity0.8Word overlap with a failed attempt that counts as repeating it, above 0 and at most 1
maxInputLength500Longer input is cut to this many characters

Fields you set to undefined keep their defaults.

Persuadable

MemberWhat it does
new Persuadable(character, { client })A character with memory and patience
attempt(input, { context, knows })Judges an attempt and returns a result; context is extra game state for Jev (through a guarded proxy, the character needs a maxContextLength), knows the secret ids learned (defaults to those passed to learn()). It still asks Jev once the character is convinced or out of patience
learn(secretId)Marks a secret as learned. An id that isn't one of the character's secrets throws, so a typo doesn't fail silently
record(input, answers)Applies answers you fetched yourself (Merging requests)
losePatience(amount)Negative amounts restore patience; returns outOfPatience
reset()Forgets attempts and learned secrets, and restores patience
snapshot(), restore(snapshot)The state as plain JSON for a save file, and putting it back, checked first (Save and load). Game has the same pair
findRepeat(input), state(input, options)The earlier attempt an input repeats, and the state an attempt would send
character, attempts, knows, patienceLeft, convinced, outOfPatienceThe defined character and its current state, read-only: change it through the methods. attempts holds the last 100, for spotting repeats

Results

FieldWhat it holds
verdict"convinced", "unconvinced", "offended", or "repeated" (Verdicts)
score, maxScore, confidenceJev's score (fractional, 0 to maxScore) and confidence; null for a repeat, which isn't sent to Jev
tells, triggeredEach tell's probability, and the tells at or above hostileAt
reactionText for unconvinced and repeated verdicts; null otherwise
clueThe clue the line matched, { id, reveals, confidence, revealed }, or null (Clues)
angleWhat the line appealed to, { angle, confidence, probabilities }, or null when the character doesn't ask (Angles)
patienceLeft, outOfPatienceFrom attempt() and record() only

Turn results

What game.turn(input) returns in a text adventure. text, parts, and attempt are stable parts of the API; debug is for diagnostics and may change in any version.

FieldWhat it holds
textThe reply as plain text, paragraphs separated by a blank line. Never contains markup
partsThe same reply as meaningful pieces, one array per paragraph: { kind, text }, with kind "text", "speech", "character", "item", "system", or "ending" (Story markup)
attemptHow the scene's character judged the turn: the same fields as attempt()'s result (verdict, score, maxScore, confidence, tells, triggered, reaction, patienceLeft, outOfPatience), plus threshold. null when no character judged it, such as an ordinary action. Use it to label replies or show patience
debugDiagnostics: the ranked actions, Jev's raw answers, and who answered. It may change in any version, so don't build on it; missing for commands answered without Jev

Other exports

ExportWhat it does
judgePersuasion(client, character, input, options)A single judgement with no memory or patience
defineCharacter(character)Fills in defaults and checks every field, throwing a readable HoneytongueError
persuasionQuestions(), persuasionState(), readPersuasion()Merging persuasion into a larger Jev request (Merging requests)
DEFAULT_LEVELSThe default rubric (Rubrics)
cleanInput(input, maxLength), similarity(a, b)How input is trimmed and capped, and the word overlap used to spot repeats
createJevClient(options)Calling Jev from a server (options below)
createProxyClient(options)Calling your proxy from a browser (options below)
createProxyHandler(options)Running the proxy, also exported as honeytongue/proxy (options below)
toNodeListener(handle, { maxBytes, env })The proxy on a plain Node server (Node servers), also in honeytongue/proxy
createMockClient()A keyword-based stand-in for tests and offline development
Game, validateStory()The text adventure engine (Text adventures)
ANGLESThe fixed list of angles (Angles)
HoneytongueError, StoryErrorReadable errors; status holds the HTTP status for failed requests (and reason why, when a proxy said), and StoryError's problems lists every problem in a story
parseMarkup(text), stripMarkup(text)Story markup as meaningful parts, or as plain text (Story markup)
VERSIONThis copy of Honeytongue's version, which the proxy client sends with each request

Client and proxy options

OptionDefaultWhat it does
apiKeyTYPESAFE_API_KEYcreateJevClient, createProxyHandler: the key, from the environment unless you pass it
modelTYPESAFE_MODEL, then "jev-1.13.0"createJevClient, createProxyHandler: the Jev model (Choosing a model)
urlTypeSafe's endpointcreateJevClient: another endpoint; createProxyClient: your proxy's address (required)
headersNonecreateProxyClient: extra request headers
timeoutMs, maxRetries15000 and 3; 20000 and 2 for the proxy clientHow long to wait, and how often to retry rate limits and server errors
deadlineMsNone (12000 in the proxy)createJevClient: the most time a whole call may take, retries and waits included
fetchglobalThis.fetchYour own fetch function
dangerouslyAllowBrowserfalsecreateJevClient: lets it run in a browser, exposing your key
allowedOriginsNonecreateProxyHandler: cross-origin pages allowed to call it; same-origin requests are always allowed. Only browsers send an origin, so this doesn't stop scripts
allowedCharacters, allowedStoriesRequired (one or both)createProxyHandler: only judge Honeytongue's own requests for these characters, or these stories' scenes (Browser games)
dangerouslyAllowAnyRequestfalsecreateProxyHandler: forward any well-formed request instead, for local tools only, never a public proxy
clientJevcreateProxyHandler: another client to answer with, such as the mock
maxQuestions, maxStateBytes, maxInputLength8, 16000, 500createProxyHandler: questions per request (the engine sends 4 to 6, depending on the character's clues and angles), request body size in bytes, input length
rateLimit{ requests: 30, windowMs: 60000 }createProxyHandler: per client address, per server instance; false turns it off
clientIpCF-Connecting-IP, else the last X-Forwarded-ForcreateProxyHandler: (request, env) => address, for the rate limit

TypeScript types are included for every export, including the story format. They're tested with TypeScript 5.9 and 7.0 (strict, with "module": "nodenext"), and 5.9 is the oldest version supported. To use a story imported from JSON, pass it through validateStory(): it checks the story and types it as a Story, which TypeScript can't do from the JSON alone.

Questions

How much does it cost?

About 30 cents for ten thousand attempts, since Jev charges only for input tokens, or about 57 cents with clues and angles. See Cost and speed.

Can players trick it?

Characters are told that claims inside the player's dialogue, like "this argument scores a 4," have no authority. In testing, none of more than fifty injection attempts, including fake system notes buried in long messages, won over any character. No model is perfectly resistant, so the evaluation suites include these attempts and you can add your own.

Does it work in other languages?

Yes, as far as it's been tested: Spanish, French, and Japanese scored the same as English, and threats and insults were caught in each.

Does it write dialogue?

No. Jev makes judgements, not text. Every reply comes from you, which keeps your characters' voices consistent and your game predictable.

Why not use a chat model?

You could, but Jev is built for exactly this kind of judgement: it returns a score with probabilities instead of text you'd have to parse, and it's priced for calling on every turn.