dokiworlds-app-sdk 0.2.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.
package/GUIDE.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # dokiworlds-app-sdk 使用指南
2
2
 
3
- 适用版本:`dokiworlds-app-sdk@0.2.0`。主要入口是 `createAppClient`、`client.whenReady`、`client.input`、`client.apps.launch`、`client.complete` 和 `client.requestExit`;宿主侧可用 `createAppHost` 和 `createAppsHostExtension`。协议仍为 v2。
3
+ 适用版本:`dokiworlds-app-sdk@0.4.0`。主要入口是 `createAppClient`、`client.whenReady`、`client.input`、`client.apps.launch`、`client.complete`、`client.requestExit` 和独立世界的 `createLlmRuntime`;宿主侧可用 `createAppHost` 和 `createAppsHostExtension`。协议仍为 v2。
4
+
5
+ ## 平台 LLM 代理
6
+
7
+ `dokiworlds-app-sdk/llm_config` 只提供平台代理调用:`createLlmRuntime({ worldId }).listModels()` 查询当前可用文本模型,`invoke(...)` 发起调用。SDK 不包含 API key、provider 或 base URL。世界必须由 DokiWorlds 启动,后端会写入短期 HttpOnly 世界会话;直接打开 HTML 时 LLM 调用会被拒绝。模型 ID 必须取自 `listModels()` 的返回值,不能硬编码 Provider 模型名。
4
8
 
5
9
  `0.1.0` 的客户端没有初始化输入读取 API,不能直接用于下面的检定演出插槽。
6
10
 
@@ -148,12 +152,12 @@ Physics Dice v1.0.7 当前文档明确不接收指定点数或 seed,不能展
148
152
  ```json
149
153
  {
150
154
  "entry": "index.html",
151
- "locales": { "en": { "name": "Hello App" } },
155
+ "locales": { "zh-cn": { "name": "你好" }, "en": { "name": "Hello App" } },
152
156
  "runtime": { "input": { "contract": "demo.hello.input", "version": 1 } }
153
157
  }
154
158
  ```
155
159
 
156
- `entry` 必须是目录内的相对文件路径。未提供 manifest 时,宿主使用 `index.html`、目录名作为显示名称,以及 `{ "contract": "doki.dev.launch", "version": 1, "data": {} }` 作为初始输入。manifest 中的 `runtime.input` 只定义 `contract` 和 `version`;从 **APPS** 按钮直接启动时,`data` 是空对象。当前本地宿主只枚举存在入口文件的子目录,最多读取前 100 个合法目录。
160
+ `entry` 必须是目录内的相对文件路径。列表名称优先使用 `locales.zh-cn.name`,没有中文名时使用 `locales.en.name`。未提供 manifest 时,宿主使用 `index.html`、目录名作为显示名称,以及 `{ "contract": "doki.dev.launch", "version": 1, "data": {} }` 作为初始输入。manifest 中的 `runtime.input` 只定义 `contract` 和 `version`;从 **APPS** 按钮直接启动时,`data` 是空对象。当前本地宿主只枚举存在入口文件的子目录,最多读取前 100 个合法目录。
157
161
 
158
162
  本地 App 使用与宿主同源的 iframe,以便加载 ES module 和静态资源。这个调试入口只应放入可信任的开发 App。
159
163
 
package/README.md CHANGED
@@ -2,7 +2,26 @@
2
2
 
3
3
  中文完整使用说明见 [GUIDE.md](./GUIDE.md)。
4
4
 
5
- Version 0.2.0 adds `whenReady()`, the `input` getter, and `requestExit()` to the v2 client. An embedded App can read its versioned input, return a completion, and request another App when the host grants that capability. The host controls catalog lookup, permissions, presentation, and lifecycle. See GUIDE.md for the check-reveal slot contract and local package installation.
5
+ 完整 HTML 世界的 ZIP 结构、`packageType: "world"` 清单和平台 LLM 接入见 [WORLD_PACKAGE_GUIDE.md](./WORLD_PACKAGE_GUIDE.md)。
6
+
7
+ Version 0.4.0 adds `llm.listModels()` for standalone worlds. An embedded App can read its versioned input, return a completion, and request another App when the host grants that capability. The host controls catalog lookup, permissions, presentation, and lifecycle. See GUIDE.md for the check-reveal slot contract and local package installation.
8
+
9
+ ## Platform LLM proxy
10
+
11
+ Internal worlds can import `dokiworlds-app-sdk/llm_config` and call the platform proxy. The SDK contains no provider URL or API key; the running world must first receive a platform-issued world session.
12
+
13
+ ```js
14
+ import { createLlmRuntime } from 'dokiworlds-app-sdk/llm_config';
15
+
16
+ const llm = createLlmRuntime({ worldId: 'my-world' });
17
+ // The catalog is dynamic: choose a model returned for this player/session.
18
+ const models = await llm.listModels();
19
+ const model = models.find((item) => item.recommended)?.modelId ?? models[0]?.modelId;
20
+ if (!model) throw new Error('No DokiWorlds text model is currently available');
21
+ const reply = await llm.invoke({ model, messages: [{ role: 'user', content: 'Hello' }] });
22
+ ```
23
+
24
+ Do not hard-code a provider model name. `listModels()` returns only text models currently enabled by the platform for the launched world; each item has `modelId`, and may include `tierId`, `recommended`, and `priceDiamonds`. The available list can change with platform configuration, player entitlement, or provider availability.
6
25
 
7
26
  ```js
8
27
  import { createAppClient } from "dokiworlds-app-sdk";
@@ -26,4 +45,4 @@ The package uses the `dokiworld.app` protocol v2 handshake and `dokiworld-app-ap
26
45
 
27
46
  ## Local development in this repository
28
47
 
29
- Place an App at `frontend/public/apps/<app-id>/index.html`, then open a game in a development build and use the **APPS** button. IDs use lowercase letters, digits, dots, and hyphens. An optional `manifest.json` can provide `entry` (a relative HTML path), `locales.en.name`, and `runtime.input` (`contract` and `version`); otherwise `index.html`, the folder name, and the `doki.dev.launch` v1 input contract are used. Local Apps run with the host origin so module scripts and local assets load normally; only put trusted development Apps in this directory. A nested `apps.launch` may target another App in the same local catalog; its completion output is returned to the caller, while closing the child returns `{ status: "cancelled" }`.
48
+ Place an App at `frontend/public/apps/<app-id>/index.html`, then open a game in a development build and use the **APPS** button. IDs use lowercase letters, digits, dots, and hyphens. An optional `manifest.json` can provide `entry` (a relative HTML path), `locales.zh-cn.name` (falling back to `locales.en.name`), and `runtime.input` (`contract` and `version`); otherwise `index.html`, the folder name, and the `doki.dev.launch` v1 input contract are used. Local Apps run with the host origin so module scripts and local assets load normally; only put trusted development Apps in this directory. A nested `apps.launch` may target another App in the same local catalog; its completion output is returned to the caller, while closing the child returns `{ status: "cancelled" }`.
@@ -0,0 +1,116 @@
1
+ # 独立世界包发布指南
2
+
3
+ 本指南用于把完整 HTML 世界发布到 DokiWorlds 的访客入口。它不同于嵌入式 App:世界拥有自己的页面、脚本和资源,平台只提供发布与直接入口;它不会显示在登录后世界广场的剧情包目录中。
4
+
5
+ ## 打包结构
6
+
7
+ 将下面目录的内容压缩为 ZIP;也可以在 ZIP 中额外套一层目录。`index.html` 和 `manifest.json` 必须在同一层。
8
+
9
+ ```text
10
+ honglou-opening.zip
11
+ ├── manifest.json
12
+ ├── index.html
13
+ ├── assets/
14
+ │ ├── cover.webp
15
+ │ └── scene.webp
16
+ └── scripts/
17
+ └── main.js
18
+ ```
19
+
20
+ 所有入口、封面和资源引用都应使用相对路径。不要使用以 `/` 开头的资源路径;世界在平台中从 `/worlds/<id>/` 加载。
21
+
22
+ ### 资源性能要求
23
+
24
+ 图片、音频、字体、脚本和样式必须作为 ZIP 内的独立文件,通过相对路径引用;不要把它们编码为 `data:` / Base64 URI 塞进 `index.html`。内联大资源会阻塞入口 HTML 的首次解析,也无法按资源粒度复用浏览器缓存。
25
+
26
+ 发布后的入口 HTML 继续从 DokiWorlds 同源加载,以保持平台会话与 SDK 的 `/api/...` 调用;平台会将相对静态资源解析到当前 `version-contentHash` 的 CDN release。该 release 路径不可变,图片、音频、字体和脚本可被浏览器与 CDN 长期缓存;更新世界时提高 `version` 并重新上传整个 ZIP 即会使用新路径。
27
+
28
+ ## manifest.json
29
+
30
+ `packageType` 为 `world` 时,Game Admin 会把 ZIP 作为独立世界发布。旧 App 清单未填写该字段时仍按 `app` 处理。
31
+
32
+ ```json
33
+ {
34
+ "schemaVersion": 3,
35
+ "packageType": "world",
36
+ "id": "honglou-opening",
37
+ "version": "1.0.0",
38
+ "entry": "index.html",
39
+ "cover": "assets/cover.webp",
40
+ "locales": {
41
+ "zh-cn": {
42
+ "name": "红楼开篇",
43
+ "description": "从大观园的一段序章开始。"
44
+ },
45
+ "en": {
46
+ "name": "Honglou Opening",
47
+ "description": "An opening chapter in the Grand View Garden."
48
+ }
49
+ },
50
+ "world": {
51
+ "genre": "古风剧情",
52
+ "tags": ["红楼梦", "叙事", "角色扮演"],
53
+ "aiEnabled": true
54
+ }
55
+ }
56
+ ```
57
+
58
+ 字段要求:
59
+
60
+ - `id`:小写字母、数字和连字符;发布后不可与其他世界冲突。
61
+ - `version`:递增的 `major.minor.patch`。同一世界不能重复或降低版本。
62
+ - `entry`、`cover`:ZIP 内已有的安全相对路径;`cover` 是访客入口卡片所需字段。
63
+ - `locales.zh-cn` 与 `locales.en`:都必须有非空 `name` 和 `description`。
64
+ - `world.genre`:非空分类名称;`world.tags`:最多 8 个非空标签。
65
+ - `world.aiEnabled`:布尔值。设为 `true` 后,平台启动的世界可使用平台 LLM;设为 `false` 时 LLM 运行会话与调用都会被拒绝。
66
+
67
+ ## 使用平台 LLM
68
+
69
+ 安装私有 SDK 后,在打包前将其编译进浏览器脚本。静态 HTML 不能直接解析 npm 裸模块名。
70
+
71
+ ```js
72
+ import { createLlmRuntime } from 'dokiworlds-app-sdk/llm_config';
73
+
74
+ const llm = createLlmRuntime({ worldId: 'honglou-opening' });
75
+ const models = await llm.listModels();
76
+ const model = models.find((item) => item.recommended)?.modelId ?? models[0]?.modelId;
77
+ if (!model) throw new Error('当前没有可用的 DokiWorlds 文本模型');
78
+ const reply = await llm.invoke({
79
+ model,
80
+ messages: [{ role: 'user', content: '问问府中事' }],
81
+ });
82
+ console.log(reply.content);
83
+ ```
84
+
85
+ 模型由平台实时提供。必须先调用 `llm.listModels()`,再从返回项的 `modelId` 选择;不要硬编码 Provider 的模型名。返回项可能包含 `tierId`、`recommended` 和 `priceDiamonds`,可用于世界自己的模型选择界面。可用列表会随平台配置、身份、额度或 Provider 可用性变化。
86
+
87
+ 从访客入口启动时,平台会用访客 ID 建立同样短期、世界作用域的 HttpOnly 运行会话。访客调用当前不扣钻石,但平台会记录世界、模型、token 与估算成本;后续可能按访客 ID 增加额度。世界不得自行保存或要求 API key。
88
+
89
+ 模型、消息和系统提示词由世界作者传入;登录玩家仍按普通游玩 LLM 调用进行登录校验、余额/额度预留和结算,访客则走平台记录的免费试玩路径。
90
+
91
+ ## 上传与更新
92
+
93
+ 1. 在 Game Admin 选择 ZIP,等待预览通过。
94
+ 2. 确认预览中显示“独立世界”,再点击发布。
95
+ 3. 平台先上传全部文件到 `worlds/<id>/releases/<version>-<contentHash>/`,随后更新 `worlds/catalog.json`;访客入口会显示其封面、标题、描述、分类和标签。
96
+ 4. 更新时提高 `version` 并重新上传整个 ZIP。
97
+
98
+ 当前 P0 版本采用“刷新即最新版本”:新的目录条目一经发布,刷新后的玩家会加载新版,旧页面可能因资源或接口变化而失效。没有世界存档、版本回滚、审核队列或旧会话固定版本保证。
99
+
100
+ ## 本地调试
101
+
102
+ 无需上传 OSS,也无需创建 ZIP。将解压后的完整世界目录放入本仓库的 `frontend/public/apps/<id>/`,例如:
103
+
104
+ ```text
105
+ frontend/public/apps/honglou-opening/
106
+ ├── manifest.json
107
+ ├── index.html
108
+ └── assets/...
109
+ ```
110
+
111
+ 本地前端与后端运行时,会把其中 `packageType: "world"` 的清单加入访客入口;它从 `/apps/<id>/<entry>` 直接加载。该目录已经被 Git 忽略,不会被提交。`packageType` 不是 `world` 的目录仍按原有本地 App 方式处理。
112
+
113
+ ## 常见错误
114
+
115
+ - `WORLD_MANIFEST_INVALID`:核对必填字段、路径是否在 ZIP 内,以及中英文展示信息。
116
+ - `402 insufficient_balance`:玩家余额或额度不足;这是平台正常的游玩计费结果。
package/package.json CHANGED
@@ -1,14 +1,18 @@
1
1
  {
2
2
  "name": "dokiworlds-app-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
7
7
  "types": "./src/index.d.ts",
8
8
  "default": "./src/index.js"
9
+ },
10
+ "./llm_config": {
11
+ "types": "./src/llm_config.d.ts",
12
+ "default": "./src/llm_config.js"
9
13
  }
10
14
  },
11
- "files": ["src", "README.md", "GUIDE.md"],
15
+ "files": ["src", "README.md", "GUIDE.md", "WORLD_PACKAGE_GUIDE.md"],
12
16
  "scripts": {
13
17
  "test": "node --test tests/*.test.mjs",
14
18
  "typecheck": "tsc --noEmit -p tsconfig.json",
@@ -0,0 +1,13 @@
1
+ export declare class LlmRuntimeError extends Error { readonly code: string }
2
+ export interface LlmMessage { role: 'system' | 'user' | 'assistant'; content: string }
3
+ export interface LlmInvokeRequest { model?: string; messages: LlmMessage[]; temperature?: number; maxTokens?: number; requestId?: string; signal?: AbortSignal }
4
+ export interface LlmInvokeResult { content: string; model: string; usage: unknown }
5
+ /** A text model enabled by the platform for the current world session. */
6
+ export interface LlmModel { modelId: string; tierId?: string; recommended?: boolean; priceDiamonds?: number }
7
+ export interface LlmRuntime {
8
+ /** Fetches the current platform-approved text models; do not hard-code model IDs. */
9
+ listModels(options?: { signal?: AbortSignal }): Promise<readonly LlmModel[]>
10
+ invoke(request: LlmInvokeRequest): Promise<LlmInvokeResult>
11
+ }
12
+ /** Uses an HttpOnly world session; API keys and provider URLs never enter the client. */
13
+ export declare function createLlmRuntime(options: { worldId?: string; endpoint?: string; fetch?: typeof fetch } ): LlmRuntime
@@ -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
+ }