@wsl233/dsh-gomoku 0.0.0-stage → 0.3.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/README.md +145 -2
- package/assets/dsniang.png +0 -0
- package/client.js +212 -0
- package/cordis.patch.yml +7 -0
- package/docs/ui-desktop.png +0 -0
- package/docs/ui-idle.png +0 -0
- package/docs/ui-lan.png +0 -0
- package/docs/ui-menu.png +0 -0
- package/docs/ui-narrow.png +0 -0
- package/index.js +433 -0
- package/lan-server.js +765 -0
- package/package.json +39 -4
- package/preview.html +44 -0
- package/ui/engine/ai.js +898 -0
- package/ui/engine/board.js +164 -0
- package/ui/engine/evaluate.js +242 -0
- package/ui/gomoku-ui.js +2130 -0
- package/ui/gomoku.css +1549 -0
- package/ui/lan.html +47 -0
- package/vendor/qrcode-generator-LICENSE.md +101 -0
- package/vendor/qrcode.js +2297 -0
- package/vendor/qrcode.mjs +2300 -0
package/index.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-gomoku — Host half.
|
|
3
|
+
*
|
|
4
|
+
* Exposes the plugin's static UI files, the LAN server and the DeepSeek proxy
|
|
5
|
+
* to the DSH web renderer.
|
|
6
|
+
*
|
|
7
|
+
* The routes are registered lazily through `webServer` because the web carrier
|
|
8
|
+
* may initialize after this plugin's own fiber. Requests are fenced with the
|
|
9
|
+
* DSH Connection service when it is available, following the same pattern as
|
|
10
|
+
* other bundled plugins.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { readFile } from 'node:fs/promises';
|
|
14
|
+
import { extname, resolve, sep } from 'node:path';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { startLanServer } from './lan-server.js';
|
|
17
|
+
|
|
18
|
+
export const name = 'dsh-gomoku';
|
|
19
|
+
|
|
20
|
+
const ROUTE_PREFIX = '/dsh-gomoku';
|
|
21
|
+
const ROOT = fileURLToPath(new URL('.', import.meta.url));
|
|
22
|
+
const UI_DIR = resolve(ROOT, 'ui');
|
|
23
|
+
const ASSET_DIR = resolve(ROOT, 'assets');
|
|
24
|
+
|
|
25
|
+
let lanServer = null;
|
|
26
|
+
let lanServerPromise = null;
|
|
27
|
+
let lanStartError = null;
|
|
28
|
+
let llmService = null;
|
|
29
|
+
|
|
30
|
+
function ensureLanServer() {
|
|
31
|
+
if (!lanServerPromise) {
|
|
32
|
+
lanServerPromise = startLanServer({ root: ROOT })
|
|
33
|
+
.then((handle) => {
|
|
34
|
+
lanServer = handle;
|
|
35
|
+
console.log(`[dsh-gomoku] LAN server listening on ${handle.origin}`);
|
|
36
|
+
return handle;
|
|
37
|
+
})
|
|
38
|
+
.catch((error) => {
|
|
39
|
+
lanStartError = error;
|
|
40
|
+
console.warn('[dsh-gomoku] LAN server failed:', error);
|
|
41
|
+
throw error;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return lanServerPromise;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const MIME = {
|
|
48
|
+
'.html': 'text/html; charset=utf-8',
|
|
49
|
+
'.css': 'text/css; charset=utf-8',
|
|
50
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
51
|
+
'.png': 'image/png',
|
|
52
|
+
'.svg': 'image/svg+xml',
|
|
53
|
+
'.json': 'application/json; charset=utf-8',
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Register the browser-facing routes.
|
|
58
|
+
* @param {object} ctx - Cordis plugin context.
|
|
59
|
+
*/
|
|
60
|
+
export function apply(ctx) {
|
|
61
|
+
ensureLanServer().catch(() => {});
|
|
62
|
+
ctx.effect(() => {
|
|
63
|
+
return () => {
|
|
64
|
+
if (lanServer) {
|
|
65
|
+
lanServer.close();
|
|
66
|
+
lanServer = null;
|
|
67
|
+
lanServerPromise = null;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}, 'dsh-gomoku: LAN server');
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
ctx.inject(['llm'], (llmCtx) => {
|
|
74
|
+
llmService = llmCtx.llm || (typeof llmCtx.get === 'function' ? llmCtx.get('llm') : null);
|
|
75
|
+
return () => { llmService = null; };
|
|
76
|
+
});
|
|
77
|
+
} catch (error) {
|
|
78
|
+
console.warn('[dsh-gomoku] LLM service unavailable:', error);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
ctx.inject(['webServer', 'connection'], (webCtx) => {
|
|
82
|
+
const webServer = webCtx.get('webServer');
|
|
83
|
+
if (!webServer) return;
|
|
84
|
+
|
|
85
|
+
webCtx.effect(
|
|
86
|
+
() =>
|
|
87
|
+
webServer.register({
|
|
88
|
+
kind: 'prefix',
|
|
89
|
+
path: ROUTE_PREFIX,
|
|
90
|
+
handler: (req, res) => {
|
|
91
|
+
handleRequest(webCtx, req, res).catch((error) => {
|
|
92
|
+
console.warn('[dsh-gomoku] request failed:', error);
|
|
93
|
+
if (!res.headersSent) {
|
|
94
|
+
res.statusCode = 500;
|
|
95
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
96
|
+
}
|
|
97
|
+
if (!res.writableEnded) res.end('Internal error');
|
|
98
|
+
});
|
|
99
|
+
},
|
|
100
|
+
}),
|
|
101
|
+
'dsh-gomoku: static routes',
|
|
102
|
+
);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Route one request under `/dsh-gomoku`.
|
|
108
|
+
* @param {object} webCtx - context that has `connection` and `webServer`.
|
|
109
|
+
* @param {import('node:http').IncomingMessage} req
|
|
110
|
+
* @param {import('node:http').ServerResponse} res
|
|
111
|
+
*/
|
|
112
|
+
async function handleRequest(webCtx, req, res) {
|
|
113
|
+
const connection = webCtx.get('connection');
|
|
114
|
+
if (connection && typeof connection.requestRejection === 'function') {
|
|
115
|
+
let rejection;
|
|
116
|
+
try {
|
|
117
|
+
rejection = connection.requestRejection(req);
|
|
118
|
+
} catch {
|
|
119
|
+
rejection = 403;
|
|
120
|
+
}
|
|
121
|
+
if (rejection !== undefined && rejection !== null) {
|
|
122
|
+
res.statusCode = rejection;
|
|
123
|
+
res.end();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const method = req.method || 'GET';
|
|
129
|
+
const isDeepseekMove = method === 'POST' && new URL(String(req.url || '/'), 'http://localhost').pathname === `${ROUTE_PREFIX}/deepseek/move`;
|
|
130
|
+
if (method !== 'GET' && method !== 'HEAD' && !isDeepseekMove) {
|
|
131
|
+
res.statusCode = 405;
|
|
132
|
+
res.setHeader('Allow', 'GET, HEAD');
|
|
133
|
+
res.end();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
let requestUrl;
|
|
138
|
+
let pathname;
|
|
139
|
+
try {
|
|
140
|
+
requestUrl = new URL(String(req.url || '/'), 'http://localhost');
|
|
141
|
+
pathname = decodeURIComponent(requestUrl.pathname);
|
|
142
|
+
} catch {
|
|
143
|
+
res.statusCode = 400;
|
|
144
|
+
res.end();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (pathname === `${ROUTE_PREFIX}/lan/info`) {
|
|
149
|
+
let handle;
|
|
150
|
+
try {
|
|
151
|
+
handle = await ensureLanServer();
|
|
152
|
+
} catch {
|
|
153
|
+
sendJson(res, {
|
|
154
|
+
ok: false,
|
|
155
|
+
error: 'lan-unavailable',
|
|
156
|
+
message: lanStartError ? String(lanStartError.message || lanStartError) : '局域网服务未启动',
|
|
157
|
+
}, method, 503);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
sendJson(res, {
|
|
161
|
+
ok: true,
|
|
162
|
+
...handle.info(),
|
|
163
|
+
linkBase: handle.linkBase,
|
|
164
|
+
}, method);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (pathname === `${ROUTE_PREFIX}/lan/qr`) {
|
|
169
|
+
let handle;
|
|
170
|
+
try {
|
|
171
|
+
handle = await ensureLanServer();
|
|
172
|
+
} catch {
|
|
173
|
+
sendText(res, 503, 'QR unavailable', method);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const text = requestUrl.searchParams.get('text') || '';
|
|
177
|
+
if (!text || text.length > 900) {
|
|
178
|
+
sendText(res, 400, 'Bad QR text', method);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
res.statusCode = 200;
|
|
183
|
+
res.setHeader('Content-Type', MIME['.svg']);
|
|
184
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
185
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
186
|
+
if (method === 'HEAD') res.end();
|
|
187
|
+
else res.end(handle.qrSvg(text));
|
|
188
|
+
} catch {
|
|
189
|
+
sendText(res, 500, 'QR error', method);
|
|
190
|
+
}
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (pathname === `${ROUTE_PREFIX}/deepseek/info`) {
|
|
195
|
+
try {
|
|
196
|
+
const llm = getLlm(webCtx);
|
|
197
|
+
const providers = typeof llm.listProviders === 'function' ? llm.listProviders() : [];
|
|
198
|
+
sendJson(res, { ok: true, providers: providers.map((provider) => provider && (provider.id || provider.name || String(provider))) }, method);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
sendJson(res, { ok: false, error: 'llm-unavailable', message: String(error && error.message || error) }, method, 503);
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (pathname === `${ROUTE_PREFIX}/deepseek/move` && method === 'POST') {
|
|
206
|
+
let llm;
|
|
207
|
+
try {
|
|
208
|
+
llm = getLlm(webCtx);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
sendJson(res, { ok: false, error: 'llm-unavailable', message: String(error && error.message || error) }, method, 503);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
let payload;
|
|
214
|
+
try {
|
|
215
|
+
payload = await readJsonBody(req);
|
|
216
|
+
} catch {
|
|
217
|
+
sendJson(res, { ok: false, error: 'bad-request' }, method, 400);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
const result = await requestDeepseekMove(llm, payload);
|
|
222
|
+
sendJson(res, { ok: true, ...result }, method);
|
|
223
|
+
} catch (error) {
|
|
224
|
+
console.warn('[dsh-gomoku] DeepSeek move failed:', error);
|
|
225
|
+
sendJson(res, { ok: false, error: 'deepseek-failed', message: String(error && error.message || error) }, method, 502);
|
|
226
|
+
}
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (pathname === `${ROUTE_PREFIX}/info`) {
|
|
231
|
+
sendJson(res, {
|
|
232
|
+
ok: true,
|
|
233
|
+
name,
|
|
234
|
+
version: '0.2.0',
|
|
235
|
+
phase: 'play',
|
|
236
|
+
capabilities: {
|
|
237
|
+
lan: true,
|
|
238
|
+
deepseek: true,
|
|
239
|
+
ai: true,
|
|
240
|
+
local: true,
|
|
241
|
+
hint: true,
|
|
242
|
+
review: true,
|
|
243
|
+
save: true,
|
|
244
|
+
import: true,
|
|
245
|
+
},
|
|
246
|
+
}, method);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
let base = null;
|
|
251
|
+
let relative = '';
|
|
252
|
+
if (pathname.startsWith(`${ROUTE_PREFIX}/ui/`)) {
|
|
253
|
+
base = UI_DIR;
|
|
254
|
+
relative = pathname.slice(`${ROUTE_PREFIX}/ui/`.length);
|
|
255
|
+
} else if (pathname.startsWith(`${ROUTE_PREFIX}/assets/`)) {
|
|
256
|
+
base = ASSET_DIR;
|
|
257
|
+
relative = pathname.slice(`${ROUTE_PREFIX}/assets/`.length);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (!base || !relative) {
|
|
261
|
+
sendText(res, 404, 'Not found', method);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const filePath = resolve(base, relative);
|
|
266
|
+
if (!filePath.startsWith(base + sep) || relative.includes('\0')) {
|
|
267
|
+
sendText(res, 404, 'Not found', method);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let content;
|
|
272
|
+
try {
|
|
273
|
+
content = await readFile(filePath);
|
|
274
|
+
} catch {
|
|
275
|
+
sendText(res, 404, 'Not found', method);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
res.statusCode = 200;
|
|
280
|
+
res.setHeader('Content-Type', MIME[extname(filePath).toLowerCase()] || 'application/octet-stream');
|
|
281
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
282
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
283
|
+
if (method === 'HEAD') {
|
|
284
|
+
res.end();
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
res.end(content);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function getLlm(ctx) {
|
|
291
|
+
const llm = llmService || (ctx && (ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : null))) || null;
|
|
292
|
+
if (!llm || typeof llm.stream !== 'function') {
|
|
293
|
+
throw new Error('DeepSeek 模型服务不可用');
|
|
294
|
+
}
|
|
295
|
+
return llm;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function readJsonBody(req) {
|
|
299
|
+
return new Promise((resolveBody, rejectBody) => {
|
|
300
|
+
let size = 0;
|
|
301
|
+
const chunks = [];
|
|
302
|
+
req.on('data', (chunk) => {
|
|
303
|
+
size += chunk.length;
|
|
304
|
+
if (size > 256 * 1024) {
|
|
305
|
+
rejectBody(new Error('request too large'));
|
|
306
|
+
req.destroy();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
chunks.push(chunk);
|
|
310
|
+
});
|
|
311
|
+
req.on('end', () => {
|
|
312
|
+
try {
|
|
313
|
+
resolveBody(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
|
|
314
|
+
} catch (error) {
|
|
315
|
+
rejectBody(error);
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
req.on('error', rejectBody);
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function normalizeBoard(payload) {
|
|
323
|
+
if (!payload || !Array.isArray(payload.board) || payload.board.length !== 361) {
|
|
324
|
+
throw new Error('棋盘数据不合法');
|
|
325
|
+
}
|
|
326
|
+
return payload.board.map((value) => (value === 1 || value === 2 ? value : 0));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function requestDeepseekMove(llm, payload) {
|
|
330
|
+
const board = normalizeBoard(payload);
|
|
331
|
+
const side = payload.side === 2 ? 2 : 1;
|
|
332
|
+
const startedAt = Date.now();
|
|
333
|
+
const rawProviders = typeof llm.listProviders === 'function' ? llm.listProviders() : [];
|
|
334
|
+
const providers = Array.isArray(rawProviders)
|
|
335
|
+
? rawProviders
|
|
336
|
+
: Object.keys(rawProviders || {}).map((key) => ({ id: key, ...(rawProviders[key] || {}) }));
|
|
337
|
+
if (!providers.length) throw new Error('DSH 未配置 DeepSeek 模型');
|
|
338
|
+
const provider = providers[0].id || providers[0].name || String(providers[0]);
|
|
339
|
+
let models = [];
|
|
340
|
+
if (typeof llm.listModels === 'function') {
|
|
341
|
+
try { models = await llm.listModels(provider); } catch { models = []; }
|
|
342
|
+
}
|
|
343
|
+
const model = (models && models[0] && (models[0].id || models[0].name)) || 'deepseek-v4-flash';
|
|
344
|
+
|
|
345
|
+
const moves = [];
|
|
346
|
+
if (Array.isArray(payload.moves)) {
|
|
347
|
+
for (const item of payload.moves) {
|
|
348
|
+
if (!Array.isArray(item) || item.length < 2) continue;
|
|
349
|
+
const x = Number(item[0]);
|
|
350
|
+
const y = Number(item[1]);
|
|
351
|
+
const color = item[2] === 2 ? 2 : 1;
|
|
352
|
+
if (Number.isInteger(x) && Number.isInteger(y) && x >= 0 && x < 19 && y >= 0 && y < 19) {
|
|
353
|
+
moves.push(`${x},${y},${color}`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const history = moves.length ? moves.join(';') : '空盘';
|
|
358
|
+
const prompt = [
|
|
359
|
+
'19 路五子棋。坐标 x,y 为 0-18,你执' + (side === 1 ? '黑' : '白') + '(1黑 2白)。',
|
|
360
|
+
'已落子(按顺序):' + history,
|
|
361
|
+
'只输出一个空位,格式 x,y,不要任何解释。',
|
|
362
|
+
].join('\n');
|
|
363
|
+
|
|
364
|
+
const options = {
|
|
365
|
+
provider,
|
|
366
|
+
model,
|
|
367
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
368
|
+
temperature: 0.1,
|
|
369
|
+
maxTokens: 32,
|
|
370
|
+
signal: AbortSignal.timeout(25000),
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
let text = '';
|
|
374
|
+
let failure = null;
|
|
375
|
+
for await (const chunk of llm.stream(options)) {
|
|
376
|
+
if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text;
|
|
377
|
+
if (chunk && chunk.type === 'finish' && chunk.kind === 'error') failure = chunk.failure || chunk;
|
|
378
|
+
}
|
|
379
|
+
if (failure) throw new Error(failure.message || failure.code || '模型调用失败');
|
|
380
|
+
const parsed = parseMoveText(text, board);
|
|
381
|
+
if (!parsed) throw new Error('模型未返回合法落子');
|
|
382
|
+
return {
|
|
383
|
+
move: parsed,
|
|
384
|
+
provider,
|
|
385
|
+
model,
|
|
386
|
+
text: text.trim().slice(0, 400),
|
|
387
|
+
prompt,
|
|
388
|
+
elapsedMs: Date.now() - startedAt,
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function parseMoveText(text, board) {
|
|
393
|
+
if (!text) return null;
|
|
394
|
+
const candidates = [];
|
|
395
|
+
const objectMatch = text.match(/\{[^}]*\}/g) || [];
|
|
396
|
+
for (const raw of objectMatch) {
|
|
397
|
+
try {
|
|
398
|
+
const value = JSON.parse(raw);
|
|
399
|
+
if (value && Number.isInteger(value.x) && Number.isInteger(value.y)) candidates.push(value);
|
|
400
|
+
} catch { /* ignore */ }
|
|
401
|
+
}
|
|
402
|
+
const numberMatch = text.match(/["']?x["']?\s*[:=]\s*(\d+)[\s,]+["']?y["']?\s*[:=]\s*(\d+)/i);
|
|
403
|
+
if (numberMatch) candidates.push({ x: Number(numberMatch[1]), y: Number(numberMatch[2]) });
|
|
404
|
+
const pairMatch = text.match(/(?:^|[^\d])(\d{1,2})\s*,\s*(\d{1,2})(?:[^\d]|$)/);
|
|
405
|
+
if (pairMatch) candidates.push({ x: Number(pairMatch[1]), y: Number(pairMatch[2]) });
|
|
406
|
+
for (const move of candidates) {
|
|
407
|
+
if (move.x >= 0 && move.x < 19 && move.y >= 0 && move.y < 19 && board[move.y * 19 + move.x] === 0) {
|
|
408
|
+
return { x: move.x, y: move.y };
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function sendJson(res, value, method, status) {
|
|
415
|
+
res.statusCode = status || 200;
|
|
416
|
+
res.setHeader('Content-Type', MIME['.json']);
|
|
417
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
418
|
+
if (method === 'HEAD') {
|
|
419
|
+
res.end();
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
res.end(JSON.stringify(value));
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function sendText(res, status, text, method) {
|
|
426
|
+
res.statusCode = status;
|
|
427
|
+
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
428
|
+
if (method === 'HEAD') {
|
|
429
|
+
res.end();
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
res.end(text);
|
|
433
|
+
}
|