dokiworlds-app-sdk 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,71 @@
1
+ const MAX_MESSAGES = 64;
2
+ const MAX_MESSAGE_CHARACTERS = 12_000;
3
+
4
+ export class LlmRuntimeError extends Error {
5
+ constructor(code, message) { super(message); this.name = "LlmRuntimeError"; this.code = code; }
6
+ }
7
+
8
+ function endpointFor(worldId, endpoint) {
9
+ if (typeof endpoint === "string" && endpoint) return endpoint.replace(/\/$/, "");
10
+ if (typeof worldId !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(worldId)) throw new LlmRuntimeError("invalid-world", "Invalid DokiWorlds world id");
11
+ return `/api/worlds/${worldId}/llm`;
12
+ }
13
+
14
+ function validMessages(messages) {
15
+ return Array.isArray(messages) && messages.length > 0 && messages.length <= MAX_MESSAGES
16
+ && messages.every((message) => message && typeof message === "object"
17
+ && ["system", "user", "assistant"].includes(message.role)
18
+ && typeof message.content === "string")
19
+ && messages.reduce((total, message) => total + message.content.length, 0) <= MAX_MESSAGE_CHARACTERS;
20
+ }
21
+
22
+ function modelList(payload) {
23
+ if (!payload || typeof payload !== "object" || !Array.isArray(payload.models)) return null;
24
+ const models = payload.models.flatMap((item) => {
25
+ if (!item || typeof item !== "object" || typeof item.modelId !== "string" || !item.modelId.trim()) return [];
26
+ return [{
27
+ modelId: item.modelId.trim(),
28
+ ...(typeof item.tierId === "string" ? { tierId: item.tierId } : {}),
29
+ ...(typeof item.recommended === "boolean" ? { recommended: item.recommended } : {}),
30
+ ...(typeof item.priceDiamonds === "number" && Number.isFinite(item.priceDiamonds) ? { priceDiamonds: item.priceDiamonds } : {}),
31
+ }];
32
+ });
33
+ return Object.freeze(models.map((model) => Object.freeze(model)));
34
+ }
35
+
36
+ /** A browser client for the platform's credential-owning LLM proxy. */
37
+ export function createLlmRuntime({ worldId, endpoint, fetch: fetchImpl = globalThis.fetch } = {}) {
38
+ const baseUrl = endpointFor(worldId, endpoint);
39
+ if (typeof fetchImpl !== "function") throw new LlmRuntimeError("unavailable", "Fetch is unavailable");
40
+ return Object.freeze({
41
+ /** Returns the text models currently available to this world session. */
42
+ async listModels({ signal } = {}) {
43
+ let response;
44
+ try { response = await fetchImpl(`${baseUrl}/models`, { method: "GET", credentials: "include", signal }); }
45
+ catch { throw new LlmRuntimeError("network-error", "The DokiWorlds LLM service could not be reached"); }
46
+ let payload = null;
47
+ try { payload = await response.json(); } catch { /* handled below */ }
48
+ const problem = payload?.detail && typeof payload.detail === "object" ? payload.detail : payload;
49
+ if (!response.ok) throw new LlmRuntimeError(problem?.code || `http-${response.status}`, problem?.message || "The DokiWorlds LLM service rejected the request");
50
+ const models = modelList(payload);
51
+ if (models === null) throw new LlmRuntimeError("invalid-response", "The DokiWorlds LLM service returned an invalid model list");
52
+ return models;
53
+ },
54
+ async invoke({ model, messages, temperature, maxTokens, requestId, signal } = {}) {
55
+ if (!validMessages(messages)) throw new LlmRuntimeError("invalid-request", "Invalid LLM messages");
56
+ if (model !== undefined && (typeof model !== "string" || !model.trim())) throw new LlmRuntimeError("invalid-request", "Invalid LLM model");
57
+ if (temperature !== undefined && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) throw new LlmRuntimeError("invalid-request", "Invalid temperature");
58
+ if (maxTokens !== undefined && (!Number.isInteger(maxTokens) || maxTokens < 1 || maxTokens > 1024)) throw new LlmRuntimeError("invalid-request", "Invalid maxTokens");
59
+ const body = { messages, ...(model ? { model } : {}), ...(temperature !== undefined ? { temperature } : {}), ...(maxTokens !== undefined ? { maxTokens } : {}), ...(requestId ? { requestId } : {}) };
60
+ let response;
61
+ try { response = await fetchImpl(`${baseUrl}/chat-completions`, { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal }); }
62
+ catch { throw new LlmRuntimeError("network-error", "The DokiWorlds LLM service could not be reached"); }
63
+ let payload = null;
64
+ try { payload = await response.json(); } catch { /* handled below */ }
65
+ const problem = payload?.detail && typeof payload.detail === "object" ? payload.detail : payload;
66
+ if (!response.ok) throw new LlmRuntimeError(problem?.code || `http-${response.status}`, problem?.message || "The DokiWorlds LLM service rejected the request");
67
+ if (typeof payload?.content !== "string") throw new LlmRuntimeError("invalid-response", "The DokiWorlds LLM service returned an invalid response");
68
+ return Object.freeze({ content: payload.content, model: typeof payload.model === "string" ? payload.model : model || "", usage: payload.usage ?? null });
69
+ },
70
+ });
71
+ }