- JavaScript 100%
| src | ||
| tests | ||
| komarusquare-js-0.1.0.tgz | ||
| package.json | ||
| README.md | ||
komarusquare-js
Standalone JavaScript SDK for the komarusquare RP-platform API. Plain modern ESM, zero runtime dependencies, no build step. Node >= 18 and modern browsers.
Install
Install from the self-hosted git repo (anonymous read enabled):
pnpm add http://10.52.67.1:3030/komaruthebot/komarusquare-js.git
Or from a tarball, if you received one:
pnpm add ./komarusquare-js-0.1.0.tgz
Quick start
All paths below are relative to the API base http://127.0.0.1:8010/api/v1
(server default; pass another via baseUrl). Bodies are copied from the
server docs: authentication.md,
chats.md,
events-sse.md.
import { createClient } from 'komarusquare-js';
const client = createClient({ baseUrl: 'http://127.0.0.1:8010/api/v1' });
// 1. Login. Cookie mode: set_cookie: true — the transport stores the
// rp_session cookie and adds X-RP-CSRF: 1 on every write for you.
// Token mode: omit set_cookie — session.token in the response is your
// Bearer token; it is shown only once.
const { user, session } = await client.auth.login({
handle: 'komaru',
password: 'correct horse battery',
set_cookie: true,
});
// 2. Open the chat's SSE stream FIRST — replies arrive only as events.
const controller = new AbortController();
const stream = client.sse('/chats/01JBBCHAT00000000000000000X/events', {
onEvent: (type, payload) => {
if (type === 'message.created') console.log('reply:', payload.message.content);
if (type === 'closed') controller.abort(); // evicted by the 10-stream cap
},
onError: (err) => console.error('stream error', err),
}, { signal: controller.signal });
// 3. Create a chat and send. POST /chats returns 201 immediately; the
// character reply comes later via SSE (generation.started -> message.created
// -> generation.finished).
const chat = await client.chats.create({
title: 'Harbour night',
settings: { language: 'en', stm_messages: 50 },
});
const send = await client.generation.send(chat.id, { content: '@aria, ready to sail?' });
// 4. Non-streaming fallback: poll for messages newer than the send seq.
const reply = await client.generation.waitForMessage(chat.id, { afterSeq: send.message.seq });
console.log(reply.content);
// When done:
stream.close();
await client.auth.logout();
API reference
Every method returns a Promise. Non-2xx responses throw ApiError.
client.auth — authentication.md
| Method | HTTP | Notes |
|---|---|---|
register({handle, password, display_name?, invite_code?, set_cookie?}) |
POST /auth/register |
handle 1–24 chars, password 8–128; invite required unless registration_mode = open |
login({handle, password, set_cookie?}, {setToken?}?) |
POST /auth/login |
pass {setToken: true} to store session.token automatically |
logout() |
POST /auth/logout |
204; cookie mode clears the cookie |
me() |
GET /me |
current user |
setToken(value) / setSessionCookie(value) |
— | switch auth mode manually |
client.characters — characters.md
| Method | HTTP | Notes |
|---|---|---|
list({mine?, query?, limit?, cursor?}?) |
GET /characters |
|
get(id) |
GET /characters/{id} |
public projection for others |
create(body) |
POST /characters |
rendered block ≤ 2500 tokens |
update(id, body) |
PATCH /characters/{id} |
handle immutable |
delete(id) |
DELETE /characters/{id} |
204; no confirmation flag in the API |
duplicate(id, {name?}?) |
POST /characters/{id}/duplicate |
copy is private, public sheet only |
client.chats — chats.md
| Method | HTTP | Notes |
|---|---|---|
create(body) |
POST /chats |
instructions ≤ 4000 chars; settings.language, stm_messages 5–200 |
get(id) / update(id, body) / delete(id) |
GET/PATCH/DELETE /chats/{id} |
update: admin+; delete: owner |
list({limit?, cursor?}?) |
GET /chats |
ordered by last activity |
addMember(chatId, {handle, chat_role?}) |
POST /chats/{id}/members |
role: member, admin, bot |
updateMember(chatId, userId, {chat_role}) |
PATCH /chats/{id}/members/{userId} |
owner only |
removeMember(chatId, userId) |
DELETE /chats/{id}/members/{userId} |
|
addCharacter(chatId, {character_id, send_greeting?}) |
POST /chats/{id}/characters |
admin+; default send_greeting: true |
removeCharacter(chatId, characterId) |
DELETE /chats/{id}/characters/{characterId} |
|
messages(chatId, {after_seq?, before_seq?, limit?}?) |
GET /chats/{id}/messages |
limit ≤ 200; at most one of after/before |
export(chatId) |
GET /chats/{id}/export |
admin+ |
markRead(chatId, seq) |
POST /chats/{id}/read |
204 |
client.messages
Messages methods are exposed under client.messages and mirror the message
endpoints above (send via client.generation.send, list/edit/delete under
chats.messages(chatId, ...)). See chats.md.
client.memory — memory.md
| Method | HTTP | Notes |
|---|---|---|
getSettings(chatId) / updateSettings(chatId, body) |
GET/PATCH /chats/{id}/memory/settings |
|
getScene(chatId) / putScene(chatId, state) |
GET/PUT /chats/{id}/memory/scene |
|
listEntries(chatId, characterId, options?) |
GET /chats/{id}/memory/characters/{characterId}/entries |
|
editEntry(chatId, entryId, body) |
PATCH .../entries/{entryId} |
|
archiveEntry(chatId, entryId) |
DELETE .../entries/{entryId} |
|
listRelationships(chatId, characterId) |
GET .../relationships |
|
previewPrompt(chatId, characterId) |
GET .../preview |
|
getStatus(chatId) |
GET /chats/{id}/memory/status |
409 while an extract is in flight |
reset(chatId, body) |
POST /chats/{id}/memory/reset |
|
extract(chatId) |
POST /chats/{id}/memory/extract |
409 while another extract is in flight |
client.generation — generation.md
| Method | HTTP | Notes |
|---|---|---|
send(chatId, {content, mentions?, reply_to?}) |
POST /chats/{id}/messages |
201 with {message, responder_ids}; reply arrives via SSE |
reply(chatId, {character_id}) |
POST /chats/{id}/reply |
202 {queued: true} |
regenerate(chatId, messageId) |
POST /messages/{messageId}/regenerate |
202; emits message.updated |
waitForMessage(chatId, {afterSeq?, timeoutMs?, intervalMs?, signal?}?) |
GET /chats/{id}/messages?after_seq= |
polling fallback for SSE |
client.events — events-sse.md
| Method | HTTP | Notes |
|---|---|---|
stream(chatId, handlers, {signal}?) |
GET /chats/{id}/events |
returns { close() }; also iterate(chatId, ...) async-iterator wrapper; both available as client.sse(path, handlers, {signal}) |
client.turns — turns.md
| Method | HTTP | Notes |
|---|---|---|
status(chatId) |
GET /chats/{id}/turns/status |
members-visible queue state |
settings(chatId) / updateSettings(chatId, patch) |
GET/PATCH /chats/{id}/turns/settings |
chat-admin only |
updateCharacterTurn(chatId, characterId, {continue_enabled?, free_will_level?}) |
PATCH /chats/{id}/characters/{characterId} |
chat-admin; free_will_level 0–3 |
turnLog(chatId, {status?, character_id?, trigger?, limit?, cursor?}?) |
GET /chats/{id}/turns/log |
chat-admin; limit 1–100 (default 50) |
freeWillLog(chatId, {limit?, cursor?}?) |
GET /chats/{id}/turns/free-will-log |
chat-admin |
cancelQueue(chatId) |
POST /chats/{id}/turns/cancel |
drops every queued turn → {dropped} |
client.admin — admin.md
Server operators only (admin/moderator roles).
| Method | HTTP | Notes |
|---|---|---|
admin.invites.createInvite({role?, max_uses?, expires_in_days?}?) |
POST /admin/invites |
role user|moderator; max_uses 1–100 (default 1); expires_in_days 1–90 (default 7); raw code returned once |
admin.invites.listInvites() |
GET /admin/invites |
masked code_hint only |
admin.invites.revokeInvite(inviteId) |
DELETE /admin/invites/{inviteId} |
204 |
admin.users.listUsers({role?, status?, is_bot?, query?, limit?, cursor?}?) |
GET /admin/users |
moderator+; limit 1–200 (default 50) |
admin.users.getUser(userId) |
GET /admin/users/{userId} |
moderator+ |
admin.users.createUser({handle, display_name?, password?, role?, is_bot?}) |
POST /admin/users |
bots: no password, role user |
admin.users.updateUser(userId, {display_name?, bio?, handle?, role?}) |
PATCH /admin/users/{userId} |
admin |
admin.users.suspendUser(userId) / unsuspendUser(userId) |
POST .../suspend | .../unsuspend |
moderator+; last active admin can't be suspended (last_admin) |
admin.users.resetPassword(userId, {new_password}) |
POST .../reset-password |
204; kills sessions and tokens |
admin.users.issueToken(userId, {name, expires_in_days?}) |
POST .../tokens |
201; raw token shown once; expiry 1–3650 |
admin.users.deleteUser(userId, {confirm_delete_shared_chats?}) |
DELETE /admin/users/{userId} |
204; flag required when the user owns shared chats |
admin.providers.listProviders() |
GET /admin/providers |
|
admin.providers.createProvider({name, base_url, api_key?}) |
POST /admin/providers |
201; key stored server-side, never returned |
admin.providers.updateProvider(pid, {name?, base_url?, api_key?, enabled?}) |
PATCH /admin/providers/{pid} |
api_key: null removes the key |
admin.providers.deleteProvider(pid) |
DELETE /admin/providers/{pid} |
fails while engines reference it |
admin.providers.providerModels(pid) |
GET /admin/providers/{pid}/models |
|
admin.providers.syncEngines(pid, {enable_new?}) |
POST .../engines/sync |
{added, missing, unchanged}; new engines disabled unless enable_new |
admin.engines.listEngines() |
GET /admin/engines |
|
admin.engines.createEngine({provider_id, model, name?, max_context_tokens, stable?, priority?}) |
POST /admin/engines |
max_context_tokens 1024–2000000; priority default 100, lower runs first |
admin.engines.updateEngine(eid, {...}) |
PATCH /admin/engines/{eid} |
context_learned: null clears it; other fields reject null |
admin.engines.testEngine(eid) |
POST /admin/engines/{eid}/test |
{ok, latency_ms, error_code?} |
admin.engines.deleteEngine(eid) |
DELETE /admin/engines/{eid} |
204 |
admin.settings.getSettings() |
GET /admin/settings |
|
admin.settings.updateSettings({registration_mode?, default_engine_id?, decider_engine_id?, reply_max_tokens?}) |
PATCH /admin/settings |
partial — only sent keys change; modes closed|invite|open; reply_max_tokens 64–8192 |
admin.audit.listAudit({actor_id?, action?, since?, until?, limit?, cursor?}?) |
GET /admin/audit |
moderator+; limit 1–200 (default 50); append-only |
Error handling
Every non-2xx response throws an ApiError:
import { ApiError } from 'komarusquare-js';
try {
await client.auth.login({ handle: 'komaru', password: 'wrong' });
} catch (err) {
if (err instanceof ApiError) {
err.status; // HTTP status, e.g. 429
err.code; // envelope code, e.g. 'rate_limited'
err.message; // human-readable
err.retryAfter; // seconds from Retry-After, or null
err.details; // envelope details object or null
err.isRateLimited(); // true when status === 429
}
}
The library never retries automatically. On 429, honor retryAfter:
} catch (err) {
if (err.isRateLimited()) await new Promise(r => setTimeout(r, err.retryAfter * 1000));
}
Server rate limits (js-client.md): 20 messages/min, 10 reply+regenerate/min, 30 character+chat creations/hour, 5 logins/min, 10 registrations/hour/IP.
Auth modes
| Bearer token | Cookie | |
|---|---|---|
| Setup | createClient({ token }) or client.setToken(...) |
login({set_cookie: true}) or client.setSessionCookie(...) |
| Writes | just the header | transport adds X-RP-CSRF: 1 automatically |
| SSE | streaming fetch (works everywhere) | native EventSource in browsers |
Use a personal API token (rp_..., shown once) for anything long-lived;
cookies for web UIs. API tokens don't count toward the 30-session limit and
can't be combined with cookies.
SSE gotchas
- Cap 10. At most 10 open streams per user across all chats. An 11th
stream evicts your oldest one, which receives one
event: closedframe and ends. Do not auto-reconnect afterclosed— surface "stream replaced" or close streams you no longer need. - No replay on connect. After any reconnect, catch up with
chats.messages(chatId, { after_seq: lastSeq })before trusting the stream; message events carryid: <seq>usable asLast-Event-ID(informational only — the server does not replay from it). - Bearer/Node uses streaming fetch.
EventSourcecannot send anAuthorizationheader, so the transport streams withfetchand parsesevent:/data:frames (multi-line data accumulated). With cookie auth in a browser it uses nativeEventSource. : pingcomments arrive every 20 s while the chat is quiet — the transport ignores them; don't treat them as events.- Silent failures. On
generation.failedno message will ever arrive; the error exists only as that event (codes:no_engine_configured,prompt_too_large,engine_unavailable,rate_limited,bad_response,queue_full).
Docs
Full server API documentation is served by the stand at
http://<host>:8020 (source: docs/*.md in the komarusquare repo).