@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaozhu2007/koishi-plugin-litematic-renderer",
3
- "version": "0.6.0",
3
+ "version": "0.7.20",
4
4
  "description": "Render small Litematica schematics sent in QQ groups",
5
5
  "keywords": [
6
6
  "koishi",
@@ -8,19 +8,10 @@
8
8
  "minecraft",
9
9
  "qq"
10
10
  ],
11
- "homepage": "https://cnb.cool/pw.sh.cn/koishi-plugin-litematic-renderer",
12
- "bugs": {
13
- "url": "https://cnb.cool/pw.sh.cn/koishi-plugin-litematic-renderer/-/issues"
14
- },
15
11
  "license": "MIT",
16
12
  "author": "halfkite, xiaozhu2007",
17
- "repository": {
18
- "type": "git",
19
- "url": "git+https://cnb.cool/pw.sh.cn/koishi-plugin-litematic-renderer.git"
20
- },
21
13
  "files": [
22
14
  "lib",
23
- "client",
24
15
  "dist",
25
16
  "assets/threeviews",
26
17
  "assets/java-bridge",
@@ -35,33 +26,46 @@
35
26
  },
36
27
  "scripts": {
37
28
  "build": "tsc -p tsconfig.json && koishi-console build",
38
- "postbuild": "terser lib/index.js --compress --mangle --output lib/index.js",
29
+ "postbuild": "for file in lib/*.js lib/render/*.js; do terser \"$file\" --compress --mangle --output \"$file\" || exit 1; done",
30
+ "prepack": "npm run build",
39
31
  "format": "oxfmt .",
40
32
  "format:check": "oxfmt --check .",
41
- "test": "node --test test/*.test.mjs"
33
+ "test": "node --test test/*.test.mjs",
34
+ "check": "npm run format:check && npm run build && npm test"
42
35
  },
43
36
  "dependencies": {
44
37
  "@sentry/node-core": "^10.71.0",
38
+ "@types/pngjs": "^6.0.5",
45
39
  "pngjs": "^7.0.0",
46
40
  "ssh2": "^1.17.0",
47
41
  "ws": "^8.18.3"
48
42
  },
49
43
  "devDependencies": {
44
+ "@element-plus/icons-vue": "^2.3.2",
50
45
  "@koishijs/client": "^5.30.11",
51
46
  "@koishijs/plugin-adapter-onebot": "^6.0.2",
52
47
  "@koishijs/plugin-console": "^5.30.11",
53
48
  "@types/node": "^22.0.0",
54
- "@types/pngjs": "^6.0.5",
55
49
  "@types/ssh2": "^1.15.5",
56
50
  "@types/ws": "^8.5.13",
57
51
  "koishi": "^4.18.0",
58
52
  "oxfmt": "^0.65.0",
59
53
  "terser": "^5.51.2",
60
- "typescript": "^6.0.3"
54
+ "typescript": "^6.0.3",
55
+ "vue": "^3.5.42"
61
56
  },
62
57
  "peerDependencies": {
63
58
  "koishi": "^4.18.0"
64
59
  },
60
+ "overrides": {
61
+ "js-yaml": "^4.3.1",
62
+ "qs": "^6.16.0",
63
+ "uuid": "^11.1.1",
64
+ "vite": {
65
+ ".": "^6.4.3",
66
+ "esbuild": "^0.25.0"
67
+ }
68
+ },
65
69
  "koishi": {
66
70
  "description": {
67
71
  "zh": "自动渲染群内 Litematica 投影文件(极致顺滑修复版),详情请查看 NPMJS README"
package/client/index.ts DELETED
@@ -1,136 +0,0 @@
1
- import { message, send } from "@koishijs/client";
2
- import "./style.css";
3
-
4
- function nextFrame() {
5
- return new Promise<void>((resolve) =>
6
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
7
- );
8
- }
9
-
10
- function findResourcePackItems() {
11
- return [...document.querySelectorAll<HTMLElement>(".k-schema-item")].filter((item) => {
12
- return item.querySelector("h3")?.textContent?.trim() === "resourcePackPaths";
13
- });
14
- }
15
-
16
- function setupResourcePackControl(item: HTMLElement) {
17
- if (item.dataset.litematicResourcePacks === "ready") return;
18
- const controls = item.querySelector<HTMLElement>(".k-schema-right");
19
- if (!controls) return;
20
- item.dataset.litematicResourcePacks = "ready";
21
-
22
- const toolbar = document.createElement("div");
23
- toolbar.className = "litematic-resource-pack-toolbar";
24
- const uploadButton = createButton("上传材质包", true);
25
- const upButton = createButton("上移");
26
- const downButton = createButton("下移");
27
- const fileInput = document.createElement("input");
28
- fileInput.type = "file";
29
- fileInput.accept = ".zip,application/zip";
30
- fileInput.hidden = true;
31
- toolbar.append(uploadButton, upButton, downButton, fileInput);
32
- controls.prepend(toolbar);
33
-
34
- let selected = -1;
35
- const rows = () =>
36
- [...item.querySelectorAll<HTMLTableRowElement>(".k-schema-table tr")].filter(
37
- (row) => !!row.querySelector("td"),
38
- );
39
- const refresh = () => {
40
- const currentRows = rows();
41
- if (selected >= currentRows.length) selected = currentRows.length - 1;
42
- currentRows.forEach((row, index) =>
43
- row.classList.toggle("litematic-selected", index === selected),
44
- );
45
- upButton.disabled = selected <= 0;
46
- downButton.disabled = selected < 0 || selected >= currentRows.length - 1;
47
- };
48
-
49
- item.addEventListener("click", (event) => {
50
- const row = (event.target as Element).closest<HTMLTableRowElement>(".k-schema-table tr");
51
- if (!row || !row.querySelector("td")) return;
52
- selected = rows().indexOf(row);
53
- refresh();
54
- });
55
-
56
- const move = async (offset: -1 | 1) => {
57
- const currentRows = rows();
58
- if (selected < 0 || selected + offset < 0 || selected + offset >= currentRows.length) return;
59
- const actions = currentRows[selected].querySelectorAll<HTMLElement>("td.k-schema-table-button");
60
- actions[offset < 0 ? 0 : 1]?.click();
61
- selected += offset;
62
- await nextFrame();
63
- refresh();
64
- };
65
- upButton.addEventListener("click", () => void move(-1));
66
- downButton.addEventListener("click", () => void move(1));
67
- uploadButton.addEventListener("click", () => fileInput.click());
68
-
69
- fileInput.addEventListener("change", async () => {
70
- const file = fileInput.files?.[0];
71
- fileInput.value = "";
72
- if (!file) return;
73
- if (!/\.zip$/i.test(file.name)) return message.error("只允许上传 ZIP 材质包");
74
- if (file.size > 256 * 1024 * 1024) return message.error("材质包超过 256 MB 上传上限");
75
-
76
- uploadButton.disabled = true;
77
- uploadButton.textContent = "上传中...";
78
- try {
79
- const path = (await send(
80
- "litematic/resource-pack-upload",
81
- file.name,
82
- await readBase64(file),
83
- )) as string;
84
- const addButton = [...controls.querySelectorAll<HTMLButtonElement>("button")].find((button) =>
85
- /添加(行|项目)/.test(button.textContent ?? ""),
86
- );
87
- if (!addButton) throw new Error("无法找到资源包列表的添加按钮");
88
- addButton.click();
89
- await nextFrame();
90
- const inputs = item.querySelectorAll<HTMLInputElement>(".k-schema-table input");
91
- const target = inputs[inputs.length - 1];
92
- if (!target) throw new Error("无法写入资源包路径");
93
- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
94
- setter?.call(target, path);
95
- target.dispatchEvent(new Event("input", { bubbles: true }));
96
- target.dispatchEvent(new Event("change", { bubbles: true }));
97
- selected = rows().length - 1;
98
- refresh();
99
- message.success("材质包已上传并设为最高优先级,请保存配置");
100
- } catch (error) {
101
- message.error(error instanceof Error ? error.message : String(error));
102
- } finally {
103
- uploadButton.disabled = false;
104
- uploadButton.textContent = "上传材质包";
105
- }
106
- });
107
-
108
- new MutationObserver(refresh).observe(item, { childList: true, subtree: true });
109
- refresh();
110
- }
111
-
112
- function createButton(label: string, primary = false) {
113
- const button = document.createElement("button");
114
- button.type = "button";
115
- button.className = `el-button${primary ? " el-button--primary" : ""}`;
116
- button.textContent = label;
117
- return button;
118
- }
119
-
120
- function readBase64(file: File) {
121
- return new Promise<string>((resolve, reject) => {
122
- const reader = new FileReader();
123
- reader.onerror = () => reject(reader.error ?? new Error("读取文件失败"));
124
- reader.onload = () => resolve(String(reader.result).split(",", 2)[1] ?? "");
125
- reader.readAsDataURL(file);
126
- });
127
- }
128
-
129
- function scan() {
130
- findResourcePackItems().forEach(setupResourcePackControl);
131
- }
132
-
133
- new MutationObserver(scan).observe(document.body, { childList: true, subtree: true });
134
- scan();
135
-
136
- export default () => {};
package/client/style.css DELETED
@@ -1,18 +0,0 @@
1
- .litematic-resource-pack-toolbar {
2
- display: inline-flex;
3
- flex-wrap: wrap;
4
- gap: 8px;
5
- margin-right: 8px;
6
- }
7
-
8
- .litematic-resource-pack-toolbar .el-button {
9
- margin-left: 0;
10
- }
11
-
12
- .k-schema-table tr.litematic-selected td {
13
- background: var(--k-button-hover-bg);
14
- }
15
-
16
- .k-schema-table tr.litematic-selected td:first-child {
17
- box-shadow: inset 3px 0 var(--k-color-active);
18
- }
package/dist/style.css DELETED
@@ -1 +0,0 @@
1
- .litematic-resource-pack-toolbar{display:inline-flex;flex-wrap:wrap;gap:8px;margin-right:8px}.litematic-resource-pack-toolbar .el-button{margin-left:0}.k-schema-table tr.litematic-selected td{background:var(--k-button-hover-bg)}.k-schema-table tr.litematic-selected td:first-child{box-shadow:inset 3px 0 var(--k-color-active)}
@@ -1,102 +0,0 @@
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
- version: 2;
19
- id: string;
20
- filename: string;
21
- views: RenderView[];
22
- resourcePackProfile?: string;
23
- sourceGroup?: string;
24
- sourceUser?: string;
25
- }
26
- export interface GpuAgentNodeConfig {
27
- agentId: string;
28
- sharedSecret: string;
29
- enabled?: boolean;
30
- }
31
- export interface GpuAgentCapabilities {
32
- rendererVersion?: string;
33
- minecraftVersion?: string;
34
- gpu?: string;
35
- maxTextureSize?: number;
36
- resourcePackFingerprint?: string;
37
- }
38
- export interface GpuRenderImage {
39
- id: string;
40
- name: string;
41
- width: number;
42
- height: number;
43
- png: Buffer;
44
- }
45
- export interface GpuRenderResult {
46
- agentId: string;
47
- images: GpuRenderImage[];
48
- elapsedMillis?: number;
49
- cacheHit?: boolean;
50
- gpu?: string;
51
- }
52
- interface BinaryHeader {
53
- type: "input" | "image";
54
- taskId: string;
55
- attachmentId: string;
56
- name?: string;
57
- width?: number;
58
- height?: number;
59
- }
60
- export interface GpuAgentHubOptions {
61
- host: string;
62
- port: number;
63
- path: string;
64
- nodes: GpuAgentNodeConfig[];
65
- heartbeatTimeout: number;
66
- logger: {
67
- info(message: string): void;
68
- warn(message: string): void;
69
- debug(message: string): void;
70
- };
71
- }
72
- export declare function gpuAgentAuthSignature(secret: string, challenge: string, agentId: string): string;
73
- export declare function encodeGpuBinary(header: BinaryHeader, payload: Buffer): Buffer<ArrayBuffer>;
74
- export declare function decodeGpuBinary(value: Buffer): {
75
- header: BinaryHeader;
76
- payload: Buffer;
77
- };
78
- export declare function selectGpuAgent<T extends {
79
- authenticated: boolean;
80
- busy: boolean;
81
- queueLength: number;
82
- lastAssigned: number;
83
- lastSeen: number;
84
- capabilities: GpuAgentCapabilities;
85
- }>(agents: T[], views: RenderView[], now?: number, heartbeatTimeout?: number): T | undefined;
86
- export declare class GpuAgentHub extends EventEmitter {
87
- private readonly options;
88
- private readonly states;
89
- private readonly nodeConfigs;
90
- private server?;
91
- constructor(options: GpuAgentHubOptions);
92
- start(): void;
93
- close(): Promise<void>;
94
- connectedAgentIds(): string[];
95
- capabilityFingerprint(): string;
96
- render(request: GpuRenderRequest, schematic: Buffer, timeout: number): Promise<GpuRenderResult>;
97
- private accept;
98
- private onMessage;
99
- private onBinary;
100
- private disconnect;
101
- }
102
- export {};
@@ -1,257 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GpuAgentHub = exports.GPU_BINARY_HEADER_LIMIT = exports.GPU_PROTOCOL_VERSION = void 0;
4
- exports.gpuAgentAuthSignature = gpuAgentAuthSignature;
5
- exports.encodeGpuBinary = encodeGpuBinary;
6
- exports.decodeGpuBinary = decodeGpuBinary;
7
- exports.selectGpuAgent = selectGpuAgent;
8
- const node_crypto_1 = require("node:crypto");
9
- const node_events_1 = require("node:events");
10
- const ws_1 = require("ws");
11
- exports.GPU_PROTOCOL_VERSION = 2;
12
- exports.GPU_BINARY_HEADER_LIMIT = 64 * 1024;
13
- const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
14
- function gpuAgentAuthSignature(secret, challenge, agentId) {
15
- return (0, node_crypto_1.createHmac)("sha256", secret).update(challenge).update(".").update(agentId).digest("hex");
16
- }
17
- function encodeGpuBinary(header, payload) {
18
- const encoded = Buffer.from(JSON.stringify(header), "utf8");
19
- if (encoded.length > exports.GPU_BINARY_HEADER_LIMIT)
20
- throw new Error("GPU binary header is too large");
21
- const output = Buffer.allocUnsafe(4 + encoded.length + payload.length);
22
- output.writeUInt32BE(encoded.length, 0);
23
- encoded.copy(output, 4);
24
- payload.copy(output, 4 + encoded.length);
25
- return output;
26
- }
27
- function decodeGpuBinary(value) {
28
- if (value.length < 5)
29
- throw new Error("GPU binary frame is truncated");
30
- const headerLength = value.readUInt32BE(0);
31
- if (!headerLength || headerLength > exports.GPU_BINARY_HEADER_LIMIT || 4 + headerLength > value.length) {
32
- throw new Error("GPU binary frame has an invalid header");
33
- }
34
- const header = JSON.parse(value.toString("utf8", 4, 4 + headerLength));
35
- if (!header ||
36
- !["input", "image"].includes(header.type) ||
37
- !header.taskId ||
38
- !header.attachmentId) {
39
- throw new Error("GPU binary frame has an invalid envelope");
40
- }
41
- return { header, payload: value.subarray(4 + headerLength) };
42
- }
43
- function selectGpuAgent(agents, views, now = Date.now(), heartbeatTimeout = 30_000) {
44
- const requiredTexture = Math.max(...views.map((view) => Math.max(view.width, view.height) * Math.max(1, view.supersampling)), 1);
45
- return agents
46
- .filter((agent) => agent.authenticated && !agent.busy && now - agent.lastSeen <= heartbeatTimeout)
47
- .filter((agent) => !agent.capabilities.maxTextureSize || agent.capabilities.maxTextureSize >= requiredTexture)
48
- .sort((left, right) => left.queueLength - right.queueLength || left.lastAssigned - right.lastAssigned)[0];
49
- }
50
- function secureHexEqual(left, right) {
51
- if (typeof left !== "string" || !/^[0-9a-f]+$/i.test(left))
52
- return false;
53
- const first = Buffer.from(left, "hex");
54
- const second = Buffer.from(right, "hex");
55
- return first.length === second.length && first.length > 0 && (0, node_crypto_1.timingSafeEqual)(first, second);
56
- }
57
- class GpuAgentHub extends node_events_1.EventEmitter {
58
- options;
59
- states = new Map();
60
- nodeConfigs;
61
- server;
62
- constructor(options) {
63
- super();
64
- this.options = options;
65
- this.nodeConfigs = new Map(options.nodes.filter((node) => node.enabled !== false).map((node) => [node.agentId, node]));
66
- }
67
- start() {
68
- if (this.server)
69
- return;
70
- this.server = new ws_1.WebSocketServer({
71
- host: this.options.host,
72
- port: this.options.port,
73
- path: this.options.path,
74
- });
75
- this.server.on("connection", (socket) => this.accept(socket));
76
- this.server.on("listening", () => this.options.logger.info(`GPU Agent WebSocket listening on ws://${this.options.host}:${this.options.port}${this.options.path}`));
77
- this.server.on("error", (error) => this.options.logger.warn(`GPU Agent WebSocket error: ${error.message}`));
78
- }
79
- async close() {
80
- for (const state of this.states.values())
81
- this.disconnect(state, new Error("GPU Agent hub stopped"));
82
- const server = this.server;
83
- this.server = undefined;
84
- if (server)
85
- await new Promise((resolve) => server.close(() => resolve()));
86
- }
87
- connectedAgentIds() {
88
- return [...this.states.values()]
89
- .filter((state) => state.authenticated)
90
- .map((state) => state.agentId);
91
- }
92
- capabilityFingerprint() {
93
- return ([...this.states.values()]
94
- .filter((state) => state.authenticated)
95
- .map((state) => [
96
- state.agentId,
97
- state.capabilities.rendererVersion ?? "",
98
- state.capabilities.minecraftVersion ?? "",
99
- state.capabilities.resourcePackFingerprint ?? "",
100
- ].join(":"))
101
- .sort()
102
- .join("|") || "offline");
103
- }
104
- async render(request, schematic, timeout) {
105
- const state = selectGpuAgent([...this.states.values()], request.views, Date.now(), this.options.heartbeatTimeout);
106
- if (!state)
107
- throw new Error("没有可用且能力匹配的 GPU Agent");
108
- const taskId = request.id || (0, node_crypto_1.randomUUID)();
109
- state.busy = true;
110
- state.queueLength++;
111
- state.lastAssigned = Date.now();
112
- try {
113
- const promise = new Promise((resolve, reject) => {
114
- const timer = setTimeout(() => {
115
- state.pending.delete(taskId);
116
- reject(new Error(`GPU Agent ${state.agentId} 渲染超时`));
117
- }, timeout);
118
- state.pending.set(taskId, { resolve, reject, images: [], timer });
119
- });
120
- state.socket.send(JSON.stringify({ type: "render", version: 2, task: { ...request, id: taskId } }));
121
- state.socket.send(encodeGpuBinary({ type: "input", taskId, attachmentId: "litematic", name: request.filename }, schematic));
122
- return await promise;
123
- }
124
- finally {
125
- state.busy = false;
126
- state.queueLength = Math.max(0, state.queueLength - 1);
127
- }
128
- }
129
- accept(socket) {
130
- const state = {
131
- agentId: "",
132
- socket,
133
- authenticated: false,
134
- challenge: (0, node_crypto_1.randomUUID)(),
135
- queueLength: 0,
136
- busy: false,
137
- lastAssigned: 0,
138
- lastSeen: Date.now(),
139
- capabilities: {},
140
- pending: new Map(),
141
- };
142
- this.states.set(socket, state);
143
- socket.on("message", (data, isBinary) => {
144
- try {
145
- this.onMessage(state, Buffer.from(data), isBinary);
146
- }
147
- catch (error) {
148
- this.options.logger.warn(`GPU Agent protocol error: ${error instanceof Error ? error.message : String(error)}`);
149
- socket.close(1008, "protocol error");
150
- }
151
- });
152
- socket.on("close", () => this.disconnect(state, new Error(`GPU Agent ${state.agentId || "unknown"} disconnected`)));
153
- socket.on("error", (error) => this.options.logger.debug(`GPU Agent socket error: ${error.message}`));
154
- }
155
- onMessage(state, data, isBinary) {
156
- state.lastSeen = Date.now();
157
- if (isBinary)
158
- return this.onBinary(state, data);
159
- const message = JSON.parse(data.toString("utf8"));
160
- if (message.type === "hello" && message.version === 2 && typeof message.agentId === "string") {
161
- if (!this.nodeConfigs.has(message.agentId))
162
- throw new Error(`unconfigured agentId: ${message.agentId}`);
163
- state.agentId = message.agentId;
164
- state.challenge = (0, node_crypto_1.randomUUID)();
165
- state.socket.send(JSON.stringify({ type: "challenge", version: 2, challenge: state.challenge }));
166
- return;
167
- }
168
- if (message.type === "auth" && state.agentId) {
169
- const node = this.nodeConfigs.get(state.agentId);
170
- const expected = gpuAgentAuthSignature(node.sharedSecret, state.challenge, state.agentId);
171
- if (!secureHexEqual(message.signature, expected))
172
- throw new Error("invalid agent signature");
173
- state.authenticated = true;
174
- state.capabilities = message.capabilities ?? {};
175
- state.socket.send(JSON.stringify({ type: "authenticated", version: 2 }));
176
- this.options.logger.info(`GPU Agent connected: ${state.agentId}${state.capabilities.gpu ? ` (${state.capabilities.gpu})` : ""}`);
177
- return;
178
- }
179
- if (!state.authenticated)
180
- throw new Error("agent is not authenticated");
181
- if (message.type === "heartbeat") {
182
- state.busy = Boolean(message.busy);
183
- state.queueLength = Math.max(0, Number(message.queueLength) || 0);
184
- if (message.capabilities)
185
- state.capabilities = { ...state.capabilities, ...message.capabilities };
186
- return;
187
- }
188
- if (message.type === "progress") {
189
- this.emit("progress", {
190
- agentId: state.agentId,
191
- taskId: message.taskId,
192
- progress: message.progress,
193
- stage: message.stage,
194
- });
195
- return;
196
- }
197
- if (message.type === "result" || message.type === "error") {
198
- const pending = state.pending.get(message.taskId);
199
- if (!pending) {
200
- this.options.logger.warn(`GPU Agent ${state.agentId} 回传了未知任务 ${message.taskId} 的结果(可能已超时)`);
201
- return;
202
- }
203
- clearTimeout(pending.timer);
204
- state.pending.delete(message.taskId);
205
- if (message.type === "error")
206
- pending.reject(new Error(`${message.code ?? "GPU_RENDER_FAILED"}: ${message.message ?? "GPU render failed"}`));
207
- else {
208
- this.options.logger.info(`GPU Agent ${state.agentId} 回传结果:任务 ${message.taskId},${pending.images.length} 张图`);
209
- pending.resolve({
210
- agentId: state.agentId,
211
- images: pending.images,
212
- elapsedMillis: message.elapsedMillis,
213
- cacheHit: message.cacheHit,
214
- gpu: state.capabilities.gpu,
215
- });
216
- }
217
- }
218
- }
219
- onBinary(state, data) {
220
- if (!state.authenticated)
221
- throw new Error("agent is not authenticated");
222
- const { header, payload } = decodeGpuBinary(data);
223
- if (header.type !== "image")
224
- throw new Error("server only accepts image binary frames");
225
- if (payload.length < PNG_SIGNATURE.length ||
226
- !payload.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
227
- throw new Error("agent returned an invalid PNG attachment");
228
- }
229
- const pending = state.pending.get(header.taskId);
230
- if (!pending)
231
- return;
232
- pending.images.push({
233
- id: header.attachmentId,
234
- name: header.name ?? `${header.attachmentId}.png`,
235
- width: Number(header.width) || 0,
236
- height: Number(header.height) || 0,
237
- png: Buffer.from(payload),
238
- });
239
- }
240
- disconnect(state, error) {
241
- if (!this.states.delete(state.socket))
242
- return;
243
- for (const pending of state.pending.values()) {
244
- clearTimeout(pending.timer);
245
- pending.reject(error);
246
- }
247
- state.pending.clear();
248
- // 必须真正关闭 socket:只删注册表会让连接变成僵尸,Agent 侧会一直认为仍在线而不再重连
249
- try {
250
- state.socket.close(1001, error.message.slice(0, 120));
251
- }
252
- catch (ignored) { }
253
- if (state.authenticated)
254
- this.options.logger.warn(error.message);
255
- }
256
- }
257
- exports.GpuAgentHub = GpuAgentHub;