dokiworlds-app-sdk 0.2.0 → 0.4.1

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,18 +1,26 @@
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.1`。主要入口是 `createAppClient`、`client.whenReady`、`client.input`、`client.apps.launch`、`client.complete`、`client.requestExit` 和独立世界的 `createLlmRuntime`;宿主侧可用 `createAppHost` 和 `createAppsHostExtension`。协议仍为 v2。
4
+
5
+ 每次接入、构建或发布前,请先打开 OSS 上的[最新使用指南](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/GUIDE.md)、[独立世界规范](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/WORLD_PACKAGE_GUIDE.md)与 [README / 版本摘要](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/README.md),并执行 `npm view dokiworlds-app-sdk version` 确认 npm 当前版本。若当前安装版本落后于在线规范要求,升级依赖、更新 lockfile 后重新构建和回归测试。
6
+
7
+ ## 平台 LLM 代理
8
+
9
+ `dokiworlds-app-sdk/llm_config` 只提供平台代理调用:`createLlmRuntime({ worldId }).listModels()` 查询当前可用文本模型,`invoke(...)` 发起调用。SDK 不包含 API key、provider 或 base URL。SDK 会固定使用 DokiWorlds 页面所在的源站,因此发布包即使通过 CDN `<base>` 加载资源,LLM 请求仍会回到平台代理。世界必须由 DokiWorlds 启动,后端会写入短期 HttpOnly 世界会话;直接打开 HTML 时 LLM 调用会被拒绝。模型 ID 必须取自 `listModels()` 的返回值,不能硬编码 Provider 模型名。
4
10
 
5
11
  `0.1.0` 的客户端没有初始化输入读取 API,不能直接用于下面的检定演出插槽。
6
12
 
7
13
  ## 安装与运行条件
8
14
 
9
- 在 App 的源码项目中安装工作区包(Windows 示例,按本机仓库位置调整):
15
+ 在 App 或独立世界的源码项目中,从 npm 安装已发布的 SDK。为保证构建可复现,首次接入及正式发布应固定版本:
10
16
 
11
17
  ```bash
12
- npm install D:/GameDev/dokiworlds/packages/dokiworlds-app-sdk
18
+ npm install dokiworlds-app-sdk@0.4.1
13
19
  ```
14
20
 
15
- SDK 是浏览器端 ESM。App 必须运行在支持 `postMessage` 的 iframe 中,由实现 `dokiworld.app` v2 的宿主加载;`apps.launch` 另外要求宿主允许拉起子 App。`npm install` 只提供 SDK,不会自行创建 App 目录、列表或弹窗。若 App 以静态文件放在 `public/apps`,请用自己的构建工具把 `dokiworlds-app-sdk` 打包进浏览器脚本;浏览器不能直接从静态页面解析 `import ... from 'dokiworlds-app-sdk'` 这个 npm 裸包名。异地交付也可以在包目录运行 `npm pack`,将生成的 tgz 交给同事安装;这不等于发布 npm。
21
+ SDK 是浏览器端 ESM。App 必须运行在支持 `postMessage` 的 iframe 中,由实现 `dokiworld.app` v2 的宿主加载;`apps.launch` 另外要求宿主允许拉起子 App。`npm install` 只提供 SDK,不会自行创建 App 目录、列表或弹窗。若 App 以静态文件放在 `public/apps`,请用自己的构建工具把 `dokiworlds-app-sdk` 打包进浏览器脚本;浏览器不能直接从静态页面解析 `import ... from 'dokiworlds-app-sdk'` 这个 npm 裸包名。
22
+
23
+ 升级时执行 `npm install dokiworlds-app-sdk@<目标版本>`,保留更新后的 lockfile,重新构建并运行回归测试。面向 DokiWorlds 上传的 ZIP 只放构建产物,绝不上传 `node_modules/`、lockfile 或 `.env`。如需离线交付,也可在包目录执行 `npm pack` 生成 tgz;这不是从 npm 安装的替代要求。
16
24
 
17
25
  ## 检定演出插槽:给 App 作者
18
26
 
@@ -148,12 +156,12 @@ Physics Dice v1.0.7 当前文档明确不接收指定点数或 seed,不能展
148
156
  ```json
149
157
  {
150
158
  "entry": "index.html",
151
- "locales": { "en": { "name": "Hello App" } },
159
+ "locales": { "zh-cn": { "name": "你好" }, "en": { "name": "Hello App" } },
152
160
  "runtime": { "input": { "contract": "demo.hello.input", "version": 1 } }
153
161
  }
154
162
  ```
155
163
 
156
- `entry` 必须是目录内的相对文件路径。未提供 manifest 时,宿主使用 `index.html`、目录名作为显示名称,以及 `{ "contract": "doki.dev.launch", "version": 1, "data": {} }` 作为初始输入。manifest 中的 `runtime.input` 只定义 `contract` 和 `version`;从 **APPS** 按钮直接启动时,`data` 是空对象。当前本地宿主只枚举存在入口文件的子目录,最多读取前 100 个合法目录。
164
+ `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
165
 
158
166
  本地 App 使用与宿主同源的 iframe,以便加载 ES module 和静态资源。这个调试入口只应放入可信任的开发 App。
159
167
 
package/README.md CHANGED
@@ -1,8 +1,43 @@
1
1
  # dokiworlds-app-sdk
2
2
 
3
+ ## Install
4
+
5
+ ```bash
6
+ npm install dokiworlds-app-sdk@0.4.1
7
+ ```
8
+
9
+ Use the package from a source project and bundle it for the browser. A browser cannot resolve the npm bare import directly from a static HTML world. To upgrade, install the explicitly selected newer version, update the lockfile, rebuild, and retest the published world package.
10
+
11
+ Before every integration, build, or upload, read the current public documentation and compare your dependency with npm:
12
+
13
+ - [SDK guide](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/GUIDE.md)
14
+ - [Standalone world package guide](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/WORLD_PACKAGE_GUIDE.md)
15
+ - `npm view dokiworlds-app-sdk version`
16
+
17
+ Do not rely on an old copied guide or replace a single SDK file inside an already-built ZIP.
18
+
3
19
  中文完整使用说明见 [GUIDE.md](./GUIDE.md)。
4
20
 
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.
21
+ 完整 HTML 世界的 ZIP 结构、`packageType: "world"` 清单和平台 LLM 接入见 [WORLD_PACKAGE_GUIDE.md](./WORLD_PACKAGE_GUIDE.md)。
22
+
23
+ Version 0.4.1 keeps standalone-world LLM proxy requests on the DokiWorlds page origin when published resources use a CDN `<base>` URL. 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.
24
+
25
+ ## Platform LLM proxy
26
+
27
+ 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.
28
+
29
+ ```js
30
+ import { createLlmRuntime } from 'dokiworlds-app-sdk/llm_config';
31
+
32
+ const llm = createLlmRuntime({ worldId: 'my-world' });
33
+ // The catalog is dynamic: choose a model returned for this player/session.
34
+ const models = await llm.listModels();
35
+ const model = models.find((item) => item.recommended)?.modelId ?? models[0]?.modelId;
36
+ if (!model) throw new Error('No DokiWorlds text model is currently available');
37
+ const reply = await llm.invoke({ model, messages: [{ role: 'user', content: 'Hello' }] });
38
+ ```
39
+
40
+ 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
41
 
7
42
  ```js
8
43
  import { createAppClient } from "dokiworlds-app-sdk";
@@ -26,4 +61,4 @@ The package uses the `dokiworld.app` protocol v2 handshake and `dokiworld-app-ap
26
61
 
27
62
  ## Local development in this repository
28
63
 
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" }`.
64
+ 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,201 @@
1
+ # 独立世界包发布指南
2
+
3
+ 本指南用于把完整 HTML 世界发布到 DokiWorlds 的访客入口。它不同于嵌入式 App:世界拥有自己的页面、脚本和资源,平台只提供发布与直接入口;它不会显示在登录后世界广场的剧情包目录中。
4
+
5
+ ## 每次使用前:确认最新 SDK 与规范
6
+
7
+ OSS 上的发布指南是独立世界的对外规范入口。**首次接入、每次重新构建和每次上传 ZIP 前**,作者都必须打开以下最新在线版本,而不是复用聊天记录、旧 ZIP 或本地缓存的说明:
8
+
9
+ - [独立世界包发布指南](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/WORLD_PACKAGE_GUIDE.md)
10
+ - [SDK 使用指南](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/GUIDE.md)
11
+ - [SDK README / 版本摘要](https://static-doki.aimeng.ai/releases/dokiworlds-app-sdk/README.md)
12
+
13
+ 同时在源码项目中确认 npm 当前发布版本与实际安装版本:
14
+
15
+ ```bash
16
+ npm view dokiworlds-app-sdk version
17
+ npm ls dokiworlds-app-sdk --depth=0
18
+ ```
19
+
20
+ 若两者不同,或在线指南要求更高版本,先执行 `npm install dokiworlds-app-sdk@<目标版本>`,提交更新后的 lockfile,重新构建并按本指南完整验证。不能只替换 ZIP 内的某个 SDK 文件。
21
+
22
+ ## 打包结构
23
+
24
+ 将下面目录的内容压缩为 ZIP;也可以在 ZIP 中额外套一层目录。`index.html` 和 `manifest.json` 必须在同一层。
25
+
26
+ ```text
27
+ honglou-opening.zip
28
+ ├── manifest.json
29
+ ├── index.html
30
+ ├── assets/
31
+ │ ├── cover.webp
32
+ │ └── scene.webp
33
+ └── scripts/
34
+ └── main.js
35
+ ```
36
+
37
+ 所有入口、封面和资源引用都必须使用相对路径。世界不是一个独占域名的网站:入口在 DokiWorlds 的 `/worlds/<id>` 下运行,平台会把相对静态资源解析到该世界当前发布版本的 CDN 目录。
38
+
39
+ ### 必须遵守的路径规则
40
+
41
+ 以下规则适用于 HTML 属性(`src`、`href`、`srcset`)、CSS `url(...)`、JavaScript 中动态加载的图片/音频/视频/字体/样式/脚本和运行时 JSON:
42
+
43
+ - **必须**把包内资源写为 `assets/cover.webp` 或 `./assets/cover.webp` 这类相对路径。
44
+ - **禁止**使用以 `/` 开头的静态资源路径,例如 `/assets/cover.webp`。它会请求 `https://<平台域名>/assets/...`,而不是当前世界的资源。
45
+ - **禁止**使用 `//host/...`、`file:`、本机地址和未审核的第三方资源 URL;世界必须能只凭 ZIP 内资源运行。
46
+ - **禁止**在包内自行声明 `<base>`。发布平台会注入版本化的 CDN 基址;作者声明的基址会覆盖它。
47
+ - 图片、音频、视频、字体、脚本和样式必须是 ZIP 内的独立文件。不要把这些大资源编码为 `data:` / Base64 URI 塞进 HTML、CSS 或 JavaScript。
48
+
49
+ 这不是风格建议:以 `/` 开头的路径通常会在独占根域名的 Netlify 等静态站点上看似可用,但发布到 DokiWorlds 后会与平台的根路径和 API 命名空间冲突。
50
+
51
+ ### 资源性能要求
52
+
53
+ 图片、音频、字体、脚本和样式必须作为 ZIP 内的独立文件,通过相对路径引用。内联大资源会阻塞入口 HTML 的首次解析,也无法按资源粒度复用浏览器缓存。
54
+
55
+ 发布后的入口 HTML 继续从 DokiWorlds 同源加载,以保持平台会话与 SDK 的 `/api/...` 调用;平台会将相对静态资源解析到当前 `version-contentHash` 的 CDN release。该 release 路径不可变,图片、音频、字体和脚本可被浏览器与 CDN 长期缓存;更新世界时提高 `version` 并重新上传整个 ZIP 即会使用新路径。
56
+
57
+ 媒体请保留原始的独立 `mp4` / `webm` 文件,勿将它们 gzip 或塞入 data URI。平台 CDN 会以正确 MIME 类型交付它们;上线验收会检查视频 Range 请求与缓存行为。单条媒体文件过大仍会影响首次播放,建议为首屏和循环待机准备压缩后的版本。
58
+
59
+ ## manifest.json
60
+
61
+ `packageType` 为 `world` 时,Game Admin 会把 ZIP 作为独立世界发布。旧 App 清单未填写该字段时仍按 `app` 处理。
62
+
63
+ ```json
64
+ {
65
+ "schemaVersion": 3,
66
+ "packageType": "world",
67
+ "id": "honglou-opening",
68
+ "version": "1.0.0",
69
+ "entry": "index.html",
70
+ "cover": "assets/cover.webp",
71
+ "locales": {
72
+ "zh-cn": {
73
+ "name": "红楼开篇",
74
+ "description": "从大观园的一段序章开始。"
75
+ },
76
+ "en": {
77
+ "name": "Honglou Opening",
78
+ "description": "An opening chapter in the Grand View Garden."
79
+ }
80
+ },
81
+ "world": {
82
+ "genre": "古风剧情",
83
+ "tags": ["红楼梦", "叙事", "角色扮演"],
84
+ "aiEnabled": true
85
+ }
86
+ }
87
+ ```
88
+
89
+ 字段要求:
90
+
91
+ - `id`:小写字母、数字和连字符;发布后不可与其他世界冲突。
92
+ - `version`:递增的 `major.minor.patch`。同一世界不能重复或降低版本。
93
+ - `entry`、`cover`:ZIP 内已有的安全相对路径;`cover` 是访客入口卡片所需字段。
94
+ - `locales.zh-cn` 与 `locales.en`:都必须有非空 `name` 和 `description`。
95
+ - `world.genre`:非空分类名称;`world.tags`:最多 8 个非空标签。
96
+ - `world.aiEnabled`:布尔值。设为 `true` 后,平台启动的世界可使用平台 LLM;设为 `false` 时 LLM 运行会话与调用都会被拒绝。
97
+
98
+ ## 使用平台 LLM
99
+
100
+ 平台 SDK 已发布到 npm。需要平台 LLM 的世界源码项目必须把它作为构建依赖安装;不要向平台索取 SDK 源码压缩包、手工复制 `node_modules`,也不要把 npm 裸模块名直接留在最终 HTML 中。
101
+
102
+ ```bash
103
+ # 首次接入:固定使用当前已验证版本
104
+ npm install dokiworlds-app-sdk@0.4.1
105
+ ```
106
+
107
+ 升级时由开发者明确选择目标版本,再重新构建和完整验证世界包:
108
+
109
+ ```bash
110
+ # 示例:升级到平台公告的后续版本
111
+ npm install dokiworlds-app-sdk@<目标版本>
112
+ npm run build
113
+ ```
114
+
115
+ `package.json` 与 lockfile 必须一并保留在世界源码仓库中,以便复现已发布 ZIP 的构建结果。每次 SDK 升级都必须重新生成 ZIP、提高世界 `version`,并从 DokiWorlds 访客入口实际验证 LLM;不要只替换 ZIP 内某个 SDK 文件。静态 HTML 不能直接解析 npm 裸模块名,因此构建过程必须把 SDK 编译进浏览器脚本或输出为包内相对模块。
116
+
117
+ ```js
118
+ import { createLlmRuntime } from 'dokiworlds-app-sdk/llm_config';
119
+
120
+ const llm = createLlmRuntime({ worldId: 'honglou-opening' });
121
+ const models = await llm.listModels();
122
+ const model = models.find((item) => item.recommended)?.modelId ?? models[0]?.modelId;
123
+ if (!model) throw new Error('当前没有可用的 DokiWorlds 文本模型');
124
+ const reply = await llm.invoke({
125
+ model,
126
+ messages: [{ role: 'user', content: '问问府中事' }],
127
+ });
128
+ console.log(reply.content);
129
+ ```
130
+
131
+ 模型由平台实时提供。必须先调用 `llm.listModels()`,再从返回项的 `modelId` 选择;不要硬编码 Provider 的模型名。返回项可能包含 `tierId`、`recommended` 和 `priceDiamonds`,可用于世界自己的模型选择界面。可用列表会随平台配置、身份、额度或 Provider 可用性变化。
132
+
133
+ 从访客入口启动时,平台会用访客 ID 建立同样短期、世界作用域的 HttpOnly 运行会话。访客调用当前不扣钻石,但平台会记录世界、模型、token 与估算成本;后续可能按访客 ID 增加额度。世界不得自行保存或要求 API key。
134
+
135
+ 模型、消息和系统提示词由世界作者传入;登录玩家仍按普通游玩 LLM 调用进行登录校验、余额/额度预留和结算,访客则走平台记录的免费试玩路径。
136
+
137
+ ### API 命名空间规则
138
+
139
+ 世界不得把自己的后端写死为平台根路径的 `/api/...`,例如 `/api/director/turn`、`/api/intent` 或 `/api/template`。这些地址属于 DokiWorlds,本地静态站点上的同名接口在平台中不会自动存在,甚至可能命中语义完全不同的平台接口。
140
+
141
+ - 需要平台模型时,只使用 `createLlmRuntime()`;SDK 内部会调用世界作用域的 LLM 代理,并在 CDN `<base>` 加速资源加载时仍回到 DokiWorlds 页面源站。作者不要自行拼接该 URL,也不要传递或保存 API key。
142
+ - 若世界确实依赖非 LLM 的外部服务,该服务地址必须是经过审核的、显式配置的 HTTPS URL;不能假定与 HTML 同域的 `/api` 属于世界。
143
+ - 浏览器直接运行的包必须把 SDK 编译或随包复制为相对模块,再用 `<script type="module">` 引用;浏览器不能解析 npm 裸模块名 `dokiworlds-app-sdk/llm_config`。
144
+ - 上传 ZIP 只包含构建产物与运行所需资源,**不**包含源码项目的 `node_modules/`、`package-lock.json` / `pnpm-lock.yaml`、构建配置或 `.env` 文件。
145
+
146
+ 一个可发布的目录示例:
147
+
148
+ ```text
149
+ my-world/
150
+ ├── manifest.json
151
+ ├── index.html
152
+ ├── llm-ui.js # type=module,使用相对 import
153
+ ├── vendor/dokiworlds-app-sdk/
154
+ │ └── llm_config.js # 打包时复制/编译得到
155
+ └── assets/
156
+ ├── cover.webp
157
+ └── opening.webm
158
+ ```
159
+
160
+ ## 上传与更新
161
+
162
+ 1. 在 Game Admin 选择 ZIP,等待预览通过。此步骤会把 ZIP **上传一次**到短期暂存区并完成服务器校验。
163
+ 2. 确认预览中显示“独立世界”,再点击发布。发布确认只提交暂存令牌,不会把同一 ZIP 再上传一遍。
164
+ 3. 平台先上传全部文件到 `worlds/<id>/releases/<version>-<contentHash>/`,随后更新 `worlds/catalog.json`;访客入口会显示其封面、标题、描述、分类和标签。
165
+ 4. 更新时提高 `version` 并重新上传整个 ZIP。
166
+
167
+ 暂存令牌仅绑定当前作者且有效一小时;成功发布会立即删除暂存 ZIP。令牌过期后,ZIP 会继续显示在 Game Admin 的“暂存上传”列表中,作者可确认后手动删除;若要发布该文件,请重新选择 ZIP 并重新预览。不要把预览响应中的令牌保存、分享或当作长期发布凭据。
168
+
169
+ 当前 P0 版本采用“刷新即最新版本”:新的目录条目一经发布,刷新后的玩家会加载新版,旧页面可能因资源或接口变化而失效。没有世界存档、版本回滚、审核队列或旧会话固定版本保证。
170
+
171
+ ### 上传前自检清单
172
+
173
+ 在压缩 ZIP 前逐项确认:
174
+
175
+ 1. `index.html`、`manifest.json`、`entry` 和 `cover` 指向的文件都在 ZIP 内,且 `entry` 与 `cover` 使用相对路径。
176
+ 2. 搜索 HTML、CSS 与作者脚本:不存在 `/assets/`、`/images/`、`/audio/`、`/video/` 等根绝对静态路径,不存在自行声明的 `<base>`。
177
+ 3. 搜索作者脚本:不存在 `/api/director`、`/api/intent`、`/api/template` 或其他自行假设的平台根 API。LLM 只通过 SDK 调用。
178
+ 4. 资源不存在大体积 `data:` / Base64 内联;图片、媒体、字体均为单独文件并能以相对路径加载。
179
+ 5. 本地将目录放到 `frontend/public/apps/<id>/`,从访客入口启动一次,确认封面、首屏、音频/视频、进入流程和 LLM(若启用)都正常。
180
+ 6. 若升级过 SDK:确认 `package.json` 与 lockfile 已锁定目标 SDK 版本,且已重新执行构建;ZIP 中没有 `node_modules/` 或 `.env` 文件。
181
+ 7. 更新已提高 `version`;发布后用无缓存窗口验证入口、封面和首屏资源均来自新 release。
182
+
183
+ Game Admin 后续会把以上会导致运行失败的项目逐步升级为上传阻断校验;在此之前,作者必须自行完成该清单。
184
+
185
+ ## 本地调试
186
+
187
+ 无需上传 OSS,也无需创建 ZIP。将解压后的完整世界目录放入本仓库的 `frontend/public/apps/<id>/`,例如:
188
+
189
+ ```text
190
+ frontend/public/apps/honglou-opening/
191
+ ├── manifest.json
192
+ ├── index.html
193
+ └── assets/...
194
+ ```
195
+
196
+ 本地前端与后端运行时,会把其中 `packageType: "world"` 的清单加入访客入口;它从 `/apps/<id>/<entry>` 直接加载。该目录已经被 Git 忽略,不会被提交。`packageType` 不是 `world` 的目录仍按原有本地 App 方式处理。
197
+
198
+ ## 常见错误
199
+
200
+ - `WORLD_MANIFEST_INVALID`:核对必填字段、路径是否在 ZIP 内,以及中英文展示信息。
201
+ - `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.1",
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,76 @@
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
+ const path = `/api/worlds/${worldId}/llm`;
12
+ // Published worlds keep their document on DokiWorlds but resolve relative
13
+ // assets from an immutable CDN <base>. A root-relative fetch would otherwise
14
+ // inherit that CDN base and miss the credential-owning platform proxy.
15
+ const origin = globalThis.location?.origin;
16
+ return typeof origin === "string" && /^https?:\/\//.test(origin) ? `${origin}${path}` : path;
17
+ }
18
+
19
+ function validMessages(messages) {
20
+ return Array.isArray(messages) && messages.length > 0 && messages.length <= MAX_MESSAGES
21
+ && messages.every((message) => message && typeof message === "object"
22
+ && ["system", "user", "assistant"].includes(message.role)
23
+ && typeof message.content === "string")
24
+ && messages.reduce((total, message) => total + message.content.length, 0) <= MAX_MESSAGE_CHARACTERS;
25
+ }
26
+
27
+ function modelList(payload) {
28
+ if (!payload || typeof payload !== "object" || !Array.isArray(payload.models)) return null;
29
+ const models = payload.models.flatMap((item) => {
30
+ if (!item || typeof item !== "object" || typeof item.modelId !== "string" || !item.modelId.trim()) return [];
31
+ return [{
32
+ modelId: item.modelId.trim(),
33
+ ...(typeof item.tierId === "string" ? { tierId: item.tierId } : {}),
34
+ ...(typeof item.recommended === "boolean" ? { recommended: item.recommended } : {}),
35
+ ...(typeof item.priceDiamonds === "number" && Number.isFinite(item.priceDiamonds) ? { priceDiamonds: item.priceDiamonds } : {}),
36
+ }];
37
+ });
38
+ return Object.freeze(models.map((model) => Object.freeze(model)));
39
+ }
40
+
41
+ /** A browser client for the platform's credential-owning LLM proxy. */
42
+ export function createLlmRuntime({ worldId, endpoint, fetch: fetchImpl = globalThis.fetch } = {}) {
43
+ const baseUrl = endpointFor(worldId, endpoint);
44
+ if (typeof fetchImpl !== "function") throw new LlmRuntimeError("unavailable", "Fetch is unavailable");
45
+ return Object.freeze({
46
+ /** Returns the text models currently available to this world session. */
47
+ async listModels({ signal } = {}) {
48
+ let response;
49
+ try { response = await fetchImpl(`${baseUrl}/models`, { method: "GET", credentials: "include", signal }); }
50
+ catch { throw new LlmRuntimeError("network-error", "The DokiWorlds LLM service could not be reached"); }
51
+ let payload = null;
52
+ try { payload = await response.json(); } catch { /* handled below */ }
53
+ const problem = payload?.detail && typeof payload.detail === "object" ? payload.detail : payload;
54
+ if (!response.ok) throw new LlmRuntimeError(problem?.code || `http-${response.status}`, problem?.message || "The DokiWorlds LLM service rejected the request");
55
+ const models = modelList(payload);
56
+ if (models === null) throw new LlmRuntimeError("invalid-response", "The DokiWorlds LLM service returned an invalid model list");
57
+ return models;
58
+ },
59
+ async invoke({ model, messages, temperature, maxTokens, requestId, signal } = {}) {
60
+ if (!validMessages(messages)) throw new LlmRuntimeError("invalid-request", "Invalid LLM messages");
61
+ if (model !== undefined && (typeof model !== "string" || !model.trim())) throw new LlmRuntimeError("invalid-request", "Invalid LLM model");
62
+ if (temperature !== undefined && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) throw new LlmRuntimeError("invalid-request", "Invalid temperature");
63
+ if (maxTokens !== undefined && (!Number.isInteger(maxTokens) || maxTokens < 1 || maxTokens > 1024)) throw new LlmRuntimeError("invalid-request", "Invalid maxTokens");
64
+ const body = { messages, ...(model ? { model } : {}), ...(temperature !== undefined ? { temperature } : {}), ...(maxTokens !== undefined ? { maxTokens } : {}), ...(requestId ? { requestId } : {}) };
65
+ let response;
66
+ try { response = await fetchImpl(`${baseUrl}/chat-completions`, { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal }); }
67
+ catch { throw new LlmRuntimeError("network-error", "The DokiWorlds LLM service could not be reached"); }
68
+ let payload = null;
69
+ try { payload = await response.json(); } catch { /* handled below */ }
70
+ const problem = payload?.detail && typeof payload.detail === "object" ? payload.detail : payload;
71
+ if (!response.ok) throw new LlmRuntimeError(problem?.code || `http-${response.status}`, problem?.message || "The DokiWorlds LLM service rejected the request");
72
+ if (typeof payload?.content !== "string") throw new LlmRuntimeError("invalid-response", "The DokiWorlds LLM service returned an invalid response");
73
+ return Object.freeze({ content: payload.content, model: typeof payload.model === "string" ? payload.model : model || "", usage: payload.usage ?? null });
74
+ },
75
+ });
76
+ }