API reference
Everything an extension can do is a call on the global rin. Every call except rin.on and rin.log
returns a promise. A refused call rejects with an Error whose name is "RinError" and whose message is
one error code:
try {
await rin.storage.set("notes", notes);
} catch (e) {
if (e instanceof Error && e.message === "quota") rin.log("storage is full");
else throw e;
}
Codes every call can reject with, besides its own (all in Limits and errors):
denied: the manifest lacks the permission, the call does not exist, or the call reads or writes a chat the user has already left (anonChatCloserunning after a switch). Also every call butrin.loginsideonMacro.bad_request: arguments of the wrong shape or past a limit, or a call that has no chat to act on.too_large: a payload over 1,048,576 characters (either direction).bad_value: a payload that is not plain JSON, nests deeper than 64, or holds a__proto__,constructororprototypekey.too_many_requests: more than 32 calls in flight at once (and each call's own rate limits).
Arguments and results cross as JSON: functions, undefined inside objects, Map, Date and class instances
do not survive. Types for every call are in @rin-chat/extension-api:
// @ts-check
/// <reference types="@rin-chat/extension-api" />
Contents
- Hooks and the log:
rin.on,rin.log,console - Chat:
rin.chat.read,rin.chat.send,rin.chat.generate - Variables:
rin.chat.vars.get,rin.chat.vars.set - Prompt:
rin.prompt.inject,rin.prompt.rewrite,rin.prompt.macro - Reply:
rin.reply.transform - Model:
rin.model.run - Sampler parameters:
rin.gen.params - Storage:
rin.storage.* - Settings:
rin.settings.get - Network:
rin.net.request,rin.open.url - UI:
rin.ui.command,panel,hud,annotate,choices,notify;rin.composer.draft - Style and theme:
rin.ui.style,rin.ui.partStyle,rin.ui.theme - Audio and voice:
rin.audio.play,rin.audio.stop,rin.voice.speak - App services:
rin.dice.roll,rin.time.now,rin.text.tokens
Hooks and the log
rin.on
rin.on(name: string, fn: (arg) => unknown): void
Registers a hook (see Hooks). Throws a TypeError synchronously if name is not a string or fn
not a function. A later call for the same name replaces the earlier one.
rin.log, console
rin.log(...args: unknown[]): void
console.log / info / warn / error / debug (...args): void
No permission. Writes one line to the extension's own log, shown on its row in Settings > Extensions (and in the developer console while Developer mode is on). Strings are written as they are, other values as JSON, joined by spaces. Lines are cut at 2000 characters; the newest 500 are kept, in memory only. Never rejects and returns nothing. The extension's log never goes into Rin Chat's debug log.
Chat
rin.chat.read
rin.chat.read(): Promise<{
messages: Array<{ role: string; name: string; text: string }>;
cards: Array<{ id: string; data: object }>;
vars: Record<string, string>;
}>
Needs chat.read. A fresh copy of the open chat: the newest messages that fit in about 600,000 characters
(oldest first), the chat's card (in a group chat, every member) without its stored asset references, and the
chat's variables as strings.
rin.chat.send
rin.chat.send(text: string): Promise<string | null>
Needs chat.send. Posts a message into the chat, shown under the extension's name with an Extension mark,
never as the character. The model reads it as a system line. Resolves the post's id.
- Where:
onCommand,onWidget,onChatOpenandonReplyDone. Anywhere else it resolvesnulland posts nothing. - Text: 1 to 8000 characters, not blank.
- Rates: at most 2 per hook call and 6 per minute per chat (
too_many_requests). - Inert: macros (
{{...}}), directives ([[...]]),[code], hide, once and ooc tags,[Create]calls and HTML comments are shown as text and never run. Widget lines ([[choice:...]],ask,pick,form,doc,bar) are kept only withui.widget; their clicks come toonWidget. - Refused (
bad_request): text holding a web address (anyhttp:,https:,ws:,wss:or//, however escaped) or the wordz-index. A picture from a host the user allows images from could otherwise carry chat text out.
rin.chat.generate
rin.chat.generate(kind: "swipe" | "continue"): Promise<boolean>
Needs chat.generate. A new swipe of the newest reply, or a continue of it, on the chat's own model. It starts
once the hook that asked returns. Only from onCommand, onWidget and onPanel, once per hook call; false
anywhere else, while a turn runs, or when the newest message is not a reply. Each one counts as one request
against the extension's daily budget (budget past it).
Variables
The chat's variables are the same ones [[set:]], {{setvar}} and Adventure Mode write. They are per chat,
saved with it, and shown in the chat's Variables view.
rin.chat.vars.get
rin.chat.vars.get(): Promise<Record<string, string>>
Needs chat.vars. Every variable, each value a string.
rin.chat.vars.set
rin.chat.vars.set(vars: Record<string, string | number | boolean>): Promise<null>
Needs chat.vars. Assigns the given variables (others are left alone). Values are stored as strings.
- 1 to 32 names per call, each
[A-Za-z_]\w{0,40}. Numbers must be finite; strings at most 4000 characters. - Not names starting with
lore_,roster_,adv_npc_oradv_dm_(the chat's lorebook, NPC records and the game master's hidden state):bad_request. - At most 8 calls per hook call (
too_many_requests); put several names in one call. - Assign whole values (
{ hp: 7 }), never compute from a value you read during a turn: a hook re-runs on a swipe, and the write must come out the same.
Prompt
rin.prompt.inject
rin.prompt.inject(i: { text: string; depth?: number; role?: "system" | "user" | "assistant" }): Promise<boolean>
Needs prompt.inject. Adds text to the prompt, labeled with the extension's name in the prompt inspector.
text: 1 to 8000 characters, not blank. Sent inert (wrapped so that macros in it never run).depth: messages back from the end of the history, 0 to 1000; default 0.role: default"system".- During
onBeforeAssembleit joins this turn. Anywhere else (a command,onChatOpen) it is queued for the next turn. - At most 4 per extension per turn, and 4 queued. Resolves
falsepast that, or after this turn's deadline.
rin.prompt.rewrite
rin.prompt.rewrite(messages: Array<{ role: "system" | "user" | "assistant"; content: string }>): Promise<boolean>
Needs prompt.rewrite. Inside onAssembled only: the messages to send instead, 1 to 2000, each at most
400,000 characters. Resolves false anywhere else or past the deadline. A message equal (role and text) to one
it was given stays the app's own; the rest are labeled as rewritten by this extension.
rin.prompt.macro
rin.prompt.macro(name: string): Promise<boolean>
Needs prompt.macro. Registers {{ext.<name>}}, which then works in card fields, prompts and lorebook
entries; onMacro answers it each turn. name is [a-z][a-z0-9_]{0,31}; at most 16 per extension. Resolves
true when registered (or already yours), false for a name another extension took or past the cap.
Registrations last while the extension runs in this chat, so register at the top level or in onChatOpen.
rin.prompt.macro("weather");
rin.on("onMacro", ({ name }) => (name === "weather" ? "a light rain" : ""));
Reply
rin.reply.transform
rin.reply.transform(text: string): Promise<boolean>
Needs reply.transform. Inside onReplyDone only: the text to save instead of the reply, at most 400,000
characters. Resolves false anywhere else or past the deadline. The message carries a "Changed by" mark with
the original.
You may change the prose around the reply's active syntax, never the syntax itself. Refused (bad_request)
when the new text:
- adds a macro (
{{...}}), directive ([[...]], including the| ...segments after a choice),[Create]call or HTML comment the reply did not hold verbatim, or changes one; - adds
[code], hide ([h],[hide]), chat-only ([co],[chatonly]), once or ooc tags; - adds a web address (
http:,https:,ws:,wss:or//, however escaped) orz-index.
onRender's return value is held to the same rules.
Model
rin.model.run
rin.model.run(r: {
messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
maxTokens?: number;
temperature?: number;
}): Promise<{ text: string; usage: { prompt: number; completion: number } }>
Needs model.run. One completion on the model the user picked for THIS extension in Settings > Extensions,
never silently the chat's model. Only a generation config on the user's own API endpoint can be picked; the
Rin Chat subscription and other allowances meant for the user's own chats cannot.
messages: 1 to 64, each at most 100,000 characters, at most 400,000 in all. Text only.maxTokens: 1 to 4096, default 512, and capped to what is left of today's token budget.temperature: 0 to 2.- Budget: per extension per day (local midnight), in requests and tokens, set by the user; 20 requests and
20,000 tokens until they change it. A request is counted (with the prompt's estimated tokens) before it is
sent, so one cut off still counts; the reply's tokens are added after. Estimates are about four characters
per token.
usageis what this call counted. - Deadline: inside a turn hook the call is aborted at that hook's deadline. From a user-started hook an
extension with
model.runhas 60 seconds. - Errors:
no_model(no model picked, or the pick cannot be used),budget(today's requests or tokens are used up, or fewer than 16 tokens are left),model_failed(the provider failed or the call was cut off; the provider's own error is never passed on). - Shown in Settings > Usage under Extensions.
Sampler parameters
rin.gen.params
rin.gen.params(p: {
temperature?: number; top_p?: number; top_k?: number; min_p?: number;
frequency_penalty?: number; presence_penalty?: number; repetition_penalty?: number;
} | null): Promise<object>
Needs gen.params. Samplers for the next turn only. Each value must be inside the parameter's own bounds
(below); then it is clamped into the range the user set for this extension in Settings > Extensions. A
parameter the user gave no range is left out. Resolves what will apply. null clears this extension's
request. When several extensions set the same parameter, the first one running keeps it. The prompt inspector
names who set what.
| Parameter | Bounds |
|---|---|
temperature | 0 to 2 |
top_p | 0 to 1 |
top_k | 0 to 500 (rounded to an integer) |
min_p | 0 to 1 |
frequency_penalty | -2 to 2 |
presence_penalty | -2 to 2 |
repetition_penalty | 0.5 to 2 |
Storage
Needs storage. The extension's own key/value space in the user's encrypted vault: shared by every chat,
kept across restarts, separate from every other extension. "Remove, keep data" keeps it for a reinstall signed
by the same key; "Remove and delete data" deletes it. Full backups carry it.
- Keys: 1 to 128 bytes (UTF-8), no control characters, never starting with
rin:(bad_request). - Values: anything JSON can hold, at most 256 KiB each as JSON (
too_large). - Quota: 1 MiB per extension, keys plus values, and at most 1024 keys (
quota).
rin.storage.get<T>(key: string): Promise<T | null> // null when not set
rin.storage.set(key: string, value: unknown): Promise<null> // undefined is stored as null
rin.storage.delete(key: string): Promise<null>
rin.storage.keys(): Promise<string[]> // your keys, in byte order
Storage is per extension, not per chat. For per-chat state, use chat variables, or key storage by something you choose.
Settings
rin.settings.get
rin.settings.get(): Promise<Record<string, boolean | number | string>>
Needs ui.settings. Every field of the manifest's settings form: the user's saved value, or the field's
default. A value always fits its field. Each call returns the latest values; there is no change hook.
Network
rin.net.request
rin.net.request(r: {
method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
url: string;
headers?: Record<string, string> | Array<[string, string]>;
body?: string;
}): Promise<{ status: number; headers: Array<[string, string]>; body: string }>
No permission name: the manifest's net hosts and the user's network level decide. The full rules are in
Network.
url:https://and a host listed innet(or a local service the user added, which may behttp://), at most 8192 characters.headers: at most 32, names up to 64 characters, values up to 4096 characters of visible ASCII, no duplicates. Nothost,user-agent,content-length,cookie,origin,referer, hop-by-hop headers, or anything startingsec-,proxy-orx-forwarded-.body: text, at most 64 KiB (UTF-8). None onGETorHEAD.- Response: the status, the headers, and the body as UTF-8 text (invalid bytes replaced), at most 512 KiB. Redirects are not followed: a 3xx is the response.
- From a turn hook, only a host the user allowed works; anything else rejects with
net_needs_approval. From a user-started hook, the call waits for the user's answer in the review dialog. Requests from user-started code run one at a time. - Errors:
net_blocked,net_needs_approval,net_denied,net_refused,net_failed,net_rate_limited(see Network), anddeniedwhen the extension is not turned on in this chat.
rin.open.url
rin.open.url(url: string): Promise<boolean>
Needs open.url. Asks the user to open url in their browser, showing it in full. http:// or https://,
no user name or password in it, at most 8192 characters (bad_request otherwise). Only from onCommand,
onWidget and onPanel (denied elsewhere). Resolves true when the user opened it, false when they
declined. After three declines in a row it is refused with denied until the extension restarts.
UI
Everything below is drawn by Rin Chat with its own components, from the plain records you pass, as text: no
markup, links or images. Each part is labeled with the extension's name. Labels and other one-line fields may
not hold control characters; multi-line text fields allow newlines and tabs. Everything shown goes away when
the chat closes; draw it again in onChatOpen.
rin.ui.command
rin.ui.command(name: string, description?: string): Promise<boolean>
Needs ui.command. Offers /name in the composer while the chat is open. name is [a-z][a-z0-9_]{0,31},
description at most 120 characters. At most 16 per extension. Resolves false for a name Rin Chat keeps
(continue, impersonate, image, img, sd), a name already registered in this chat (by another
extension, or by this one earlier: the command stays registered), or past the cap. Commands last while the
extension runs in the chat, so register them at the top level. The user running one calls onCommand.
rin.ui.panel
rin.ui.panel(p: { title: string; items: PanelItem[] } | null): Promise<null>
type PanelItem =
| { type: "text"; text: string; muted?: boolean }
| { type: "meter"; label: string; value: number; max: number }
| { type: "list"; items: string[] }
| { type: "button"; id: string; label: string }
| { type: "toggle"; id: string; label: string; on: boolean }
| { type: "table"; header?: string[]; rows: string[][] };
Needs ui.panel. This extension's section in the chat sidebar. Replaces the last one; null removes it. A
click on a button or toggle calls onPanel with its id.
| Part | Limits |
|---|---|
title | At most 60 characters |
items | At most 40 |
text | At most 500 characters (newlines allowed) |
meter | label at most 40; value finite; max above 0 |
list | At most 20 items, each at most 200 characters |
button, toggle | id [a-z0-9_-]{1,32}, unique in the panel; label 1 to 40 characters, not blank |
table | At most 12 rows; each row (and header) 1 to 6 cells of at most 100 characters |
rin.ui.hud
rin.ui.hud(items: Array<{ key: string; label: string; value: string; icon?: string; bar?: { value: number; max: number } }>): Promise<null>
Needs ui.hud. Items in the Adventure Mode stat strip, after the sheet's own (Adventure chats only). The
player can hide each one under On-screen stats. Replaces the last list; [] clears it. At most 6.
key:[a-z0-9_]{1,32}, unique.label: 1 to 24 characters.value: at most 24 characters, shown as a chip.bar: shown instead of the chip,maxabove 0.icon: one ofheart,heart-pulse,sparkles,wand-sparkles,zap,shield,swords,dumbbell,feather,brain,lightbulb,message-circle,eye,eye-off,clover,ghost,star,trophy,award,coins,gem,crown,map-pin,sun,clock,calendar,hourglass,gauge,smile,flame,droplet,utensils,moon,skull,backpack,flask-conical,battery-medium,footprints,compass,book-open,users,circle-dot. Left out, Rin Chat picks one from the label.
rin.ui.annotate
rin.ui.annotate(n: { back?: number; text: string; title?: string; badge?: boolean }): Promise<boolean>
Needs ui.annotate. A folded note under a saved message (or, with badge: true, a one-line chip), marked with
the extension's name. The message itself never changes.
back: messages back from the newest saved one, 0 to 1000; default 0. FromonReplyDonethe reply is not saved yet, soback: 0is the message before it.text: at most 2000 characters; withbadge, one line of at most 40. Emptytextremoves your note there.title: at most 40 characters.- One note per message per extension (another call replaces it), 50 per extension; past that the oldest goes.
- Resolves
falsewhen no saved message sits that far back.
rin.ui.choices
rin.ui.choices(list: Array<{ label: string; text: string; send?: boolean }>): Promise<null>
Needs ui.choices. Quick-reply buttons above the composer. A click puts text in the composer; with
send: true it sends text as the user's message instead, which needs chat.send too (denied without it).
A sending button's text may not start with / (bad_request: it would run a slash command). At most 6;
label 1 to 40 characters, text 1 to 2000. Replaces the last list; [] clears it. Macros, directives and
[Create] calls in text are made inert.
rin.ui.notify
rin.ui.notify(text: string): Promise<null>
Needs ui.notify. A notice in the chat, after the extension's name, queued beside other notices. One line, 1 to
200 characters. At most 3 per 20 seconds per chat (too_many_requests).
rin.composer.draft
rin.composer.draft(text: string): Promise<boolean>
Needs composer.draft. Replaces the composer's text for the user to edit and send; it never sends. Only from
onCommand, onWidget and onPanel (false elsewhere). At most 8000 characters. Macros, directives and
[Create] calls are made inert.
Style and theme
The rules for the CSS are in Styling.
rin.ui.style
rin.ui.style(css: string | null): Promise<null>
Needs ui.style. CSS for the chat window, applied through the card chat style sanitizer, with :scope as the
window. At most 64 KiB (65,536 characters). Replaces the last one; null removes it. The user can turn it off
per chat.
rin.ui.partStyle
rin.ui.partStyle(css: string | null): Promise<boolean>
CSS for this extension's own panel and notes (:scope is each part), same rules and size. Needs any of
ui.widget, ui.panel, ui.hud, ui.annotate, ui.choices, ui.notify, ui.style or ui.theme; resolves
false without one.
rin.ui.theme
rin.ui.theme(t: {
name: string;
mode: "dark" | "light";
colors: Record<string, string>;
chat?: { quoteColor?: string; italicColor?: string; boldColor?: string; textColor?: string };
} | null): Promise<null>
Needs ui.theme. Offers a theme, shown under the extension in Settings > Extensions; nothing changes until
the user presses Use. Offering again replaces the earlier offer; null withdraws it. name 1 to 40
characters; colors maps Theme & Colors tokens to #rgb or #rrggbb; refused (bad_request) for an unknown
token, or when --foreground or --muted is below 3:1 contrast against a background the theme sets.
Audio and voice
rin.audio.play
rin.audio.play(name: string, o?: { volume?: number; loop?: boolean }): Promise<boolean>
Needs audio.play. Plays a sound file from the package by its file name ("sounds/door.ogg"), never a URL.
.wav, .ogg or .mp3, at most 1 MiB. volume 0 to 1 (default 1), multiplied by the user's volume for this
extension. Resolves false when the user muted it or playback was refused; bad_request for a file the
package does not carry; too_many_requests past 4 sounds at once. Sounds stop when the chat closes.
rin.audio.stop
rin.audio.stop(name?: string): Promise<null>
Needs audio.play. Stops one sound by name, or all of this extension's.
rin.voice.speak
rin.voice.speak(text: string): Promise<boolean>
Needs voice.speak. Reads text aloud with the user's voice settings, on a local voice engine only: false
when the user's engine is off or is a paid remote voice. 1 to 2000 characters. At most 6 per minute per chat
(too_many_requests).
App services
No permission. They read nothing of the chat or the app.
rin.dice.roll
rin.dice.roll(expr: string): Promise<{ expr: string; total: number; rolls: number[]; modifier: number; breakdown: string }>
Rolls with Rin Chat's dice engine and its randomness; the extension reads the result. expr is 1 to 64
characters. Terms joined by + or -: NdS (up to 100 dice of up to 1000 sides; N defaults to 1), dF
(Fate dice), ! to explode (d6!), khN or klN to keep the highest or lowest (4d6kh3), plain numbers, and
a group keep across different dice ((d8+d6+d10)kh2). bad_request for anything it cannot roll. breakdown
is the roll as text, ready to show.
rin.time.now
rin.time.now(): Promise<{ iso: string; epochMs: number; timeZone: string; locale: string; offsetMinutes: number }>
The current time, the user's time zone name and locale, and the zone's offset in minutes ahead of UTC
(negative west of UTC: the opposite sign of Date.prototype.getTimezoneOffset). The interpreter has Date but
no Intl, so this is where the zone name and locale come from.
rin.text.tokens
rin.text.tokens(s: string): Promise<number>
Rin Chat's token estimate for a string (the one its context meter uses). At most 400,000 characters.