@wsl233/dsh-gomoku 0.3.10 → 0.4.6

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  DeepSeek Harness(DSH)的五子棋插件:左侧栏「五子棋」入口,主页面提供棋盘、对手选择和完整对局操作。
4
4
 
5
- 当前版本:0.3.10。支持本地双人、大肥鱼算法(简单 / 中等 / 困难)、局域网双人、DSH 模型服务驱动的 DeepSeek 对战、提示、复盘(含胜率曲线)、棋谱导出/导入、对局保留、全屏和实时胜率。
5
+ 当前版本:0.4.6(本地视觉改版;npm latest 为 0.4.0)。支持本地双人、算法对战(简单 / 中等 / 困难 / 自定义)、局域网双人、DSH 模型服务驱动的 DeepSeek 对战、提示、复盘(含胜率曲线)、棋谱导出/导入、对局保留、全屏、实时胜率,以及在 DSH 对话中分析棋局。界面提供朱砂 / 松烟 / 靛青三套主题。
6
6
 
7
7
  ## 安装
8
8
 
@@ -12,7 +12,7 @@ DeepSeek Harness(DSH)的五子棋插件:左侧栏「五子棋」入口,
12
12
  npm install -g @wsl233/dsh-gomoku
13
13
  ```
14
14
 
15
- 当前本地版本 0.3.10 尚未发布到 npm;发布前请继续用下面的本地安装命令。
15
+ npm 上的 latest 为 0.4.0;0.4.6 是本地视觉改版 + 算法强化,确认后再发布。
16
16
 
17
17
  也可以在 DSH 插件管理器里安装 `@wsl233/dsh-gomoku`。本地开发时使用:
18
18
 
@@ -24,14 +24,31 @@ plugin_manager install_bundle target="file:C:/Users/rache/Desktop/DENNIS/wuziqi/
24
24
 
25
25
  ## 使用
26
26
 
27
+ - **界面主题**:标题右侧三个色点可在朱砂 / 松烟 / 靛青之间切换,选择会记录在本机;主题同时影响棋盘毛毡、落子标记、胜率与按钮强调色。
27
28
  - **本地双人**:同一台电脑轮流落子,支持撤销、新局、提示、复盘。
28
- - **与大肥鱼对战**:你执黑先手,AI 执白;算法对战可选简单 / 中等 / 困难,DeepSeek 对战不使用难度档。
29
+ - **与算法对战**:你执黑先手,算法执白;算法对战可选简单 / 中等 / 困难 / 自定义,DeepSeek 对战不使用难度档。顶栏「算法设置」可调简单 / 中等 / 困难 / 自定义,自定义档可调搜索深度(2–20)、思考时间(0.2–30 秒)、选点范围(1–3 格)、随机让棋(关 / 低 / 中)和防守权重(0.6–1.1,越高越优先堵棋);思考中可点棋盘提示条里的「立即落子」提前采用当前最佳结果。评估已改为非重叠棋型计分,并加入双活三、四三、双冲四奖励;搜索使用置换表、根 PVS、Aspiration Window 与 VCF 杀棋搜索。
29
30
  - **局域网对战**:点击后本机启动服务端并生成加入链接与二维码;同一局域网的另一台电脑打开链接即可执白加入。浏览器端不显示换对手的「+」和模式菜单;新局、悔棋需对方同意;房主可关闭双方提示;棋谱只能在开局前或一局结束后导入并同步双方;未带房间号的链接会先显示房间号输入页。房主可在联机设置弹窗里「退出联机对战」,退出后重新点右上角 + 即可换对手;房主必须保持 DSH 打开,端口需在防火墙放行。
30
31
  - **与 DeepSeek 对战**:复用 DSH 已配置的模型服务,浏览器不接触 API Key;请求使用紧凑棋谱和短提示词。模型没有返回可用落点、请求超时或被中断时,本手不会自动落子,而是弹出提示,让你选择「重试 DeepSeek」或「切换回算法对战」。宿主对单次请求的等待上限为 10 分钟,最大输出 token 为 8192;提示词会直接给出棋盘、候选点与优先级,要求模型少推理、直接输出坐标。棋盘下方可展开「DeepSeek 过程」,查看模型、提示词、推理与原始输出;成功和失败都会记录。
31
32
  - **提示 / 复盘 / 导出导入**:提示用算法搜索最佳落子;复盘可逐手回看,底部同时绘制黑棋胜率随手数变化的曲线(0–100 刻度、50% 参考线、当前手标记、悬停提示与点击跳转);导出只生成一个 `GM1.` 开头的字符串并自动复制,导入时粘贴该字符串即可。
32
33
  - **对局保留**:离开 DSH 五子棋面板再回来,本地 / 人机棋局会从 localStorage 恢复。
33
34
  - **全屏**:只保留棋盘界面,隐藏 DSH 侧边栏。
34
35
 
36
+ ## 在 DSH 对话中分析棋局
37
+
38
+ 在插件面板里把棋局导出为 `GM1.` 字符串,直接粘贴到 DSH 对话并说「分析这盘棋」即可。插件注册了 `gomoku_analyze` 工具,DSH 模型会自动调用它,不需要打开五子棋面板。
39
+
40
+ 分析结果会以图文卡片显示在 **`gomoku_analyze` 工具调用处**,不会在其他对话里重复出现;卡片只展示分析结果,不展示“思考中 / 等待”过程。卡片默认展开:
41
+
42
+ - 按手数编号的 19×19 全盘,最佳手绿圈、失误手红圈;
43
+ - **多个局部棋盘**:关键最佳/失误手各自放大为 9×9 局部棋盘(失误手会标出实际手与绿色“荐”点);
44
+ - 每条改进分支附一个终局局部棋盘,便于直接看出改进后的形状;
45
+ - 黑方胜率随手数变化的曲线(0–100 刻度、50% 参考线、当前手标记);
46
+ - 双方各自的最佳 3 手与失误 3 手,含“实际损失”百分比;
47
+ - DeepSeek 对关键手和整体棋局的中文总评;
48
+ - 最多 3 条从失误点续写的改进分支(每条附 `GM1.` 字符串,可复制回插件导入;分支在提前五连时会自然结束)。
49
+
50
+ 本地引擎负责逐手评估、最佳应对和分支生成;DeepSeek 只复核关键手并写总评。模型复核失败时仍返回本地分析,不阻塞卡片。
51
+
35
52
  ## 局域网
36
53
 
37
54
  服务端由 `lan-server.js` 提供,端口 8790–8799,同时提供加入页、静态 UI 和 `/ws` WebSocket;二维码由 `vendor/qrcode.mjs` 本地生成,不依赖 npm 包。
@@ -40,13 +57,7 @@ plugin_manager install_bundle target="file:C:/Users/rache/Desktop/DENNIS/wuziqi/
40
57
 
41
58
  ## 开发
42
59
 
43
- 无需构建,直接打开 `preview.html` 预览 UI:
44
-
45
- ```text
46
- dsh-gomoku/preview.html?demo=0
47
- ```
48
-
49
- `preview.html` 加载 `ui/engine/board.js`、`evaluate.js`、`ai.js` 与 `ui/gomoku-ui.js`。插件宿主入口是 `index.js`,客户端入口是 `client.js`,界面与对局逻辑在 `ui/gomoku-ui.js`。
60
+ 无需构建,通过 `plugin_manager install_bundle target="file:C:/Users/rache/Desktop/DENNIS/wuziqi/dsh-gomoku"` 安装后在 DSH 中直接查看。插件宿主入口是 `index.js`,客户端入口是 `client.js`,界面与对局逻辑在 `ui/gomoku-ui.js`;对话分析由 `analysis.js` 在宿主执行,卡片在 `client.js` 中注册到 `tool.call.toolview`,只在 `gomoku_analyze` 工具结果处展示完整图文,不额外渲染思考过程。局域网加入页由 `ui/lan.html` 提供。
50
61
 
51
62
  ## 说明
52
63
 
package/analysis.js ADDED
@@ -0,0 +1,441 @@
1
+ /**
2
+ * Host-side game analysis for the `gomoku_analyze` agent tool.
3
+ *
4
+ * The browser engine is reused through a tiny vm sandbox so the dialog card and
5
+ * the panel always agree on scoring rules. The expensive part is deliberately
6
+ * local: every played move gets a static evaluation and a one-ply best reply;
7
+ * DeepSeek only reviews a handful of key moves and writes prose.
8
+ */
9
+
10
+ import { readFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import vm from 'node:vm';
14
+
15
+ const SIZE = 19;
16
+ const BLACK = 1;
17
+ const WHITE = 2;
18
+ const ENGINE_DIR = fileURLToPath(new URL('./ui/engine/', import.meta.url));
19
+ const ENGINE_FILES = ['board.js', 'evaluate.js', 'ai.js'];
20
+ const VARIANT_LENGTH = 18;
21
+ const MAX_LIST = 3;
22
+
23
+ let runtime = null;
24
+
25
+ function loadRuntime() {
26
+ if (runtime) return runtime;
27
+ const sandbox = {
28
+ window: {},
29
+ console,
30
+ setTimeout,
31
+ clearTimeout,
32
+ Date,
33
+ Math,
34
+ Promise,
35
+ };
36
+ vm.createContext(sandbox);
37
+ for (const file of ENGINE_FILES) {
38
+ const code = readFileSync(join(ENGINE_DIR, file), 'utf8');
39
+ vm.runInContext(code, sandbox, { filename: file });
40
+ }
41
+ const Gomoku = sandbox.window && sandbox.window.Gomoku;
42
+ if (!Gomoku || !Gomoku.Board || !Gomoku.Evaluate || !Gomoku.AI) {
43
+ throw new Error('五子棋引擎加载失败');
44
+ }
45
+ runtime = Gomoku;
46
+ return runtime;
47
+ }
48
+
49
+ function coord(x, y) {
50
+ return String.fromCharCode(65 + x) + (y + 1);
51
+ }
52
+
53
+ function clampRate(value) {
54
+ const n = Number(value);
55
+ if (!Number.isFinite(n)) return 50;
56
+ return Math.max(0, Math.min(100, Math.round(n * 10) / 10));
57
+ }
58
+
59
+ function rateFromValue(Gomoku, value) {
60
+ return clampRate(Gomoku.Evaluate.winRateFromBlackScore(value));
61
+ }
62
+
63
+ function sideRate(blackRate, color) {
64
+ return color === BLACK ? blackRate : 100 - blackRate;
65
+ }
66
+
67
+ function cellsOf(board) {
68
+ const cells = [];
69
+ for (let y = 0; y < SIZE; y++) {
70
+ for (let x = 0; x < SIZE; x++) {
71
+ if (board[y * SIZE + x]) cells.push({ x, y });
72
+ }
73
+ }
74
+ return cells;
75
+ }
76
+
77
+ function decodeGm1(code) {
78
+ const raw = String(code == null ? '' : code).trim();
79
+ if (!raw.startsWith('GM1.')) {
80
+ throw new Error('请提供以 GM1. 开头的棋谱,例如 GM1.e30...;可在五子棋面板的导出按钮生成。');
81
+ }
82
+ let parsed;
83
+ try {
84
+ const payload = raw.slice(4).replace(/\s+/g, '');
85
+ parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
86
+ } catch {
87
+ throw new Error('棋谱代码无法解析,请确认复制了完整的 GM1. 字符串。');
88
+ }
89
+ const list = Array.isArray(parsed) ? parsed : parsed && parsed.m;
90
+ if (!Array.isArray(list)) {
91
+ throw new Error('棋谱代码缺少 m 着法数组。');
92
+ }
93
+ if (list.length === 0) {
94
+ throw new Error('棋谱为空,至少需要一只手才能分析。');
95
+ }
96
+ const board = new Uint8Array(SIZE * SIZE);
97
+ const moves = [];
98
+ const G = loadRuntime();
99
+ let turn = BLACK;
100
+ let winner = 0;
101
+ let winLine = null;
102
+ for (let i = 0; i < list.length; i++) {
103
+ const item = list[i];
104
+ if (!Array.isArray(item) || item.length < 3) {
105
+ throw new Error(`第 ${i + 1} 手格式无效。`);
106
+ }
107
+ const x = Number(item[0]);
108
+ const y = Number(item[1]);
109
+ const color = Number(item[2]);
110
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
111
+ throw new Error(`第 ${i + 1} 手坐标越界。`);
112
+ }
113
+ if (color !== BLACK && color !== WHITE) {
114
+ throw new Error(`第 ${i + 1} 手颜色无效。`);
115
+ }
116
+ if (winner) {
117
+ throw new Error(`第 ${i + 1} 手出现在对局结束之后。`);
118
+ }
119
+ if (color !== turn) {
120
+ throw new Error(`第 ${i + 1} 手颜色顺序错误:应为${turn === BLACK ? '黑' : '白'}方。`);
121
+ }
122
+ const index = y * SIZE + x;
123
+ if (board[index] !== 0) {
124
+ throw new Error(`第 ${i + 1} 手落点 ${coord(x, y)} 已有棋子。`);
125
+ }
126
+ board[index] = color;
127
+ moves.push({ n: i + 1, x, y, color, coord: coord(x, y) });
128
+ if (G.Board.hasFive(board, x, y, color)) {
129
+ winner = color;
130
+ winLine = G.Board.winLineAt(board, x, y, color);
131
+ }
132
+ turn = color === BLACK ? WHITE : BLACK;
133
+ }
134
+ return { moves, board, winner, winLine };
135
+ }
136
+
137
+ function pickBest(Gomoku, board, cells, color) {
138
+ const work = board.slice();
139
+ const engine = new Gomoku.Evaluate.Engine(work, cells);
140
+ const candidates = Gomoku.AI.genMoves(engine, color, 2, 80);
141
+ let best = null;
142
+ for (const candidate of candidates) {
143
+ if (!candidate || work[candidate.y * SIZE + candidate.x] !== 0) continue;
144
+ engine.make(candidate.x, candidate.y, color);
145
+ const blackRate = rateFromValue(Gomoku, engine.value());
146
+ const ownRate = sideRate(blackRate, color);
147
+ engine.unmake(candidate.x, candidate.y);
148
+ if (
149
+ !best ||
150
+ ownRate > best.ownRate ||
151
+ (ownRate === best.ownRate && candidate.win && !best.win)
152
+ ) {
153
+ best = {
154
+ x: candidate.x,
155
+ y: candidate.y,
156
+ coord: coord(candidate.x, candidate.y),
157
+ ownRate,
158
+ blackRate,
159
+ win: Boolean(candidate.win),
160
+ };
161
+ }
162
+ }
163
+ return best;
164
+ }
165
+
166
+ function applyMove(board, cells, move) {
167
+ board[move.y * SIZE + move.x] = move.color;
168
+ cells.push({ x: move.x, y: move.y });
169
+ }
170
+
171
+ function encodeMoves(Gomoku, moves) {
172
+ const m = moves.map((move) => [move.x, move.y, move.color]);
173
+ return 'GM1.' + Buffer.from(JSON.stringify({ v: 1, m }), 'utf8').toString('base64url');
174
+ }
175
+
176
+ function analyzeMoves(decoded) {
177
+ const G = loadRuntime();
178
+ const { moves, winner } = decoded;
179
+ let board = new Uint8Array(SIZE * SIZE);
180
+ let cells = [];
181
+ const rates = [{ n: 0, black: 50 }];
182
+ const records = [];
183
+ let previousBlackRate = 50;
184
+
185
+ for (const move of moves) {
186
+ const before = board.slice();
187
+ const beforeCells = cells.slice();
188
+ const best = pickBest(G, before, beforeCells, move.color);
189
+ applyMove(board, cells, move);
190
+ const terminal = G.Board.hasFive(board, move.x, move.y, move.color);
191
+ const afterBlackRate = terminal
192
+ ? (move.color === BLACK ? 100 : 0)
193
+ : rateFromValue(G, new G.Evaluate.Engine(board).value());
194
+ const actualOwnRate = sideRate(afterBlackRate, move.color);
195
+ const bestOwnRate = best ? best.ownRate : actualOwnRate;
196
+ const loss = Math.max(0, Math.round((bestOwnRate - actualOwnRate) * 10) / 10);
197
+ const beforeOwnRate = sideRate(previousBlackRate, move.color);
198
+ const swing = Math.round((actualOwnRate - beforeOwnRate) * 10) / 10;
199
+
200
+ records.push({
201
+ n: move.n,
202
+ color: move.color,
203
+ colorLabel: move.color === BLACK ? '黑' : '白',
204
+ move: { x: move.x, y: move.y, coord: move.coord },
205
+ beforeRate: previousBlackRate,
206
+ afterRate: afterBlackRate,
207
+ actualOwnRate: Math.round(actualOwnRate * 10) / 10,
208
+ best: best
209
+ ? {
210
+ x: best.x,
211
+ y: best.y,
212
+ coord: best.coord,
213
+ ownRate: Math.round(bestOwnRate * 10) / 10,
214
+ blackRate: Math.round(best.blackRate * 10) / 10,
215
+ }
216
+ : null,
217
+ bestOwnRate: Math.round(bestOwnRate * 10) / 10,
218
+ loss,
219
+ swing,
220
+ terminal,
221
+ isBest: Boolean(best && best.x === move.x && best.y === move.y),
222
+ });
223
+ rates.push({
224
+ n: move.n,
225
+ black: terminal ? (move.color === BLACK ? 100 : 0) : afterBlackRate,
226
+ });
227
+ previousBlackRate = rates[rates.length - 1].black;
228
+ if (terminal) break;
229
+ }
230
+
231
+ const bestMoves = records
232
+ .filter((item) => !item.terminal && item.loss <= 2 && item.swing > 0)
233
+ .sort((a, b) => b.swing - a.swing || a.loss - b.loss)
234
+ .slice(0, MAX_LIST);
235
+
236
+ const mistakes = records
237
+ .filter((item) => !item.terminal && item.loss >= 4)
238
+ .sort((a, b) => b.loss - a.loss)
239
+ .slice(0, MAX_LIST);
240
+
241
+ if (bestMoves.length === 0) {
242
+ bestMoves.push(
243
+ ...records
244
+ .filter((item) => !item.terminal)
245
+ .sort((a, b) => a.loss - b.loss)
246
+ .slice(0, MAX_LIST),
247
+ );
248
+ }
249
+ if (mistakes.length === 0) {
250
+ mistakes.push(
251
+ ...records
252
+ .filter((item) => !item.terminal)
253
+ .sort((a, b) => b.loss - a.loss)
254
+ .slice(0, MAX_LIST),
255
+ );
256
+ }
257
+
258
+ return {
259
+ moves: records,
260
+ rates,
261
+ bestMoves,
262
+ mistakes,
263
+ winner,
264
+ total: moves.length,
265
+ };
266
+ }
267
+
268
+ function branchFrom(decoded, mistake, label) {
269
+ const G = loadRuntime();
270
+ const prefix = decoded.moves.slice(0, Math.max(0, mistake.n - 1));
271
+ const board = new Uint8Array(SIZE * SIZE);
272
+ const cells = [];
273
+ for (const move of prefix) applyMove(board, cells, move);
274
+ const branchMoves = prefix.slice();
275
+ let color = mistake.color;
276
+ let lastBlackRate = 50;
277
+ let ended = false;
278
+
279
+ for (let step = 0; branchMoves.length < VARIANT_LENGTH + prefix.length; step++) {
280
+ if (board.every((cell) => cell !== 0)) break;
281
+ const best = pickBest(G, board, cells, color);
282
+ if (!best) break;
283
+ const move = {
284
+ x: best.x,
285
+ y: best.y,
286
+ color,
287
+ n: branchMoves.length + 1,
288
+ coord: best.coord,
289
+ };
290
+ applyMove(board, cells, move);
291
+ branchMoves.push(move);
292
+ lastBlackRate = rateFromValue(G, new G.Evaluate.Engine(board).value());
293
+ if (G.Board.hasFive(board, move.x, move.y, color)) {
294
+ ended = true;
295
+ lastBlackRate = color === BLACK ? 100 : 0;
296
+ break;
297
+ }
298
+ color = color === BLACK ? WHITE : BLACK;
299
+ }
300
+
301
+ return {
302
+ from: mistake.n,
303
+ label: label || `从第 ${mistake.n} 手改进`,
304
+ length: branchMoves.length - prefix.length,
305
+ totalMoves: branchMoves.length,
306
+ finalBlackRate: Math.round(lastBlackRate * 10) / 10,
307
+ endedInWin: ended,
308
+ moves: branchMoves.map((move) => ({ x: move.x, y: move.y, color: move.color, n: move.n })),
309
+ code: encodeMoves(G, branchMoves),
310
+ };
311
+ }
312
+
313
+ function describeWinner(winner) {
314
+ if (winner === BLACK) return '黑方胜';
315
+ if (winner === WHITE) return '白方胜';
316
+ return '未分出胜负';
317
+ }
318
+
319
+ function buildReviewPrompt(decoded, analysis) {
320
+ const lines = [];
321
+ for (const item of analysis.bestMoves) {
322
+ lines.push(
323
+ `第${item.n}手 ${item.colorLabel}${item.move.coord},引擎最佳 ${item.best ? item.best.coord : '无'},` +
324
+ `该手胜率 ${item.beforeRate}%→${item.afterRate}%(黑方视角),损失 ${item.loss}%`,
325
+ );
326
+ }
327
+ const mistakes = [];
328
+ for (const item of analysis.mistakes) {
329
+ mistakes.push(
330
+ `第${item.n}手 ${item.colorLabel}${item.move.coord},引擎建议 ${item.best ? item.best.coord : '无'},` +
331
+ `损失 ${item.loss}%(该手落子后黑胜率 ${item.afterRate}%)`,
332
+ );
333
+ }
334
+ return [
335
+ '你是五子棋教练。下面是一盘棋的本地引擎摘要(静态评估 + 一层最佳应对),不是绝对结论。',
336
+ `共 ${analysis.total} 手,结果:${describeWinner(analysis.winner)}。`,
337
+ '值得肯定的手:',
338
+ ...(lines.length ? lines : ['无明显高分决策。']),
339
+ '值得复盘的手:',
340
+ ...(mistakes.length ? mistakes : ['未发现明显失误。']),
341
+ '请用中文写 4–6 句总评:先讲整体布局与转折,再分别点评双方的关键选择和改进方向。',
342
+ '不要输出 JSON,不要编造新坐标;可以引用上面出现过的坐标。',
343
+ ].join('\n');
344
+ }
345
+
346
+ async function reviewWithLlm(llm, decoded, analysis, signal) {
347
+ if (!llm || typeof llm.stream !== 'function') {
348
+ return { review: '', reviewError: 'DSH 模型服务不可用' };
349
+ }
350
+ try {
351
+ const rawProviders = typeof llm.listProviders === 'function'
352
+ ? await Promise.resolve(llm.listProviders())
353
+ : [];
354
+ const providers = Array.isArray(rawProviders)
355
+ ? rawProviders
356
+ : Object.keys(rawProviders || {}).map((key) => ({ id: key, ...(rawProviders[key] || {}) }));
357
+ if (!providers.length) throw new Error('DSH 未配置模型');
358
+ const provider = providers[0].id || providers[0].name || String(providers[0]);
359
+ let models = [];
360
+ if (typeof llm.listModels === 'function') {
361
+ try {
362
+ models = await llm.listModels(provider);
363
+ } catch {
364
+ models = [];
365
+ }
366
+ }
367
+ const model = (models && models[0] && (models[0].id || models[0].name)) || 'deepseek-v4-flash';
368
+ const prompt = buildReviewPrompt(decoded, analysis);
369
+ const timeout = AbortSignal.timeout(60000);
370
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
371
+ let text = '';
372
+ let reasoning = '';
373
+ for await (const chunk of llm.stream({
374
+ provider,
375
+ model,
376
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
377
+ temperature: 0.2,
378
+ maxTokens: 900,
379
+ signal: combined,
380
+ })) {
381
+ if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text;
382
+ if (chunk && chunk.type === 'reasoning-delta' && typeof chunk.text === 'string') {
383
+ reasoning += chunk.text;
384
+ }
385
+ }
386
+ const review = (text || reasoning).trim();
387
+ if (!review) throw new Error('模型没有返回复盘文字');
388
+ return { review, provider, model, reviewError: '' };
389
+ } catch (error) {
390
+ return {
391
+ review: '',
392
+ reviewError: error && error.message ? error.message : String(error),
393
+ };
394
+ }
395
+ }
396
+
397
+ export async function analyzeGame(code, options = {}) {
398
+ const decoded = decodeGm1(code);
399
+ const local = analyzeMoves(decoded);
400
+ const variants = [];
401
+ const realMistakes = local.mistakes.filter((item) => item.loss >= 4);
402
+ for (const mistake of realMistakes.slice(0, 3)) {
403
+ try {
404
+ variants.push(branchFrom(decoded, mistake));
405
+ } catch {
406
+ // A branch is optional; never fail the whole analysis for it.
407
+ }
408
+ }
409
+ const review = await reviewWithLlm(options.llm, decoded, local, options.signal);
410
+ const lastRate = local.rates[local.rates.length - 1].black;
411
+ const analysis = {
412
+ ...local,
413
+ variants,
414
+ review: review.review,
415
+ reviewError: review.reviewError,
416
+ reviewProvider: review.provider || '',
417
+ reviewModel: review.model || '',
418
+ finalBlackRate: lastRate,
419
+ winnerLabel: describeWinner(local.winner),
420
+ };
421
+ const bestText = local.bestMoves
422
+ .slice(0, 3)
423
+ .map((item) => `第 ${item.n} 手 ${item.colorLabel}${item.move.coord}`)
424
+ .join('、') || '无';
425
+ const mistakeText = local.mistakes
426
+ .filter((item) => item.loss >= 4)
427
+ .slice(0, 3)
428
+ .map((item) => `第 ${item.n} 手 ${item.colorLabel}${item.move.coord}(损失 ${item.loss}%)`)
429
+ .join('、') || '无明显失误';
430
+ const summary = [
431
+ `五子棋分析:共 ${local.total} 手,${analysis.winnerLabel}。`,
432
+ `当前黑方胜率 ${lastRate}%。`,
433
+ `值得肯定的手:${bestText}。`,
434
+ `可复盘的手:${mistakeText}。`,
435
+ `已生成 ${variants.length} 条改进分支。`,
436
+ review.review ? `总评:${review.review}` : `总评暂缺:${review.reviewError || '未调用模型'}`,
437
+ ].join('\n');
438
+ return { summary, analysis };
439
+ }
440
+
441
+ export { decodeGm1 };