@xiaozhu2007/koishi-plugin-litematic-renderer 0.6.0 → 0.7.20

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.
Files changed (62) hide show
  1. package/README.md +94 -6
  2. package/assets/standalone-renderer/litematic-standalone-renderer-0.2.8-patch.1.jar +0 -0
  3. package/dist/index.css +1 -0
  4. package/dist/index.js +13 -1
  5. package/lib/cache.d.ts +94 -0
  6. package/lib/cache.js +1 -0
  7. package/lib/concurrency.d.ts +13 -0
  8. package/lib/concurrency.js +1 -0
  9. package/lib/config.d.ts +205 -0
  10. package/lib/config.js +1 -0
  11. package/lib/diagnostics.d.ts +86 -0
  12. package/lib/diagnostics.js +1 -0
  13. package/lib/gpuAgentProtocol.d.ts +196 -0
  14. package/lib/gpuAgentProtocol.js +1 -0
  15. package/lib/index.d.ts +74 -435
  16. package/lib/index.js +1 -1
  17. package/lib/jsonFile.d.ts +8 -0
  18. package/lib/jsonFile.js +1 -0
  19. package/lib/litematic.d.ts +103 -0
  20. package/lib/litematic.js +1 -0
  21. package/lib/messageDelivery.d.ts +82 -0
  22. package/lib/messageDelivery.js +1 -0
  23. package/lib/messageFiles.d.ts +93 -0
  24. package/lib/messageFiles.js +1 -0
  25. package/lib/officialProxy.d.ts +12 -0
  26. package/lib/officialProxy.js +1 -0
  27. package/lib/onebotCompat.d.ts +29 -0
  28. package/lib/onebotCompat.js +1 -0
  29. package/lib/projectionCache.d.ts +83 -0
  30. package/lib/projectionCache.js +1 -0
  31. package/lib/projectionSearch.d.ts +3 -0
  32. package/lib/projectionSearch.js +1 -0
  33. package/lib/rateLimit.d.ts +18 -0
  34. package/lib/rateLimit.js +1 -0
  35. package/lib/render/cpu.d.ts +23 -0
  36. package/lib/render/cpu.js +1 -0
  37. package/lib/render/externalGpu.d.ts +12 -0
  38. package/lib/render/externalGpu.js +1 -0
  39. package/lib/render/gpuAgent.d.ts +7 -0
  40. package/lib/render/gpuAgent.js +1 -0
  41. package/lib/render/imageValidation.d.ts +18 -0
  42. package/lib/render/imageValidation.js +1 -0
  43. package/lib/render/javaBridge.d.ts +11 -0
  44. package/lib/render/javaBridge.js +1 -0
  45. package/lib/render/standalone.d.ts +76 -0
  46. package/lib/render/standalone.js +1 -0
  47. package/lib/render/types.d.ts +5 -0
  48. package/lib/render/types.js +1 -0
  49. package/lib/render/webgl.d.ts +21 -0
  50. package/lib/render/webgl.js +1 -0
  51. package/lib/resourcePacks.d.ts +15 -0
  52. package/lib/resourcePacks.js +1 -0
  53. package/lib/runtimePaths.d.ts +8 -0
  54. package/lib/runtimePaths.js +1 -0
  55. package/lib/schematicFormats.d.ts +8 -0
  56. package/lib/schematicFormats.js +1 -0
  57. package/package.json +18 -14
  58. package/client/index.ts +0 -136
  59. package/client/style.css +0 -18
  60. package/dist/style.css +0 -1
  61. package/lib/gpu-agent-protocol.d.ts +0 -102
  62. package/lib/gpu-agent-protocol.js +0 -257
@@ -0,0 +1,205 @@
1
+ import { Schema } from "koishi";
2
+ import type { GpuAgentNodeConfig } from "./gpuAgentProtocol";
3
+ /** 多视角图片的排列与发送方式,与 Agent 协议保持一致 */
4
+ export type ImageSendLayout = "horizontal" | "vertical" | "separate";
5
+ /** 兼容旧配置,未知或缺省的图片布局回退为横向 */
6
+ export declare function normalizeImageSendLayout(value: unknown): ImageSendLayout;
7
+ /** Litematic 渲染插件的完整配置 */
8
+ export interface Config {
9
+ /** QQ 机器人的接入方式 */
10
+ qqBotType: QqBotType;
11
+ /** 官方 QQ 的实验性固定出口方式;默认关闭,不改变既有网络行为 */
12
+ officialProxyMode: OfficialProxyMode;
13
+ /** 已有 HTTP(S) 或 SOCKS 代理地址,仅在 proxy 模式使用 */
14
+ officialProxyUrl: string;
15
+ /** SSH 固定出口使用的可执行文件;密钥模式不会把秘密写入命令行 */
16
+ sshProxyExecutable: string;
17
+ /** SSH 固定出口服务器的数字 IP */
18
+ sshProxyHost: string;
19
+ /** SSH 固定出口服务器端口 */
20
+ sshProxyPort: number;
21
+ /** SSH 固定出口登录用户 */
22
+ sshProxyUser: string;
23
+ /** SSH 私钥路径;设置后优先于密码 */
24
+ sshProxyPrivateKey: string;
25
+ /** SSH 密码;仅交给 ssh2,不输出到日志或命令行 */
26
+ sshProxyPassword: string;
27
+ /** SSH SOCKS5 代理仅在本机监听的端口 */
28
+ sshProxyLocalPort: number;
29
+ /** 是否启用实验性官方 QQ 静默断线自动重载;默认关闭 */
30
+ officialGatewayWatchdog: boolean;
31
+ /** 独立渲染器使用的 Java 可执行文件;为空时自动查找 Java 21 或更高版本 */
32
+ standaloneJavaCommand: string;
33
+ /** Minecraft 客户端 JAR 或基础资源包路径 */
34
+ minecraftJarPath: string;
35
+ /** 自定义材质包路径,后面的材质包具有更高优先级 */
36
+ resourcePackPaths: string[];
37
+ /** 可按群或单次任务选择的命名材质包配置档 */
38
+ resourcePackProfiles: ResourcePackProfile[];
39
+ /** 未命中群映射时使用的材质包配置档 */
40
+ defaultResourcePackProfile: string;
41
+ /** 群聊到材质包配置档的覆盖映射 */
42
+ groupResourcePackProfiles: GroupResourcePackProfile[];
43
+ /** 用于生成投影图的渲染后端 */
44
+ renderEngine: "standalone" | "gpuAgent" | "java" | "webgl" | "cpu";
45
+ /** 独立 Java 渲染器 JAR 的路径 */
46
+ standaloneRendererJar: string;
47
+ /** 独立 Java 渲染任务的超时时间,单位为毫秒 */
48
+ standaloneRenderTimeout: number;
49
+ /** 独立 Java 渲染器首次运行时的最大堆内存,单位为 MiB */
50
+ standaloneJavaMaxHeapMb: number;
51
+ /** 内存不足后重试进程的最大堆内存,单位为 MiB */
52
+ standaloneJavaRetryMaxHeapMb: number;
53
+ /** 检测到内存不足时允许重启 Java 进程的次数 */
54
+ standaloneJavaMemoryRestartLimit: number;
55
+ /** 自动处理的最大文件大小,单位为 KiB */
56
+ maxFileSize: number;
57
+ /** 私聊自动处理的独立文件大小上限,单位为 KiB */
58
+ privateMaxFileSize: number;
59
+ /** 每个用户每分钟允许的渲染请求数;0 表示不限流 */
60
+ renderRateLimitPerMinute: number;
61
+ /** 投影声明方块数及所有区域总体积的上限 */
62
+ maxBlocks: number;
63
+ /** 同时执行的本地渲染任务数;0 表示不限制 */
64
+ maxConcurrentRenders: number;
65
+ /** 六面图和 CPU 渲染结果的最长边像素上限 */
66
+ outputSize: number;
67
+ /** CPU 正二轴测渲染中方块菱形的半宽 */
68
+ isometricCellSize: number;
69
+ /** PNG 背景颜色,格式为十六进制 RGB */
70
+ background: string;
71
+ /** 单张渲染 PNG 的最大字节数 */
72
+ maxRenderedImageBytes: number;
73
+ /** 是否将 PNG 背景输出为透明 */
74
+ transparentBackground: boolean;
75
+ /** 是否默认使用 QQ 合并转发发送渲染结果 */
76
+ sendAsForward: boolean;
77
+ /** 是否允许私聊附件和私聊命令触发渲染;默认关闭以保持原行为 */
78
+ allowPrivateRender: boolean;
79
+ /** 是否在每张渲染图前显示视图标题 */
80
+ showViewTitles: boolean;
81
+ /** 官方 QQ 图片布局与 Agent 拼接请求,默认横向;separate 表示逐张发送 */
82
+ imageSendLayout: ImageSendLayout;
83
+ /** 每页投影搜索结果上限,范围 1–100,默认 15 */
84
+ projectionSearchResultLimit: number;
85
+ /** 是否显示投影名称;默认开启,仅影响发送文本 */
86
+ showMetadataProjectionName: boolean;
87
+ /** 是否显示保存者游戏 ID;默认开启,仅影响发送文本 */
88
+ showMetadataAuthor: boolean;
89
+ /** 是否显示创建时间;默认开启,仅影响发送文本 */
90
+ showMetadataCreatedAt: boolean;
91
+ /** 是否显示方块数和总体积;默认开启,仅影响发送文本 */
92
+ showMetadataBlockStats: boolean;
93
+ /** 是否显示投影尺寸;默认开启,仅影响发送文本 */
94
+ showMetadataSize: boolean;
95
+ /** 是否显示 Litematic 格式版本;默认开启,仅影响发送文本 */
96
+ showMetadataLitematicVersion: boolean;
97
+ /** 是否显示游戏版本和数据版本;默认开启,仅影响发送文本 */
98
+ showMetadataGameVersion: boolean;
99
+ /** 是否在结果消息中引用并提及发送者 */
100
+ replyAndMention: boolean;
101
+ /** 是否为支持的发送方式附加六面正交合成图 */
102
+ sixFaceOverview: boolean;
103
+ /** 六面正交合成图的排列方向 */
104
+ sixFaceLayout: SixFaceLayout;
105
+ /** 针对指定群聊覆盖的发送选项 */
106
+ groupSendOptions: GroupSendOption[];
107
+ /** 是否启用群白名单 */
108
+ groupWhitelistEnabled: boolean;
109
+ /** 启用后只允许列表中的群渲染 */
110
+ groupWhitelist: string[];
111
+ /** 是否启用群黑名单 */
112
+ groupBlacklistEnabled: boolean;
113
+ /** 启用后禁止列表中的群渲染,优先级高于白名单 */
114
+ groupBlacklist: string[];
115
+ /** 文件下载及 WebGL 页面操作的超时时间,单位为毫秒 */
116
+ renderTimeout: number;
117
+ /** 用户直链渲染的网络访问策略 */
118
+ directUrlPolicy: "disabled" | "public" | "any";
119
+ /** public 策略下仍允许访问的精确主机名 */
120
+ directUrlAllowedHosts: string[];
121
+ /** 持久化渲染缓存的目录 */
122
+ cacheDirectory: string;
123
+ /** 所有版本渲染缓存的总容量上限,单位为 GiB,不包含持久投影源文件 */
124
+ cacheMaxSizeGb: number;
125
+ /** 渲染缓存的最长保留时间,单位为天;0 表示不按时间清理,源文件始终保留 */
126
+ cacheMaxAgeDays: number;
127
+ /** 聚合渲染诊断信息的 JSON 文件路径 */
128
+ diagnosticsFilePath: string;
129
+ /** 启用诊断 HTTP 下载端点时使用的访问令牌;为空时不注册端点 */
130
+ diagnosticsHttpToken: string;
131
+ /** 用于上报渲染异常的 Sentry DSN */
132
+ sentryDsn: string;
133
+ /** 是否修复 OneBot 适配器对群文件上传事件的映射 */
134
+ patchOneBotGroupUpload: boolean;
135
+ /** Fabric Java 渲染桥交换任务文件的目录 */
136
+ javaBridgeDirectory: string;
137
+ /** 优先调用的外部 GPU 渲染器命令 */
138
+ gpuRendererCommand: string;
139
+ /** 等待 Fabric Java 渲染桥返回结果的超时时间,单位为毫秒 */
140
+ javaRenderTimeout: number;
141
+ /** Java 渲染器最终输出图像的边长 */
142
+ javaResolution: number;
143
+ /** Java 渲染器的离屏超采样倍数 */
144
+ javaSupersampling: number;
145
+ /** WebGL 渲染的质量预设 */
146
+ webglQuality: "standard" | "high" | "ultra";
147
+ /** WebGL 单张渲染图的宽度 */
148
+ webglWidth: number;
149
+ /** WebGL 单张渲染图的高度 */
150
+ webglHeight: number;
151
+ /** 是否将 WebGL 正二轴测结果裁成正方形 */
152
+ isometricSquare: boolean;
153
+ /** 正二轴测主体在画布中的最大占比 */
154
+ isometricFill: number;
155
+ /** 正二轴测视图绕竖直轴旋转的角度 */
156
+ isometricRotation: number;
157
+ /** 正二轴测视图的俯仰角 */
158
+ isometricSlant: number;
159
+ /** 是否启动 GPU Agent v2 WebSocket 服务;与选择渲染引擎分开控制 */
160
+ gpuAgentEnabled: boolean;
161
+ /** GPU Agent v2 服务监听地址 */
162
+ gpuAgentListenHost: string;
163
+ /** GPU Agent v2 服务监听端口 */
164
+ gpuAgentListenPort: number;
165
+ /** GPU Agent v2 WebSocket 路径 */
166
+ gpuAgentPath: string;
167
+ /** 允许连接的 GPU Agent 节点及其独立密钥 */
168
+ gpuAgentNodes: GpuAgentNodeConfig[];
169
+ /** 单个 GPU Agent 渲染任务的等待时间,单位为毫秒 */
170
+ gpuAgentTimeout: number;
171
+ /** GPU Agent 失败后是否回退到本地 standalone */
172
+ gpuAgentFallback: boolean;
173
+ }
174
+ /** 自建 QQ 中发送多张渲染图的方式 */
175
+ export type SendMode = "forward" | "combined";
176
+ /** 群聊是否覆盖全局的引用及提及设置 */
177
+ export type ReplyAndMentionOverride = "inherit" | "enabled" | "disabled";
178
+ /** 六面正交合成图的排列方向 */
179
+ export type SixFaceLayout = "horizontal" | "vertical";
180
+ /** QQ 机器人的接入方式 */
181
+ export type QqBotType = "official" | "selfHosted";
182
+ /** 官方 QQ 实验性固定出口模式 */
183
+ export type OfficialProxyMode = "disabled" | "proxy" | "ssh";
184
+ /** 指定群聊的消息发送覆盖项 */
185
+ export interface GroupSendOption {
186
+ /** 要应用覆盖设置的 QQ 群号 */
187
+ groupId: string;
188
+ /** 多张渲染图的发送方式 */
189
+ sendMode: SendMode;
190
+ /** 引用及提及行为相对于全局配置的覆盖方式 */
191
+ replyAndMention: ReplyAndMentionOverride;
192
+ }
193
+ /** 一组可复用的 Minecraft 基础资源与覆盖材质包。 */
194
+ export interface ResourcePackProfile {
195
+ name: string;
196
+ minecraftJarPath: string;
197
+ resourcePackPaths: string[];
198
+ }
199
+ /** 指定群聊使用的材质包配置档。 */
200
+ export interface GroupResourcePackProfile {
201
+ groupId: string;
202
+ profile: string;
203
+ }
204
+ /** Koishi 控制台使用的插件配置模式 */
205
+ export declare const Config: Schema<Config>;
package/lib/config.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Config=void 0,exports.normalizeImageSendLayout=normalizeImageSendLayout;const koishi_1=require("koishi");function normalizeImageSendLayout(i){return"vertical"===i||"separate"===i?i:"horizontal"}exports.Config=koishi_1.Schema.intersect([koishi_1.Schema.object({qqBotType:koishi_1.Schema.union([koishi_1.Schema.const("official").description("QQ 官方机器人"),koishi_1.Schema.const("selfHosted").description("自建 QQ(OneBot / NapCat)")]).role("radio").default("selfHosted").description("机器人接入类型;决定图片、合并转发、引用和 @ 的发送方式"),patchOneBotGroupUpload:koishi_1.Schema.boolean().default(!0).description("自建 QQ:启动时修复 OneBot 群文件上传事件;官方机器人不使用此项"),officialProxyMode:koishi_1.Schema.union([koishi_1.Schema.const("disabled").description("关闭中转"),koishi_1.Schema.const("proxy").description("使用已有代理"),koishi_1.Schema.const("ssh").description("自动建立 SSH 中转")]).role("radio").default("disabled").description("实验性:仅官方 QQ 使用固定公网出口;默认关闭,不改变现有网络行为").experimental(),officialProxyUrl:koishi_1.Schema.string().default("").description("实验性:已有 socks5h、socks5、http 或 https 代理地址").experimental(),sshProxyExecutable:koishi_1.Schema.string().default("ssh").description("实验性:密钥模式使用的 SSH 可执行文件").experimental(),sshProxyHost:koishi_1.Schema.string().default("").description("实验性:SSH 中转服务器的数字 IP,例如 203.0.113.10").experimental(),sshProxyPort:koishi_1.Schema.natural().min(1).max(65535).default(22).description("实验性:SSH 中转服务器端口").experimental(),sshProxyUser:koishi_1.Schema.string().default("root").description("实验性:SSH 登录用户名").experimental(),sshProxyPrivateKey:koishi_1.Schema.path({filters:["file"]}).default("").description("实验性:SSH 私钥路径;填写后优先使用密钥登录").experimental(),sshProxyPassword:koishi_1.Schema.string().role("secret").default("").description("实验性:SSH 登录密码;不会进入命令行或日志").experimental(),sshProxyLocalPort:koishi_1.Schema.natural().min(1).max(65535).default(1080).description("实验性:仅监听 127.0.0.1 的 SOCKS5 端口").experimental(),officialGatewayWatchdog:koishi_1.Schema.boolean().default(!1).description("实验性:8 分钟无入站消息时热重载 QQ 适配器;默认关闭").experimental()}).description("机器人接入"),koishi_1.Schema.object({renderEngine:koishi_1.Schema.union([koishi_1.Schema.const("standalone"),koishi_1.Schema.const("gpuAgent").description("独立 GPU Agent v2(主动连接)"),koishi_1.Schema.const("java"),koishi_1.Schema.const("webgl"),koishi_1.Schema.const("cpu")]).default("standalone").description("渲染引擎;保留本地全部引擎,并新增主动连接的 GPU Agent v2"),maxFileSize:koishi_1.Schema.natural().min(1).default(1024).description("群聊自动处理的最大文件大小(KB)"),privateMaxFileSize:koishi_1.Schema.natural().min(1).default(1024).description("私聊自动处理的独立文件大小(KB);不改变群聊上限"),renderRateLimitPerMinute:koishi_1.Schema.natural().max(600).default(0).description("每个用户每分钟允许的渲染请求数;设为 0 表示不限流"),maxBlocks:koishi_1.Schema.natural().min(1).max(2e9).default(5e6).description("投影区域体积及声明方块数上限;用于拒绝尺寸异常或资源消耗过大的投影"),maxConcurrentRenders:koishi_1.Schema.natural().max(64).default(2).description("同时执行的本地渲染任务数;设为 0 表示不限制"),outputSize:koishi_1.Schema.natural().min(128).max(4096).default(1024).description("六面图和 CPU 渲染最长边的最大像素数"),background:koishi_1.Schema.string().default("#000000").description("PNG 背景颜色"),maxRenderedImageBytes:koishi_1.Schema.natural().min(1048576).max(268435456).default(67108864).description("单张渲染 PNG 的最大大小(字节)"),transparentBackground:koishi_1.Schema.boolean().default(!1).description("输出透明背景"),isometricFill:koishi_1.Schema.percent().default(.78).description("正二轴测主体在画布中的最大占比"),isometricRotation:koishi_1.Schema.number().min(0).max(360).step(1).default(135).description("Isometric Renders 绕竖直轴的基准旋转角"),isometricSlant:koishi_1.Schema.number().min(-90).max(90).step(1).default(36).description("Isometric Renders 俯仰角;36° 为正二轴测预设")}).description("渲染设置"),koishi_1.Schema.object({allowPrivateRender:koishi_1.Schema.boolean().default(!1).description("允许私聊附件及私聊命令触发渲染;默认关闭以保持现有行为"),sendAsForward:koishi_1.Schema.boolean().default(!1).description("仅自建 QQ:开启为合并转发,关闭为联合发送;官方 QQ 忽略此项"),showViewTitles:koishi_1.Schema.boolean().default(!1).description("仅自建 QQ:发送图片时显示视图标题"),imageSendLayout:koishi_1.Schema.union([koishi_1.Schema.const("horizontal").description("横向拼接"),koishi_1.Schema.const("vertical").description("竖向拼接"),koishi_1.Schema.const("separate").description("逐张发送")]).default("horizontal").description("官方 QQ 和 GPU Agent 图片布局,合成图超过 10 MiB 时自动逐张发送"),projectionSearchResultLimit:koishi_1.Schema.natural().min(1).max(100).default(15).description("投影搜索最多显示的结果数"),showMetadataProjectionName:koishi_1.Schema.boolean().default(!0).description("投影信息:显示投影名称"),showMetadataAuthor:koishi_1.Schema.boolean().default(!0).description("投影信息:显示保存者游戏 ID"),showMetadataCreatedAt:koishi_1.Schema.boolean().default(!0).description("投影信息:显示创建时间"),showMetadataBlockStats:koishi_1.Schema.boolean().default(!0).description("投影信息:显示方块数/体积"),showMetadataSize:koishi_1.Schema.boolean().default(!0).description("投影信息:显示尺寸"),showMetadataLitematicVersion:koishi_1.Schema.boolean().default(!0).description("投影信息:显示Litematic 版本"),showMetadataGameVersion:koishi_1.Schema.boolean().default(!0).description("投影信息:显示游戏版本和数据版本"),replyAndMention:koishi_1.Schema.boolean().default(!1).description("自建 QQ 会引用并 @ 发送者;官方 QQ 仅引用,避免显示 OpenID"),sixFaceOverview:koishi_1.Schema.boolean().default(!0).description("合并转发时生成并附加上、下、东、南、西、北六面正交合成图"),sixFaceLayout:koishi_1.Schema.union([koishi_1.Schema.const("horizontal").description("横向 3×2"),koishi_1.Schema.const("vertical").description("纵向 2×3")]).default("horizontal").description("六面正交合成图布局;最长边由 outputSize 控制"),groupSendOptions:koishi_1.Schema.array(koishi_1.Schema.object({groupId:koishi_1.Schema.string().description("QQ群号"),sendMode:koishi_1.Schema.union([koishi_1.Schema.const("forward").description("合并转发"),koishi_1.Schema.const("combined").description("联合发送(一条普通消息)")]).default("forward"),replyAndMention:koishi_1.Schema.union([koishi_1.Schema.const("inherit").description("继承全局设置"),koishi_1.Schema.const("enabled").description("开启回复 @"),koishi_1.Schema.const("disabled").description("关闭回复 @")]).default("inherit")})).default([]).description("按群覆盖发送方式和回复设置;官方 QQ 只使用引用开关,自建 QQ 同时使用发送模式和 @"),groupWhitelistEnabled:koishi_1.Schema.boolean().default(!1).description("启用群白名单:开启后仅白名单内的群可以渲染"),groupWhitelist:koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("群白名单(需开启上面的开关):官方 QQ 填开放平台群哈希,自建 QQ 填群号"),groupBlacklistEnabled:koishi_1.Schema.boolean().default(!1).description("启用群黑名单:开启后黑名单内的群始终不渲染,优先级高于白名单"),groupBlacklist:koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("群黑名单(需开启上面的开关)")}).description("发送设置"),koishi_1.Schema.object({standaloneJavaCommand:koishi_1.Schema.string().default("").description("独立渲染器使用的 Java 可执行文件;推荐 Java 21+,留空自动查找"),minecraftJarPath:koishi_1.Schema.string().default("").description("可选的 Minecraft 客户端 JAR 或基础资源包;留空使用内置 26.2 原版资源"),resourcePackPaths:koishi_1.Schema.array(koishi_1.Schema.string()).role("table").default([]).description("自定义材质包路径;控制台可上传 ZIP,越靠后优先级越高"),resourcePackProfiles:koishi_1.Schema.array(koishi_1.Schema.object({name:koishi_1.Schema.string().required().description("配置档唯一名称"),minecraftJarPath:koishi_1.Schema.string().default("").description("基础资源包;留空继承上方 minecraftJarPath"),resourcePackPaths:koishi_1.Schema.array(koishi_1.Schema.string()).role("table").default([]).description("此配置档的覆盖材质包;越靠后优先级越高")})).default([]).description("命名材质包配置档;旧 resourcePackPaths 作为 default 配置档"),defaultResourcePackProfile:koishi_1.Schema.string().default("default").description("未指定或未命中群映射时使用的配置档名称"),groupResourcePackProfiles:koishi_1.Schema.array(koishi_1.Schema.object({groupId:koishi_1.Schema.string().required().description("QQ群号或官方 QQ 群哈希"),profile:koishi_1.Schema.string().required().description("材质包配置档名称")})).role("table").default([]).description("按群选择材质包配置档;重复群号以最后一项为准"),standaloneRendererJar:koishi_1.Schema.string().default("").description("独立渲染器 JAR;留空使用插件内置版本"),standaloneRenderTimeout:koishi_1.Schema.natural().min(1e4).default(18e4).description("独立 Java 渲染超时(毫秒)"),standaloneJavaMaxHeapMb:koishi_1.Schema.natural().min(128).max(32768).step(8).default(200).description("首次独立渲染的最大堆内存(MiB)"),standaloneJavaRetryMaxHeapMb:koishi_1.Schema.natural().min(256).max(32768).step(128).default(2048).description("内存不足时新进程重试的最大堆内存(MiB)"),standaloneJavaMemoryRestartLimit:koishi_1.Schema.natural().max(3).default(1).description("检测到内存不足后启动全新进程重试的次数"),javaResolution:koishi_1.Schema.natural().min(256).max(4096).default(1024).description("Java 渲染最终输出边长"),javaSupersampling:koishi_1.Schema.natural().min(1).max(4).default(2).description("离屏超采样倍数")}).description("独立渲染器"),koishi_1.Schema.object({renderTimeout:koishi_1.Schema.natural().min(1e3).default(3e4).description("文件下载超时(毫秒)"),directUrlPolicy:koishi_1.Schema.union([koishi_1.Schema.const("disabled").description("关闭直链渲染命令"),koishi_1.Schema.const("public").description("仅允许公网 HTTP(S) 地址"),koishi_1.Schema.const("any").description("允许私网地址(仅可信环境使用)")]).role("radio").default("public").description("litematic.render 直链的网络访问策略;群文件下载不受此项影响"),directUrlAllowedHosts:koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("public 策略额外允许的精确主机名,例如内部对象存储域名"),cacheDirectory:koishi_1.Schema.string().default("data/litematic-renderer-cache").description("持久缓存目录;按插件版本和投影 SHA-256 分区"),cacheMaxSizeGb:koishi_1.Schema.number().min(1).max(1024).step(1).default(20).description("所有版本渲染缓存总上限(GiB),超出后按最久未使用清理,保留投影源文件"),cacheMaxAgeDays:koishi_1.Schema.number().min(0).max(3650).step(1).default(30).description("渲染缓存的最长保留时间(天);设为 0 可关闭按时间清理,保留投影源文件"),diagnosticsFilePath:koishi_1.Schema.string().default("data/litematic-renderer-diagnostics.json").description("渲染诊断持久化文件路径;导出地址固定为 /litematic-renderer/diagnostics"),diagnosticsHttpToken:koishi_1.Schema.string().role("secret").default("").description("诊断 HTTP 下载令牌;留空时禁用 /litematic-renderer/diagnostics"),sentryDsn:koishi_1.Schema.string().default("").description("Sentry DSN,用于上报渲染错误;留空时读取 SENTRY_DSN 环境变量").experimental()}).description("缓存与诊断"),koishi_1.Schema.object({isometricCellSize:koishi_1.Schema.natural().min(2).max(32).default(7).description("CPU 正二轴测方块菱形半宽"),javaRenderTimeout:koishi_1.Schema.natural().min(1e4).default(18e4).description("等待 Minecraft Java 渲染桥的超时(毫秒)"),webglQuality:koishi_1.Schema.union([koishi_1.Schema.const("standard"),koishi_1.Schema.const("high"),koishi_1.Schema.const("ultra")]).default("high").description("WebGL 渲染质量"),webglWidth:koishi_1.Schema.natural().min(256).max(2048).default(800).description("WebGL 单张图宽度"),webglHeight:koishi_1.Schema.natural().min(256).max(2048).default(600).description("WebGL 单张图高度"),isometricSquare:koishi_1.Schema.boolean().default(!0).description("将 WebGL 正二轴测图输出为正方形"),javaBridgeDirectory:koishi_1.Schema.string().default("").description("renderEngine=java 时使用的 Fabric Java 渲染桥任务目录"),gpuRendererCommand:koishi_1.Schema.string().default("").description("可选外部 GPU 渲染器命令;非空时优先尝试,失败后回退到 renderEngine")}).description("高级设置"),koishi_1.Schema.object({gpuAgentEnabled:koishi_1.Schema.boolean().default(!1).description("启动 GPU Agent v2 WebSocket 服务;默认关闭,不占用监听端口"),gpuAgentListenHost:koishi_1.Schema.string().default("0.0.0.0").description("GPU Agent v2 监听地址"),gpuAgentListenPort:koishi_1.Schema.natural().min(1).max(65535).default(39180).description("GPU Agent v2 监听端口"),gpuAgentPath:koishi_1.Schema.string().default("/litematic-renderer/agent/v2").description("GPU Agent v2 WebSocket 路径"),gpuAgentNodes:koishi_1.Schema.array(koishi_1.Schema.object({agentId:koishi_1.Schema.string().description("GPU 节点唯一 ID"),sharedSecret:koishi_1.Schema.string().role("secret").description("该节点的 HMAC 共享密钥"),enabled:koishi_1.Schema.boolean().default(!0).description("允许此节点连接")})).default([]).description("允许连接的 GPU 节点;每个节点使用独立密钥"),gpuAgentTimeout:koishi_1.Schema.natural().min(1e4).max(36e5).default(24e4).description("等待 GPU Agent 完成任务的超时(毫秒)"),gpuAgentFallback:koishi_1.Schema.boolean().default(!0).description("GPU Agent 不可用或失败时回退到本地 standalone")}).description("GPU Agent v2")]);
@@ -0,0 +1,86 @@
1
+ import type { Context } from "koishi";
2
+ import type { Config } from "./config";
3
+ export interface DiagnosticsSummary {
4
+ generatedAt?: string;
5
+ blockKinds: number;
6
+ blockOccurrences: number;
7
+ errorKinds: number;
8
+ errorOccurrences: number;
9
+ topBlocks: Array<{
10
+ state: string;
11
+ reason: string;
12
+ count: number;
13
+ }>;
14
+ recentErrors: Array<{
15
+ engine: string;
16
+ message: string;
17
+ count: number;
18
+ generatedAt?: string;
19
+ }>;
20
+ }
21
+ /** 读取诊断聚合文件并返回适合控制台展示的定长摘要。 */
22
+ export declare function getDiagnosticsSummary(path: string): Promise<DiagnosticsSummary>;
23
+ /**
24
+ * 将单次独立渲染诊断合并到插件级诊断文件
25
+ *
26
+ * @remarks
27
+ * 相同方块问题会累加计数并最多保留 20 个样本,相同渲染错误也会累加计数
28
+ *
29
+ * @param output - 包含 `render-diagnostics.json` 的渲染输出目录
30
+ * @param destination - 插件级诊断 JSON 文件路径
31
+ * @param logger - 用于报告新增诊断类别的 Koishi 日志器
32
+ * @returns 无诊断内容时直接解决,否则在合并文件写入后解决
33
+ * @throws 无法读取或写入诊断文件时抛出文件系统错误
34
+ */
35
+ export declare function mergeRenderDiagnostics(output: string, destination: string, logger: ReturnType<Context["logger"]>): Promise<void>;
36
+ /**
37
+ * 将其他插件版本生成的诊断文件移动到归档目录
38
+ *
39
+ * @param path - 当前诊断文件路径
40
+ * @param archiveDirectory - 旧版本诊断归档目录
41
+ * @param logger - 用于报告归档结果的 Koishi 日志器
42
+ * @returns 检查或归档完成后解决的 Promise
43
+ * @throws 无法读取或移动诊断文件时抛出文件系统错误
44
+ */
45
+ export declare function rotateDiagnosticsFile(path: string, archiveDirectory: string, logger: ReturnType<Context["logger"]>): Promise<void>;
46
+ /**
47
+ * 禁用当前诊断快照并重新创建空白诊断文件
48
+ *
49
+ * @param path - 当前诊断文件路径
50
+ * @param disabledDirectory - 禁用快照的存放目录
51
+ * @returns 可直接发送给管理员的处理结果
52
+ * @throws 无法移动或重新创建诊断文件时抛出文件系统错误
53
+ */
54
+ export declare function disableDiagnosticsSnapshot(path: string, disabledDirectory: string): Promise<string>;
55
+ /**
56
+ * 向插件级诊断文件追加无需单次渲染目录的错误
57
+ *
58
+ * @param destination - 插件级诊断文件路径
59
+ * @param renderId - 用于错误去重的渲染标识
60
+ * @param engine - 发生问题的处理阶段或渲染引擎
61
+ * @param message - 诊断错误文本
62
+ * @param logger - 用于报告诊断写入位置的 Koishi 日志器
63
+ * @returns 诊断写入完成后解决的 Promise
64
+ * @throws 无法读写诊断文件时抛出文件系统错误
65
+ */
66
+ export declare function appendGlobalRenderError(destination: string, renderId: string, engine: string, message: string, logger: ReturnType<Context["logger"]>): Promise<void>;
67
+ /**
68
+ * 记录单次渲染错误并将其合并到插件级诊断文件
69
+ *
70
+ * @param output - 当前渲染输出目录
71
+ * @param destination - 插件级诊断文件路径
72
+ * @param engine - 当前渲染引擎
73
+ * @param error - 捕获到的任意错误值
74
+ * @param logger - 用于报告诊断写入的 Koishi 日志器
75
+ * @returns 本地记录和全局合并完成后解决的 Promise
76
+ * @throws 无法写入诊断文件时抛出文件系统错误
77
+ */
78
+ export declare function appendRenderError(output: string, destination: string, engine: Config["renderEngine"], error: unknown, logger: ReturnType<Context["logger"]>): Promise<void>;
79
+ /**
80
+ * 将内部渲染错误转换为不泄露本地路径的用户提示
81
+ *
82
+ * @param error - 捕获到的任意错误值
83
+ * @param config - 格式化文件大小提示所需的配置
84
+ * @returns 可直接发送给用户的中文错误消息
85
+ */
86
+ export declare function formatRenderError(error: unknown, config: Pick<Config, "maxFileSize">): string;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getDiagnosticsSummary=getDiagnosticsSummary,exports.mergeRenderDiagnostics=mergeRenderDiagnostics,exports.rotateDiagnosticsFile=rotateDiagnosticsFile,exports.disableDiagnosticsSnapshot=disableDiagnosticsSnapshot,exports.appendGlobalRenderError=appendGlobalRenderError,exports.appendRenderError=appendRenderError,exports.formatRenderError=formatRenderError;const node_fs_1=require("node:fs"),node_path_1=require("node:path"),cache_1=require("./cache"),jsonFile_1=require("./jsonFile"),runtimePaths_1=require("./runtimePaths");async function getDiagnosticsSummary(e){const r=await(0,jsonFile_1.readJson)((0,node_path_1.resolve)(e))??{},n=Array.isArray(r.blocks)?r.blocks:[],t=Array.isArray(r.errors)?r.errors:[],s=e=>Math.max(0,Number(e?.count)||0);return{generatedAt:"string"==typeof r.generatedAt?r.generatedAt:void 0,blockKinds:n.length,blockOccurrences:n.reduce((e,r)=>e+s(r),0),errorKinds:t.length,errorOccurrences:t.reduce((e,r)=>e+s(r),0),topBlocks:n.map(e=>({state:String(e?.state??"unknown"),reason:String(e?.reason??"unknown"),count:s(e)})).sort((e,r)=>r.count-e.count).slice(0,10),recentErrors:t.map(e=>({engine:String(e?.engine??"unknown"),message:String(e?.message??"unknown"),count:s(e),generatedAt:"string"==typeof e?.generatedAt?e.generatedAt:void 0})).sort((e,r)=>String(r.generatedAt??"").localeCompare(String(e.generatedAt??""))).slice(0,10)}}async function mergeRenderDiagnostics(e,r,n){const t=(0,node_path_1.join)(e,"render-diagnostics.json"),s=await(0,jsonFile_1.readJson)(t);if(!s)return;const o=Array.isArray(s.blocks)?s.blocks:[],a=Array.isArray(s.errors)?s.errors:[];if(!o.length&&!a.length)return;const i=(0,node_path_1.resolve)(r),c=await(0,jsonFile_1.readJson)(i)??{format:2,generatedAt:(new Date).toISOString(),blocks:[],errors:[]},d=new Map;for(const e of c.blocks??[])d.set(`${e.state}\0${e.reason}`,e);for(const e of o){const r=`${e.state}\0${e.reason}`,n=d.get(r);n?(n.count=Number(n.count??0)+Number(e.count??0),n.samples=[...n.samples??[],...e.samples??[]].slice(0,20)):d.set(r,{...e,samples:e.samples??[]})}const g=new Map;for(const e of c.errors??[])g.set(`${e.renderId}\0${e.engine}\0${e.message}`,e);for(const e of a){const r=`${e.renderId}\0${e.engine}\0${e.message}`,n=g.get(r);n?n.count=Number(n.count??0)+Number(e.count??0):g.set(r,{...e})}const u={format:2,pluginVersion:runtimePaths_1.PLUGIN_VERSION,generatedAt:(new Date).toISOString(),blocks:[...d.values()],errors:[...g.values()]};await node_fs_1.promises.mkdir((0,node_path_1.resolve)(r,".."),{recursive:!0}).catch(()=>{}),await node_fs_1.promises.writeFile(i,JSON.stringify(u,null,2)+"\n"),o.length&&n.warn(`记录 ${o.length} 类无法正常渲染的方块;诊断已保存到 ${i}`),a.length&&n.warn(`记录 ${a.length} 类渲染错误;诊断已保存到 ${i}`)}async function rotateDiagnosticsFile(e,r,n){const t=await(0,jsonFile_1.readJson)(e);if(!t||t.pluginVersion===runtimePaths_1.PLUGIN_VERSION)return;await node_fs_1.promises.mkdir(r,{recursive:!0});const s=(0,cache_1.cachePathSegment)("string"==typeof t.pluginVersion?t.pluginVersion:"legacy"),o=formatDiagnosticsTimestamp(new Date),a=(0,node_path_1.join)(r,`litematic-renderer-diagnostics-v${s}-${o}.json`);await node_fs_1.promises.rename(e,a),n.info(`已将旧版诊断汇总归档到 ${a}`)}async function disableDiagnosticsSnapshot(e,r){if(!await(0,jsonFile_1.readJson)(e))return"当前没有可禁用的诊断汇总";await node_fs_1.promises.mkdir(r,{recursive:!0});const n=(0,node_path_1.join)(r,`litematic-renderer-diagnostics-disabled-${formatDiagnosticsTimestamp(new Date)}.json`);return await node_fs_1.promises.rename(e,n),await node_fs_1.promises.writeFile(e,JSON.stringify({format:2,pluginVersion:runtimePaths_1.PLUGIN_VERSION,generatedAt:(new Date).toISOString(),blocks:[],errors:[]},null,2)+"\n"),`当前诊断已移入禁用文件夹:${n}`}async function appendGlobalRenderError(e,r,n,t,s){const o=(0,node_path_1.resolve)(e),a=await(0,jsonFile_1.readJson)(o)??{format:2,pluginVersion:runtimePaths_1.PLUGIN_VERSION,generatedAt:(new Date).toISOString(),blocks:[],errors:[]};a.format=2,a.pluginVersion=runtimePaths_1.PLUGIN_VERSION,a.errors??=[];const i=a.errors.find(e=>e.renderId===r&&e.engine===n&&e.message===t);i?i.count=Number(i.count??0)+1:a.errors.push({renderId:r,engine:n,message:t,count:1,generatedAt:(new Date).toISOString()}),await node_fs_1.promises.mkdir((0,node_path_1.dirname)(o),{recursive:!0}),await node_fs_1.promises.writeFile(o,JSON.stringify(a,null,2)+"\n"),s.warn(`渲染问题已记录到 ${o}`)}function formatDiagnosticsTimestamp(e){const r=e=>String(e).padStart(2,"0");return`${e.getFullYear()}${r(e.getMonth()+1)}${r(e.getDate())}-${r(e.getHours())}${r(e.getMinutes())}${r(e.getSeconds())}`}async function appendRenderError(e,r,n,t,s){const o=(0,node_path_1.join)(e,"render-diagnostics.json"),a=await(0,jsonFile_1.readJson)(o)??{format:2,generatedAt:(new Date).toISOString(),blocks:[],errors:[]};a.format=2,a.errors??=[];const i=t instanceof Error?t.message:String(t),c=(0,node_path_1.basename)(e),d=a.errors.find(e=>e.renderId===c&&e.engine===n&&e.message===i);d?d.count=Number(d.count??0)+1:a.errors.push({renderId:c,engine:n,message:i,count:1,generatedAt:(new Date).toISOString()}),await node_fs_1.promises.writeFile(o,JSON.stringify(a,null,2)+"\n"),await mergeRenderDiagnostics(e,r,s)}function formatRenderError(e,r){const n=e instanceof Error?e.message:String(e);return/投影方块数或区域体积超过/i.test(n)?`${n},不渲染`:/文件超过|file size|file.*limit/i.test(n)?`文件大小超过 ${(r.maxFileSize/1024).toFixed(2)} MB,不渲染`:/java 21\+|未找到.*java|java.*not found/i.test(n)?"未找到 Java 21+,请在插件配置中检查 Java 可执行文件设置":/standalone renderer|独立.*渲染器.*不存在|渲染器.*not exist/i.test(n)?"独立渲染器不可用,请重装插件或检查 Java 渲染配置":/minecraft.*resource|resource pack|原版资源|材质包.*不存在/i.test(n)?"Minecraft 原版资源包不可用,请检查资源包配置":"投影渲染失败,请检查渲染器配置或导出诊断文件"}
@@ -0,0 +1,196 @@
1
+ import { EventEmitter } from "node:events";
2
+ export declare const GPU_PROTOCOL_VERSION = 2;
3
+ export declare const GPU_BINARY_HEADER_LIMIT: number;
4
+ export interface RenderView {
5
+ id: string;
6
+ name?: string;
7
+ yaw: number;
8
+ pitch: number;
9
+ zoom?: number;
10
+ autoFill?: boolean;
11
+ width: number;
12
+ height: number;
13
+ background: string;
14
+ transparentBackground: boolean;
15
+ supersampling: number;
16
+ }
17
+ export interface GpuRenderRequest {
18
+ /** 协议版本;本次扩展仍兼容 v2 */
19
+ version: 2;
20
+ /** 关联输入、进度与结果的唯一任务 ID */
21
+ id: string;
22
+ /** 源投影文件名,不包含目录 */
23
+ filename: string;
24
+ /** 任务请求的视角与输出参数 */
25
+ views: RenderView[];
26
+ /** 命名材质档;省略时仅允许 default 节点 */
27
+ resourcePackProfile?: string;
28
+ /** 来源群号,供 Agent 历史和诊断展示 */
29
+ sourceGroup?: string;
30
+ /** 来源用户标识,私聊任务也可以提供 */
31
+ sourceUser?: string;
32
+ /** 调用方插件版本,用于区分不同版本生成的缓存 */
33
+ pluginVersion?: string;
34
+ /** 本地渲染配置指纹;同一投影的不同配置必须独立缓存 */
35
+ renderConfigSha256?: string;
36
+ /** 图片拼接方向,省略时由 Agent 使用自己的默认设置 */
37
+ imageSendLayout?: "horizontal" | "vertical" | "separate";
38
+ }
39
+ export interface GpuAgentNodeConfig {
40
+ agentId: string;
41
+ sharedSecret: string;
42
+ enabled?: boolean;
43
+ }
44
+ export interface GpuAgentCapabilities {
45
+ /** Agent 渲染工具版本,参与节点缓存指纹 */
46
+ rendererVersion?: string;
47
+ /** Agent 使用的 Minecraft 版本 */
48
+ minecraftVersion?: string;
49
+ /** 显卡或图形驱动报告的名称 */
50
+ gpu?: string;
51
+ /** GPU 支持的纹理边长上限,单位为像素 */
52
+ maxTextureSize?: number;
53
+ /** 有效资源包内容摘要 */
54
+ resourcePackFingerprint?: string;
55
+ /** 节点可提供的材质档;旧节点未声明时只支持 default */
56
+ resourcePackProfiles?: string[];
57
+ /** Agent 是否启用夜视;参与节点缓存指纹 */
58
+ nightVisionEnabled?: boolean;
59
+ /** Agent 夜视亮度等级(1–15);未声明时兼容旧节点 */
60
+ nightVisionLevel?: number;
61
+ /** Agent 光照算法标识;变化时使旧渲染结果失效 */
62
+ lightingProfile?: string;
63
+ /** Agent 本地视角与各视角亮度的摘要 */
64
+ localViewsFingerprint?: string;
65
+ /** Agent 默认拼接布局;旧节点缺省为 horizontal */
66
+ cloudMergeLayout?: string;
67
+ }
68
+ export interface GpuRenderImage {
69
+ id: string;
70
+ name: string;
71
+ width: number;
72
+ height: number;
73
+ png: Buffer;
74
+ }
75
+ export interface GpuRenderResult {
76
+ /** 实际完成该任务的节点 ID;重试后可能不同于预选节点 */
77
+ agentId: string;
78
+ /** 实际节点的渲染能力摘要,用于识别结果来源 */
79
+ rendererFingerprint: string;
80
+ /** Agent 合成图过大时要求逐张发送,旧 Agent 未提供时为 false */
81
+ forceSeparateImages?: boolean;
82
+ /** 已通过协议校验的 PNG 附件,按 Agent 返回顺序排列 */
83
+ images: GpuRenderImage[];
84
+ /** Agent 报告的渲染耗时,单位为毫秒 */
85
+ elapsedMillis?: number;
86
+ /** 是否命中 Agent 自身的缓存 */
87
+ cacheHit?: boolean;
88
+ /** 实际节点的显卡名称 */
89
+ gpu?: string;
90
+ /** 实际节点的工具版本;旧 Agent 可能未声明 */
91
+ rendererVersion?: string;
92
+ }
93
+ interface BinaryHeader {
94
+ type: "input" | "image";
95
+ taskId: string;
96
+ attachmentId: string;
97
+ name?: string;
98
+ width?: number;
99
+ height?: number;
100
+ }
101
+ export interface GpuAgentSnapshot {
102
+ agentId: string;
103
+ online: boolean;
104
+ busy: boolean;
105
+ queueLength: number;
106
+ lastSeen?: number;
107
+ connectedAt?: number;
108
+ currentTaskId?: string;
109
+ progress?: number;
110
+ stage?: string;
111
+ capabilities: GpuAgentCapabilities;
112
+ }
113
+ export interface GpuAgentHubStatus {
114
+ queued: number;
115
+ queuedTaskIds: string[];
116
+ assigned: number;
117
+ completed: number;
118
+ failed: number;
119
+ cancelled: number;
120
+ nodes: GpuAgentSnapshot[];
121
+ }
122
+ export interface GpuAgentPlan {
123
+ agentId: string;
124
+ fingerprint: string;
125
+ }
126
+ export interface GpuAgentHubOptions {
127
+ host: string;
128
+ port: number;
129
+ path: string;
130
+ nodes: GpuAgentNodeConfig[];
131
+ heartbeatTimeout: number;
132
+ logger: {
133
+ info(message: string): void;
134
+ warn(message: string): void;
135
+ debug(message: string): void;
136
+ };
137
+ }
138
+ export declare function gpuAgentAuthSignature(secret: string, challenge: string, agentId: string): string;
139
+ export declare function encodeGpuBinary(header: BinaryHeader, payload: Buffer): Buffer<ArrayBuffer>;
140
+ export declare function decodeGpuBinary(value: Buffer): {
141
+ header: BinaryHeader;
142
+ payload: Buffer;
143
+ };
144
+ export declare function selectGpuAgent<T extends {
145
+ authenticated: boolean;
146
+ busy: boolean;
147
+ queueLength: number;
148
+ lastAssigned: number;
149
+ lastSeen: number;
150
+ capabilities: GpuAgentCapabilities;
151
+ }>(agents: T[], views: RenderView[], now?: number, heartbeatTimeout?: number, resourcePackProfile?: string): T | undefined;
152
+ /** 在在线兼容节点中优先选择负载最低者,并用路由键稳定打散同负载节点。 */
153
+ export declare function selectGpuAgentForRouting<T extends {
154
+ agentId: string;
155
+ authenticated: boolean;
156
+ busy: boolean;
157
+ queueLength: number;
158
+ lastAssigned: number;
159
+ lastSeen: number;
160
+ capabilities: GpuAgentCapabilities;
161
+ }>(agents: T[], views: RenderView[], routingKey: string, now?: number, heartbeatTimeout?: number, resourcePackProfile?: string): T | undefined;
162
+ /** 未声明能力的旧 Agent 只兼容 default,命名配置档必须显式声明。 */
163
+ export declare function supportsResourcePackProfile(capabilities: GpuAgentCapabilities, profile?: string): boolean;
164
+ export declare class GpuAgentHub extends EventEmitter {
165
+ private readonly options;
166
+ private readonly states;
167
+ private readonly nodeConfigs;
168
+ private readonly queue;
169
+ private assigned;
170
+ private completed;
171
+ private failed;
172
+ private cancelled;
173
+ private server?;
174
+ constructor(options: GpuAgentHubOptions);
175
+ start(): void;
176
+ close(): Promise<void>;
177
+ connectedAgentIds(): string[];
178
+ listeningAddress(): string | import("ws").AddressInfo | null | undefined;
179
+ status(): GpuAgentHubStatus;
180
+ /** 取消尚未分配给 Agent 的任务,已执行任务由远端渲染器自行完成。 */
181
+ cancel(taskId: string): boolean;
182
+ plan(request: GpuRenderRequest, routingKey: string): GpuAgentPlan | undefined;
183
+ capabilityFingerprint(): string;
184
+ render(request: GpuRenderRequest, schematic: Buffer, timeout: number, preferredAgentId?: string): Promise<GpuRenderResult>;
185
+ private run;
186
+ private compatibleStates;
187
+ private dispatch;
188
+ private emitStatus;
189
+ private accept;
190
+ private onMessage;
191
+ private onBinary;
192
+ private disconnect;
193
+ }
194
+ /** 生成适合管理员命令查看的 GPU Agent 状态文本。 */
195
+ export declare function formatGpuAgentStatus(status: GpuAgentHubStatus): string;
196
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.GpuAgentHub=exports.GPU_BINARY_HEADER_LIMIT=exports.GPU_PROTOCOL_VERSION=void 0,exports.gpuAgentAuthSignature=gpuAgentAuthSignature,exports.encodeGpuBinary=encodeGpuBinary,exports.decodeGpuBinary=decodeGpuBinary,exports.selectGpuAgent=selectGpuAgent,exports.selectGpuAgentForRouting=selectGpuAgentForRouting,exports.supportsResourcePackProfile=supportsResourcePackProfile,exports.formatGpuAgentStatus=formatGpuAgentStatus;const node_crypto_1=require("node:crypto"),node_events_1=require("node:events"),ws_1=require("ws");exports.GPU_PROTOCOL_VERSION=2,exports.GPU_BINARY_HEADER_LIMIT=65536;const PNG_SIGNATURE=Buffer.from([137,80,78,71,13,10,26,10]);function gpuAgentAuthSignature(e,t,s){return(0,node_crypto_1.createHmac)("sha256",e).update(t).update(".").update(s).digest("hex")}function encodeGpuBinary(e,t){const s=Buffer.from(JSON.stringify(e),"utf8");if(s.length>exports.GPU_BINARY_HEADER_LIMIT)throw new Error("GPU binary header is too large");const n=Buffer.allocUnsafe(4+s.length+t.length);return n.writeUInt32BE(s.length,0),s.copy(n,4),t.copy(n,4+s.length),n}function decodeGpuBinary(e){if(e.length<5)throw new Error("GPU binary frame is truncated");const t=e.readUInt32BE(0);if(!t||t>exports.GPU_BINARY_HEADER_LIMIT||4+t>e.length)throw new Error("GPU binary frame has an invalid header");const s=JSON.parse(e.toString("utf8",4,4+t));if(!(s&&["input","image"].includes(s.type)&&s.taskId&&s.attachmentId))throw new Error("GPU binary frame has an invalid envelope");return{header:s,payload:e.subarray(4+t)}}function selectGpuAgent(e,t,s=Date.now(),n=3e4,i){const r=Math.max(...t.map(e=>Math.max(e.width,e.height)*Math.max(1,e.supersampling)),1);return e.filter(e=>e.authenticated&&!e.busy&&s-e.lastSeen<=n).filter(e=>!e.capabilities.maxTextureSize||e.capabilities.maxTextureSize>=r).filter(e=>supportsResourcePackProfile(e.capabilities,i)).sort((e,t)=>e.queueLength-t.queueLength||e.lastAssigned-t.lastAssigned)[0]}function selectGpuAgentForRouting(e,t,s,n=Date.now(),i=3e4,r){const a=requiredTextureSize(t),o=e.filter(e=>e.authenticated&&n-e.lastSeen<=i).filter(e=>!e.capabilities.maxTextureSize||e.capabilities.maxTextureSize>=a).filter(e=>supportsResourcePackProfile(e.capabilities,r)).sort((e,t)=>Number(e.busy)-Number(t.busy)||e.queueLength-t.queueLength||e.lastAssigned-t.lastAssigned||e.agentId.localeCompare(t.agentId));if(!o.length)return;const u=o[0],c=o.filter(e=>e.busy===u.busy&&e.queueLength===u.queueLength);return c[(0,node_crypto_1.createHash)("sha256").update(s).digest().readUInt32BE(0)%c.length]}function supportsResourcePackProfile(e,t){const s=t?.trim()||"default",n=e.resourcePackProfiles?.filter(Boolean);return n?.length?n.includes(s):"default"===s}function requiredTextureSize(e){return Math.max(...e.map(e=>Math.max(e.width,e.height)*Math.max(1,e.supersampling)),1)}function agentFingerprint(e){return[e.agentId,e.capabilities.rendererVersion??"",e.capabilities.minecraftVersion??"",e.capabilities.resourcePackFingerprint??"",!0===e.capabilities.nightVisionEnabled?"1":"0",String(e.capabilities.nightVisionLevel??""),e.capabilities.lightingProfile??"",e.capabilities.localViewsFingerprint??"",e.capabilities.cloudMergeLayout??"horizontal"].join(":")}function secureHexEqual(e,t){if("string"!=typeof e||!/^[0-9a-f]+$/i.test(e))return!1;const s=Buffer.from(e,"hex"),n=Buffer.from(t,"hex");return s.length===n.length&&s.length>0&&(0,node_crypto_1.timingSafeEqual)(s,n)}class GpuAgentHub extends node_events_1.EventEmitter{options;states=new Map;nodeConfigs;queue=[];assigned=0;completed=0;failed=0;cancelled=0;server;constructor(e){super(),this.options=e,this.nodeConfigs=new Map(e.nodes.filter(e=>!1!==e.enabled).map(e=>[e.agentId,e]))}start(){this.server||(this.server=new ws_1.WebSocketServer({host:this.options.host,port:this.options.port,path:this.options.path}),this.server.on("connection",e=>this.accept(e)),this.server.on("listening",()=>{this.options.logger.info(`GPU Agent WebSocket listening on ws://${this.options.host}:${this.options.port}${this.options.path}`),this.emit("listening",this.server?.address())}),this.server.on("error",e=>this.options.logger.warn(`GPU Agent WebSocket error: ${e.message}`)))}async close(){for(const e of this.queue.splice(0))clearTimeout(e.timer),e.reject(new Error("GPU Agent hub stopped"));for(const e of this.states.values())this.disconnect(e,new Error("GPU Agent hub stopped"));const e=this.server;this.server=void 0,e&&await new Promise(t=>e.close(()=>t()))}connectedAgentIds(){return[...this.states.values()].filter(e=>e.authenticated).map(e=>e.agentId)}listeningAddress(){return this.server?.address()}status(){const e=Date.now(),t=[...this.nodeConfigs.keys()].map(t=>{const s=[...this.states.values()].find(e=>e.authenticated&&e.agentId===t),n=Boolean(s&&e-s.lastSeen<=this.options.heartbeatTimeout);return{agentId:t,online:n,busy:!!n&&Boolean(s?.busy),queueLength:n?s?.queueLength??0:0,lastSeen:s?.lastSeen,connectedAt:s?.connectedAt,currentTaskId:s?.currentTaskId,progress:s?.progress,stage:s?.stage,capabilities:s?.capabilities??{}}});return{queued:this.queue.length,queuedTaskIds:this.queue.map(e=>e.request.id),assigned:this.assigned,completed:this.completed,failed:this.failed,cancelled:this.cancelled,nodes:t}}cancel(e){const t=this.queue.findIndex(t=>t.request.id===e);if(t<0)return!1;const[s]=this.queue.splice(t,1);return clearTimeout(s.timer),s.reject(new Error(`GPU Agent 任务已取消:${e}`)),this.cancelled++,this.emitStatus(),!0}plan(e,t){const s=selectGpuAgentForRouting([...this.states.values()],e.views,t,Date.now(),this.options.heartbeatTimeout,e.resourcePackProfile);return s?{agentId:s.agentId,fingerprint:agentFingerprint(s)}:void 0}capabilityFingerprint(){return[...this.states.values()].filter(e=>e.authenticated).map(agentFingerprint).sort().join("|")||"offline"}async render(e,t,s,n){if(!this.compatibleStates(e.views,n,e.resourcePackProfile).length)throw new Error("没有在线且能力匹配的 GPU Agent");return new Promise((i,r)=>{const a={request:e,schematic:t,preferredAgentId:n,deadline:Date.now()+s,timer:setTimeout(()=>{const e=this.queue.indexOf(a);e>=0&&this.queue.splice(e,1),r(new Error("等待 GPU Agent 空闲槽位超时")),this.failed++,this.emitStatus()},s),resolve:i,reject:r,attemptedAgentIds:new Set};this.queue.push(a),this.emitStatus(),this.dispatch()})}async run(e,t){clearTimeout(t.timer);const s=t.request.id||(0,node_crypto_1.randomUUID)();e.busy=!0,e.queueLength++,e.lastAssigned=Date.now(),e.currentTaskId=s,t.attemptedAgentIds.add(e.agentId),e.progress=0,e.stage="assigned",this.assigned++,this.emitStatus();try{const n=new Promise((n,i)=>{const r=setTimeout(()=>{e.pending.delete(s),i(new Error(`GPU Agent ${e.agentId} 渲染超时`))},Math.max(1,t.deadline-Date.now()));e.pending.set(s,{resolve:n,reject:i,images:[],timer:r})});e.socket.send(JSON.stringify({type:"render",version:2,task:{...t.request,id:s}})),e.socket.send(encodeGpuBinary({type:"input",taskId:s,attachmentId:"litematic",name:t.request.filename},t.schematic));const i=await n;this.completed++,t.resolve(i)}catch(s){Date.now()<t.deadline&&this.compatibleStates(t.request.views,void 0,t.request.resourcePackProfile,t.attemptedAgentIds).length>0?(t.preferredAgentId=void 0,t.timer=setTimeout(()=>{const e=this.queue.indexOf(t);e>=0&&this.queue.splice(e,1),t.reject(new Error("等待 GPU Agent 空闲槽位超时")),this.failed++,this.emitStatus()},Math.max(1,t.deadline-Date.now())),this.queue.unshift(t),this.options.logger.warn(`GPU Agent ${e.agentId} 任务失败,正在尝试其他兼容节点:${s instanceof Error?s.message:String(s)}`)):(this.failed++,t.reject(s instanceof Error?s:new Error(String(s))))}finally{e.busy=!1,e.queueLength=Math.max(0,e.queueLength-1),e.currentTaskId=void 0,e.progress=void 0,e.stage=void 0,this.emitStatus(),this.dispatch()}}compatibleStates(e,t,s,n){const i=requiredTextureSize(e),r=Date.now();return[...this.states.values()].filter(e=>e.authenticated&&(!t||e.agentId===t)&&!n?.has(e.agentId)&&r-e.lastSeen<=this.options.heartbeatTimeout&&(!e.capabilities.maxTextureSize||e.capabilities.maxTextureSize>=i)&&supportsResourcePackProfile(e.capabilities,s))}dispatch(){for(;;){const e=this.queue.findIndex(e=>Boolean(selectGpuAgent(this.compatibleStates(e.request.views,e.preferredAgentId,e.request.resourcePackProfile,e.attemptedAgentIds),e.request.views,Date.now(),this.options.heartbeatTimeout,e.request.resourcePackProfile)));if(e<0)return;const t=this.queue.splice(e,1)[0],s=selectGpuAgent(this.compatibleStates(t.request.views,t.preferredAgentId,t.request.resourcePackProfile,t.attemptedAgentIds),t.request.views,Date.now(),this.options.heartbeatTimeout,t.request.resourcePackProfile);if(!s)return void this.queue.unshift(t);this.run(s,t)}}emitStatus(){this.emit("status",this.status())}accept(e){const t={agentId:"",socket:e,authenticated:!1,challenge:(0,node_crypto_1.randomUUID)(),queueLength:0,busy:!1,lastAssigned:0,lastSeen:Date.now(),capabilities:{},pending:new Map,connectedAt:Date.now()};this.states.set(e,t),e.on("message",(s,n)=>{try{this.onMessage(t,Buffer.from(s),n)}catch(t){this.options.logger.warn(`GPU Agent protocol error: ${t instanceof Error?t.message:String(t)}`),e.close(1008,"protocol error")}}),e.on("close",()=>this.disconnect(t,new Error(`GPU Agent ${t.agentId||"unknown"} disconnected`))),e.on("error",e=>this.options.logger.debug(`GPU Agent socket error: ${e.message}`))}onMessage(e,t,s){if(e.lastSeen=Date.now(),s)return this.onBinary(e,t);const n=JSON.parse(t.toString("utf8"));if("hello"===n.type&&2===n.version&&"string"==typeof n.agentId){if(!this.nodeConfigs.has(n.agentId))throw new Error(`unconfigured agentId: ${n.agentId}`);return e.agentId=n.agentId,e.challenge=(0,node_crypto_1.randomUUID)(),void e.socket.send(JSON.stringify({type:"challenge",version:2,challenge:e.challenge}))}if("auth"===n.type&&e.agentId){const t=gpuAgentAuthSignature(this.nodeConfigs.get(e.agentId).sharedSecret,e.challenge,e.agentId);if(!secureHexEqual(n.signature,t))throw new Error("invalid agent signature");e.authenticated=!0,e.capabilities=n.capabilities??{};for(const t of this.states.values())t!==e&&t.authenticated&&t.agentId===e.agentId&&this.disconnect(t,new Error(`GPU Agent ${e.agentId} 已由新连接替换`));return e.socket.send(JSON.stringify({type:"authenticated",version:2})),this.options.logger.info(`GPU Agent connected: ${e.agentId}${e.capabilities.gpu?` (${e.capabilities.gpu})`:""}`),this.emitStatus(),void this.dispatch()}if(!e.authenticated)throw new Error("agent is not authenticated");if("heartbeat"===n.type)return e.busy=Boolean(n.busy),e.queueLength=Math.max(0,Number(n.queueLength)||0),n.capabilities&&(e.capabilities={...e.capabilities,...n.capabilities}),this.emitStatus(),void this.dispatch();if("progress"===n.type)return e.currentTaskId===n.taskId&&(e.progress=Math.max(0,Math.min(1,Number(n.progress)||0)),e.stage="string"==typeof n.stage?n.stage:void 0),this.emit("progress",{agentId:e.agentId,taskId:n.taskId,progress:n.progress,stage:n.stage}),void this.emitStatus();if("result"===n.type||"error"===n.type){const t=e.pending.get(n.taskId);if(!t)return void this.options.logger.warn(`GPU Agent ${e.agentId} 回传了未知任务 ${n.taskId} 的结果(可能已超时)`);clearTimeout(t.timer),e.pending.delete(n.taskId),"error"===n.type?t.reject(new Error(`${n.code??"GPU_RENDER_FAILED"}: ${n.message??"GPU render failed"}`)):(this.options.logger.info(`GPU Agent ${e.agentId} 回传结果:任务 ${n.taskId},${t.images.length} 张图`),t.resolve({agentId:e.agentId,rendererFingerprint:agentFingerprint(e),images:t.images,elapsedMillis:n.elapsedMillis,cacheHit:n.cacheHit,forceSeparateImages:!0===n.forceSeparateImages,gpu:e.capabilities.gpu,rendererVersion:e.capabilities.rendererVersion}))}}onBinary(e,t){if(!e.authenticated)throw new Error("agent is not authenticated");const{header:s,payload:n}=decodeGpuBinary(t);if("image"!==s.type)throw new Error("server only accepts image binary frames");if(n.length<PNG_SIGNATURE.length||!n.subarray(0,PNG_SIGNATURE.length).equals(PNG_SIGNATURE))throw new Error("agent returned an invalid PNG attachment");const i=e.pending.get(s.taskId);i&&i.images.push({id:s.attachmentId,name:s.name??`${s.attachmentId}.png`,width:Number(s.width)||0,height:Number(s.height)||0,png:Buffer.from(n)})}disconnect(e,t){if(this.states.delete(e.socket)){for(const s of e.pending.values())clearTimeout(s.timer),s.reject(t);e.pending.clear();for(let s=this.queue.length-1;s>=0;s--){const n=this.queue[s];n.preferredAgentId===e.agentId&&(this.queue.splice(s,1),clearTimeout(n.timer),n.reject(t),this.failed++)}try{e.socket.close(1001,t.message.slice(0,120))}catch(e){}e.authenticated&&this.options.logger.warn(t.message),this.emitStatus(),this.dispatch()}}}function formatGpuAgentStatus(e){const t=`GPU Agent:${e.nodes.filter(e=>e.online).length}/${e.nodes.length} 在线,排队 ${e.queued},完成 ${e.completed},失败 ${e.failed},取消 ${e.cancelled}`;return e.nodes.length?[t,...e.nodes.map(e=>{if(!e.online)return`- ${e.agentId}:离线`;const t=[e.capabilities.gpu,e.capabilities.minecraftVersion&&`MC ${e.capabilities.minecraftVersion}`,e.capabilities.rendererVersion&&`Renderer ${e.capabilities.rendererVersion}`].filter(Boolean).join(" / "),s=null==e.progress?"":` ${Math.round(100*e.progress)}%${e.stage?` ${e.stage}`:""}`;return`- ${e.agentId}:${e.busy?`忙碌${s}`:"空闲"}${t?`;${t}`:""}`})].join("\n"):`${t}\n未配置节点`}exports.GpuAgentHub=GpuAgentHub;