-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.js
More file actions
1470 lines (1351 loc) · 60.7 KB
/
Copy pathserver.js
File metadata and controls
1470 lines (1351 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MakoCode 后端服务器 (Node.js)
* 通过 shell 启动 claude 命令(与终端完全一致),NDJSON 流式传输给前端。
* 零外部依赖,仅使用 Node.js 内置模块。
*
* 用法: node server.js [端口号,默认8080]
*
* 模块化:共享常量 → lib/constants.js | 工具函数 → lib/utils.js
* 设置管理 → lib/settings.js | 安装逻辑 → lib/installer.js
*/
const http = require("http");
const { spawn } = require("child_process");
const path = require("path");
const fs = require("fs");
const crypto = require("crypto");
// ─── 导入共享模块 ──────────────────────────────────────
const {
DEFAULT_PORT, RECENT_HISTORY_WINDOW, HISTORY_PREVIEW_LENGTH, MAX_UPLOAD_SIZE,
MIME_TYPES, APP_DIRS, SETTINGS_ALLOWED_KEYS,
} = require('./lib/constants');
const {
createLogger, modelLabel, isUserSpeaker, safeSessionId,
filterAllowedKeys, writeNDJsonLine, jsonError, ndjsonError, maskApiKey,
} = require('./lib/utils');
const settings = require('./lib/settings');
const llmPresets = require('./lib/llm-presets');
const installer = require('./lib/installer');
const galgameFeatures = require('./lib/galgame-features'); // Galgame 增强功能 (贡献者: 棘寒之龙)
const platform = require('./lib/platform');
// ─── 常量 ──────────────────────────────────────────────
const PORT = parseInt(process.argv[2]) || DEFAULT_PORT;
const RESOURCE_DIR = __dirname;
const DATA_DIR = process.env.MAKO_USER_DATA_DIR || RESOURCE_DIR;
const SAVES_DIR = path.join(DATA_DIR, APP_DIRS.SAVES);
const UPLOADS_DIR = path.join(DATA_DIR, APP_DIRS.UPLOADS);
const VOICE_DIR = path.join(DATA_DIR, APP_DIRS.VOICE);
const pendingQuestions = new Map(); // qId -> { proc, res }
const PENDING_QUESTION_TTL = 5 * 60 * 1000; // 5分钟无响应自动清理,防止内存泄漏
// 带 TTL 自动清理的 pendingQuestions 操作
function setPendingQuestion(qId, entry) {
entry._timer = setTimeout(() => {
log(`Pending question ${qId} timed out, force cleaning`);
pendingQuestions.delete(qId);
}, PENDING_QUESTION_TTL);
pendingQuestions.set(qId, entry);
}
function deletePendingQuestion(qId) {
const entry = pendingQuestions.get(qId);
if (entry && entry._timer) clearTimeout(entry._timer);
pendingQuestions.delete(qId);
}
function touchPendingQuestion(qId) {
const entry = pendingQuestions.get(qId);
if (entry && entry._timer) {
clearTimeout(entry._timer);
entry._timer = setTimeout(() => {
log(`Pending question ${qId} timed out, force cleaning`);
pendingQuestions.delete(qId);
}, PENDING_QUESTION_TTL);
}
}
const log = createLogger('server');
const MIME = MIME_TYPES; // 向后兼容别名
// 安全工具列表:在 default/plan 模式下自动允许,不弹权限窗口
const SAFE_TOOLS = new Set([
'Read', 'Glob', 'Grep', 'TaskList', 'TaskGet',
'WebSearch', 'WebFetch',
'Skill', 'CronList',
'mcp__playwright__browser_snapshot', 'mcp__playwright__browser_navigate',
'mcp__playwright__browser_console_messages',
]);
// ─── 设置初始化 ─────────────────────────────────────────
settings.load(DATA_DIR);
// 向后兼容:暴露 currentModel 变量(其他代码直接引用)
let currentModel = settings.getCurrentModel();
let currentModelMode = 'flash'; // 追踪用户选择的模式标签,独立于模型字符串
let permissionMode = 'default'; // 权限模式:default/acceptEdits/plan/bypass
// 启动时根据当前模型判断初始模式
(function initModelMode() {
const flashModel = process.env.ANTHROPIC_MODEL || 'deepseek-v4-flash';
const proModel = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'deepseek-v4-pro';
if (currentModel === proModel && currentModel !== flashModel) {
currentModelMode = 'pro';
}
})();
// 向后兼容函数别名
function buildEnv() { return settings.buildEnv(); }
function loadMakoSettings() { settings.load(DATA_DIR); currentModel = settings.getCurrentModel(); }
function saveMakoSettings(s) { return settings.save(DATA_DIR, s); }
// 确保目录存在
function ensureAppDirs() {
const dirs = [
SAVES_DIR, UPLOADS_DIR, VOICE_DIR,
// Galgame 增强功能 (贡献者: 棘寒之龙)
path.join(DATA_DIR, APP_DIRS.USER_BGM),
path.join(DATA_DIR, APP_DIRS.USER_CHARA),
path.join(DATA_DIR, APP_DIRS.USER_BG),
];
dirs.forEach(d => { if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true }); });
}
ensureAppDirs();
// ─── 存档 API ────────────────────────────────────────
function listSaves(res) {
fs.readdir(SAVES_DIR, (err, files) => {
if (err) {
res.writeHead(500);
res.end(JSON.stringify({ error: "读取存档目录失败" }));
return;
}
const saves = [];
let pending = files.filter(f => f.endsWith(".json")).length;
if (pending === 0) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify([]));
return;
}
files.filter(f => f.endsWith(".json")).forEach(file => {
fs.readFile(path.join(SAVES_DIR, file), "utf8", (err, data) => {
pending--;
if (!err) {
try {
const save = JSON.parse(data);
saves.push({
id: save.id,
title: save.title || "无标题",
createdAt: save.createdAt,
updatedAt: save.updatedAt,
messageCount: (save.history || []).length,
});
} catch {}
}
if (pending === 0) {
saves.sort((a, b) => (b.updatedAt || "").localeCompare(a.updatedAt || ""));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(saves));
}
});
});
});
}
function loadSave(res, id) {
const filePath = path.join(SAVES_DIR, `${id}.json`);
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
res.writeHead(404);
res.end(JSON.stringify({ error: "存档不存在" }));
return;
}
try {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(data);
} catch {
res.writeHead(500);
res.end(JSON.stringify({ error: "存档损坏" }));
}
});
}
function saveGame(res, data) {
if (!data.id) {
res.writeHead(400);
res.end(JSON.stringify({ error: "缺少存档 ID" }));
return;
}
const filePath = path.join(SAVES_DIR, `${data.id}.json`);
const saveData = {
...data,
updatedAt: new Date().toISOString(),
createdAt: data.createdAt || new Date().toISOString(),
};
fs.writeFile(filePath, JSON.stringify(saveData, null, 2), "utf8", (err) => {
if (err) {
log(`Save error: ${err.message}`);
res.writeHead(500);
res.end(JSON.stringify({ error: "保存失败" }));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
});
}
function deleteSave(res, id) {
const filePath = path.join(SAVES_DIR, `${id}.json`);
fs.unlink(filePath, (err) => {
if (err) {
res.writeHead(404);
res.end(JSON.stringify({ error: "存档不存在" }));
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
});
}
// ─── HTTP 服务器 ─────────────────────────────────────
const server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", `http://127.0.0.1:${PORT}`);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
// ── GET / HEAD ──
if (req.method === "GET" || req.method === "HEAD") {
const isHead = req.method === "HEAD";
// 快捷指令列表
if (url.pathname === "/api/commands") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(getCommands()));
return;
}
// LLM 供应商预设列表
if (url.pathname === "/api/llm-presets") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(llmPresets.getAllPresets()));
return;
}
// 健康检查
if (url.pathname === "/api/projects" || url.pathname === "/api/projects/") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ projects: [] }));
return;
}
// 读取当前模型
if (url.pathname === "/api/model") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ model: currentModel, label: currentModelMode === 'pro' ? 'Pro' : 'Flash' }));
return;
}
// 读取茉子设置
if (url.pathname === "/api/mako-settings") {
const safe = settings.getAll(true); // true = 脱敏 API Key
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(safe));
return;
}
// 列出存档
if (url.pathname === "/api/saves") {
listSaves(res);
return;
}
// 加载存档 /api/saves/:id
const saveMatch = url.pathname.match(/^\/api\/saves\/([a-zA-Z0-9_-]+)$/);
if (saveMatch) {
loadSave(res, saveMatch[1]);
return;
}
// 版本信息
if (url.pathname === "/api/version") {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(RESOURCE_DIR, 'package.json'), 'utf8'));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ version: pkg.version || '1.0.0' }));
} catch {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ version: '1.0.0' }));
}
return;
}
// 打开 skills 文件夹(浏览器模式回退)
if (url.pathname === "/api/open-skills-folder") {
const skillsDir = path.join(require('os').homedir(), '.claude', 'skills');
try {
if (!fs.existsSync(skillsDir)) fs.mkdirSync(skillsDir, { recursive: true });
const invocation = platform.openPathInvocation(skillsDir);
const child = spawn(invocation.command, invocation.args, { stdio: 'ignore' });
child.on('error', (err) => log(`open-skills-folder error: ${err.message}`));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, path: skillsDir }));
} catch (e) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: e.message }));
}
return;
}
// 打开 plugins 文件夹(浏览器模式回退)
if (url.pathname === "/api/open-plugins-folder") {
const pluginsDir = path.join(require('os').homedir(), '.claude', 'plugins');
try {
if (!fs.existsSync(pluginsDir)) fs.mkdirSync(pluginsDir, { recursive: true });
const invocation = platform.openPathInvocation(pluginsDir);
const child = spawn(invocation.command, invocation.args, { stdio: 'ignore' });
child.on('error', (err) => log(`open-plugins-folder error: ${err.message}`));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, path: pluginsDir }));
} catch (e) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: e.message }));
}
return;
}
// 读取茉子人设(CLAUDE.md + SKILL.md)
if (url.pathname === "/api/persona") {
const personaFile = path.join(DATA_DIR, 'CLAUDE.md');
const skillFile = path.join(DATA_DIR, '.claude', 'skills', 'mako-lore', 'SKILL.md');
try {
const result = {};
if (fs.existsSync(personaFile)) result.persona = fs.readFileSync(personaFile, 'utf8');
if (fs.existsSync(skillFile)) result.lore = fs.readFileSync(skillFile, 'utf8');
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, ...result }));
} catch (e) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: e.message }));
}
return;
}
// ═══════════════════════════════════════════════════════════
// Galgame 增强功能 (贡献者: 棘寒之龙 @ Bilibili)
// ═══════════════════════════════════════════════════════════
// BGM 列表
if (url.pathname === "/api/bgm-list") { galgameFeatures.handleBgmList(DATA_DIR, res, RESOURCE_DIR); return; }
// 背景图列表 (支持 ?dir=user-chara / ?dir=user-bg)
if (url.pathname === "/api/bg-list") { galgameFeatures.handleBgList(DATA_DIR, url, res, RESOURCE_DIR); return; }
// 任务列表
if (url.pathname === "/api/tasks") { galgameFeatures.handleTasks(DATA_DIR, req, res); return; }
// 角色设定
if (url.pathname === "/api/character-config") { galgameFeatures.handleCharacterConfig(DATA_DIR, req, res, settings); return; }
// NAT 状态
if (url.pathname === "/api/nat") { galgameFeatures.handleNat(DATA_DIR, req, res); return; }
// 自定义角色列表
if (url.pathname === "/api/user-chara/list") { galgameFeatures.handleUserCharaList(DATA_DIR, res); return; }
// 自定义角色详情 ?name=xxx
if (url.pathname === "/api/user-chara/get") { galgameFeatures.handleUserCharaGet(DATA_DIR, url, res); return; }
// 当前激活的自定义角色名
if (url.pathname === "/api/user-chara/active") { galgameFeatures.handleUserCharaActive(DATA_DIR, res); return; }
// 获取已保存的语音文件 /api/voice/:voiceId
const voiceMatch = url.pathname.match(/^\/api\/voice\/([a-zA-Z0-9_-]+)$/);
if (voiceMatch) {
const voiceFile = path.join(VOICE_DIR, `${voiceMatch[1]}.wav`);
fs.readFile(voiceFile, (err, data) => {
if (err) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "语音文件不存在" }));
return;
}
res.writeHead(200, {
"Content-Type": "audio/wav",
"Cache-Control": "public, max-age=31536000",
"Content-Length": data.length,
});
res.end(data);
});
return;
}
// 静态文件 — 用 decodeURIComponent 解码路径(处理日文文件名)
let rawPath = (req.url || "/").split("?")[0].split("#")[0];
let filePath;
try { filePath = decodeURIComponent(rawPath); }
catch (e) { res.writeHead(400); res.end("Bad Request"); return; }
if (filePath === "/") filePath = "/galchat.html";
let safePath = path.normalize(filePath).replace(/^[/\\]+/, "");
if (safePath.includes("..")) { res.writeHead(403); res.end("Forbidden"); return; }
const dataPath = path.join(DATA_DIR, safePath);
let fullPath = fs.existsSync(dataPath) ? dataPath : path.join(RESOURCE_DIR, safePath);
fs.readFile(fullPath, (err, data) => {
if (err) {
if (err.code === 'ENOENT') log(`404: ${safePath} → ${fullPath}`);
res.writeHead(404); res.end("Not Found"); return;
}
const ext = path.extname(fullPath).toLowerCase();
res.writeHead(200, {
"Content-Type": MIME[ext] || "application/octet-stream",
"Content-Length": data.length,
"Cache-Control": "no-cache",
});
res.end(isHead ? undefined : data);
});
return;
}
// ── POST ──
if (req.method === "POST") {
// TTS 语音(打包版:仅返回预生成问候语音文件,不调用 GPT-SoVITS)
if (url.pathname === "/api/tts") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { text } = JSON.parse(body);
if (!text) { jsonError(res, "缺少 text 参数"); return; }
// 尝试匹配预生成语音(assets/voice/greet_NN.wav)
const greetMatch = text.match(/greet_(\d{2})\.wav$/);
let voicePath = null;
if (greetMatch) {
voicePath = path.join(RESOURCE_DIR, "assets", "voice", `greet_${greetMatch[1]}.wav`);
}
// 也检查 voice-data 缓存目录
if (!voicePath || !fs.existsSync(voicePath)) {
const cachePath = path.join(VOICE_DIR, `${crypto.createHash("md5").update(text).digest("hex").substring(0, 7)}.wav`);
if (fs.existsSync(cachePath)) voicePath = cachePath;
}
if (voicePath && fs.existsSync(voicePath)) {
const stat = fs.statSync(voicePath);
res.writeHead(200, {
"Content-Type": "audio/wav",
"Content-Length": stat.size,
"Cache-Control": "public, max-age=3600",
});
fs.createReadStream(voicePath).pipe(res);
} else {
// 无预生成语音 → 返回 404(前端静默处理)
res.writeHead(404);
res.end("No pre-generated voice available");
}
} catch { jsonError(res, "JSON 格式错误"); }
});
return;
}
// 聊天
if (url.pathname === "/api/chat") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { message, sessionId, allowedTools, permissionMode: reqPermMode, uploadedFiles, history } = JSON.parse(body);
const effectivePermMode = (reqPermMode && reqPermMode !== 'default') ? reqPermMode : permissionMode;
let prompt = (message || "").trim();
// ═══════════════════════════════════════════════════════
// Token 优化: 分层历史注入
// 原因: --session-id 在 spawn/kill 循环中不可靠,必须手动维护上下文
// 策略: 最近 10 轮原文 + 10 轮以前压缩为摘要(不丢记忆,但省 token)
// ═══════════════════════════════════════════════════════
if (history && history.length > 0) {
const RECENT_WINDOW = 10; // 保留最近 N 轮完整对话
if (history.length <= RECENT_WINDOW) {
// 短对话:全部保留原文
const historyCtx = history.map(h => {
const isUser = h.speaker === '主人' || h.speaker === '用户' || h.speaker === '玩家';
return isUser ? `玩家:${h.text}` : `茉子:${h.text}`;
}).join('\n');
prompt = `以下是你(茉子)与玩家之前的对话记录,请记住这些上下文,继续保持角色:\n\n${historyCtx}\n\n---\n玩家刚刚说:${prompt}`;
} else {
// 长对话:最近 10 轮原文 + 早期压缩
const oldHistory = history.slice(0, -RECENT_WINDOW);
const recentHistory = history.slice(-RECENT_WINDOW);
// 压缩早期对话为简短摘要(减少 token,但不丢话题脉络)
const oldSummary = oldHistory.map(h => {
const isUser = h.speaker === '主人' || h.speaker === '用户' || h.speaker === '玩家';
const preview = h.text.length > 60 ? h.text.substring(0, 60) + '…' : h.text;
return isUser ? `玩家说了:「${preview}」` : `茉子回应了:「${preview}」`;
}).join('\n');
const recentCtx = recentHistory.map(h => {
const isUser = h.speaker === '主人' || h.speaker === '用户' || h.speaker === '玩家';
return isUser ? `玩家:${h.text}` : `茉子:${h.text}`;
}).join('\n');
prompt = `以下是你(茉子)与玩家之前的对话记录。\n\n【早期对话摘要】\n${oldSummary}\n\n【最近对话(请重点记住)】\n${recentCtx}\n\n---\n玩家刚刚说:${prompt}`;
}
}
// 模型切换指令:/model flash 或 /model pro
const modelMatch = prompt.match(/^\/model\s+(pro|flash)$/i);
if (modelMatch) {
const target = modelMatch[1].toLowerCase();
const flashModel = process.env.ANTHROPIC_MODEL || 'deepseek-v4-flash';
const proModel = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'deepseek-v4-pro';
currentModel = target === 'pro' ? proModel : flashModel;
currentModelMode = target === 'pro' ? 'pro' : 'flash';
log(`Model switched to: ${currentModel} (via chat command)`);
res.writeHead(200, {
"Content-Type": "application/x-ndjson",
"Cache-Control": "no-cache",
});
writeLine(res, { type: 'claude_json', data: {
type: 'assistant', message: { content: [{ type: 'text', text: `🔀 模型已切换至 **${modelLabel(currentModel)}**,下条消息生效。` }] }
}});
writeLine(res, { type: 'done' });
res.end();
return;
}
// ═══════════════════════════════════════════════════════
// 茉子人设注入:新会话(history为空)时加载 CLAUDE.md + SKILL.md
// 原因: --input-format stream-json + sdk-ts 模式下 claude.exe 不会自动读取 CLAUDE.md
// 策略: 仅在首条消息注入,后续复用 session 上下文以节省 token
// ═══════════════════════════════════════════════════════
if (!history || history.length === 0) {
try {
const personaParts = [];
// 读取 CLAUDE.md(角色主设定)
const personaFile = path.join(DATA_DIR, 'CLAUDE.md');
if (fs.existsSync(personaFile)) {
let content = fs.readFileSync(personaFile, 'utf8').trim();
// 移除「使用 Skill 工具加载 mako-lore」的提示(因为下面直接注入了 SKILL.md 内容)
content = content.replace(
/> ⚠️ \*\*启动时使用 Skill 工具加载 `mako-lore`\*\* — 包含穗织世界观、神话诅咒、身边人物、API速查表。这些是你的背景知识,对话中随时可能用到。\n?/g,
''
);
if (content) personaParts.push(content);
}
// 读取 SKILL.md(世界观/背景知识)
const skillFile = path.join(DATA_DIR, '.claude', 'skills', 'mako-lore', 'SKILL.md');
if (fs.existsSync(skillFile)) {
let content = fs.readFileSync(skillFile, 'utf8');
// 去掉 YAML frontmatter (--- 之间的内容)
content = content.replace(/^---[\s\S]*?---\n?/, '').trim();
if (content) personaParts.push('# 世界观与背景知识\n' + content);
}
if (personaParts.length > 0) {
prompt = personaParts.join('\n\n---\n\n') + '\n\n---\n\n' + prompt;
log(`Persona injected (${(prompt.length / 1024).toFixed(1)}KB, new session)`);
}
} catch (e) {
log(`Failed to load persona: ${e.message}`);
}
}
// 如果有上传文件,在 prompt 中附加文件路径信息
if (uploadedFiles && uploadedFiles.length > 0) {
const fileList = uploadedFiles.map(f => `- ${f.path}`).join('\n');
prompt = `${prompt}\n\n[用户上传了以下文件,请先使用 Read 工具逐个读取所有文件的内容,再根据文件内容回答用户的问题:]\n${fileList}`;
}
if (!prompt) {
endWithError(res, "消息内容为空");
return;
}
log(`Chat: ${prompt.substring(0, 120)}...`);
// 注入当前权限模式,让茉子知道自己所处的模式
const modeLabels = { default: '默认模式(每步操作都需要确认)', acceptEdits: '编辑模式(文件读写自动通过,Shell仍需确认)', plan: '计划模式(纯只读,不能修改文件)', bypass: '自动模式(完全自主执行所有操作)' };
prompt = prompt + '\n\n[系统提示:当前会话运行在「' + (modeLabels[effectivePermMode] || effectivePermMode) + '」。]';
res.writeHead(200, {
"Content-Type": "application/x-ndjson",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
streamChat(res, prompt, sessionId, allowedTools, effectivePermMode);
} catch (e) {
log(`Parse error: ${e.message}`);
endWithError(res, "请求体 JSON 格式错误");
}
});
return;
}
// 问题回答
if (url.pathname === "/api/respond") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { qId, answer } = JSON.parse(body);
const entry = pendingQuestions.get(qId);
if (entry && entry.proc.exitCode === null) {
// 将前端传来的 1-based 索引映射为选项的实际值
const idx = parseInt(answer) - 1;
const question = entry.question;
let answerValue = answer; // 默认直接用前端传的值
if (question && question.optionsRaw && idx >= 0 && idx < question.optionsRaw.length) {
const rawOpt = question.optionsRaw[idx];
// rawOpt 可能是 {label, value} 对象,也可能是字符串
if (typeof rawOpt === 'object' && rawOpt !== null && rawOpt.value) {
answerValue = rawOpt.value;
} else if (typeof rawOpt === 'string') {
answerValue = rawOpt;
}
}
log(`Question answered: idx=${idx}, value="${answerValue}" (raw=${answer})`);
// 以 stream-json 用户消息格式写回 stdin,Claude 读取作为权限回答
const respMsg = JSON.stringify({ type: "user", message: { role: "user", content: answerValue } });
entry.proc.stdin.write(respMsg + "\n");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "question not found or process ended" }));
}
} catch {
jsonError(res, "JSON 格式错误");
}
});
return;
}
// 切换模型
if (url.pathname === "/api/model") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { model } = JSON.parse(body);
const flashModel = process.env.ANTHROPIC_MODEL || 'deepseek-v4-flash';
const proModel = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'deepseek-v4-pro';
if (model === "flash" || model === flashModel) {
currentModel = flashModel;
currentModelMode = 'flash';
} else if (model === "pro" || model === proModel) {
currentModel = proModel;
currentModelMode = 'pro';
} else {
jsonError(res, "未知模型,可选 flash / pro");
return;
}
log(`Model switched to: ${currentModel}`);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ model: currentModel, label: currentModelMode === 'pro' ? 'Pro' : 'Flash' }));
} catch {
jsonError(res, "JSON 格式错误");
}
});
return;
}
// 切换权限模式
if (url.pathname === "/api/mode") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { mode } = JSON.parse(body);
if (!["default", "acceptEdits", "plan", "bypass"].includes(mode)) {
jsonError(res, "无效模式,可选 default/acceptEdits/plan/bypass");
return;
}
permissionMode = mode;
log(`Permission mode set to: ${permissionMode}`);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ mode: permissionMode }));
} catch {
jsonError(res, "JSON 格式错误");
}
});
return;
}
// 保存茉子人设
if (url.pathname === "/api/persona") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { persona, lore } = JSON.parse(body);
const personaFile = path.join(DATA_DIR, 'CLAUDE.md');
const skillFile = path.join(DATA_DIR, '.claude', 'skills', 'mako-lore', 'SKILL.md');
let saved = false;
if (persona !== undefined && persona !== null) {
const personaDir = path.dirname(personaFile);
if (!fs.existsSync(personaDir)) fs.mkdirSync(personaDir, { recursive: true });
fs.writeFileSync(personaFile, persona, 'utf8');
saved = true;
}
if (lore !== undefined && lore !== null) {
const loreDir = path.dirname(skillFile);
if (!fs.existsSync(loreDir)) fs.mkdirSync(loreDir, { recursive: true });
fs.writeFileSync(skillFile, lore, 'utf8');
saved = true;
}
log('Persona files saved');
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
} catch (e) {
log(`Persona save error: ${e.message}`);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: false, error: e.message }));
}
});
return;
}
// 保存茉子设置
if (url.pathname === "/api/mako-settings") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const settings = JSON.parse(body);
// 只允许白名单中的字段
const allowed = [
"ANTHROPIC_BASE_URL",
"ANTHROPIC_AUTH_TOKEN",
"ANTHROPIC_MODEL",
"ANTHROPIC_DEFAULT_OPUS_MODEL",
"ANTHROPIC_DEFAULT_SONNET_MODEL",
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
"CLAUDE_CODE_SUBAGENT_MODEL",
"CLAUDE_CODE_EFFORT_LEVEL",
];
const filtered = {};
for (const key of allowed) {
if (settings[key] !== undefined) {
filtered[key] = String(settings[key]).trim();
}
}
if (saveMakoSettings(filtered)) {
// 如果修改了 ANTHROPIC_MODEL,同步更新 currentModel
if (filtered.ANTHROPIC_MODEL) {
currentModel = filtered.ANTHROPIC_MODEL;
log(`currentModel synced from settings: ${currentModel}`);
const proModel = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'deepseek-v4-pro';
const flashModel = process.env.ANTHROPIC_MODEL || 'deepseek-v4-flash';
if (currentModel === proModel && currentModel !== flashModel) {
currentModelMode = 'pro';
} else {
currentModelMode = 'flash';
}
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, model: currentModel, label: modelLabel(currentModel) }));
} else {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "保存失败" }));
}
} catch {
jsonError(res, "JSON 格式错误");
}
});
return;
}
// 结束游戏(关闭服务器)
if (url.pathname === "/api/quit") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
log("Quit requested — shutting down in 1s...");
setTimeout(() => process.exit(0), 1000);
return;
}
// 更新状态(从 .update-status.json 读取,由 Electron 主进程写入)
if (url.pathname === "/api/update/status") {
const updateFile = path.join(DATA_DIR, '.update-status.json');
try {
if (fs.existsSync(updateFile)) {
const data = JSON.parse(fs.readFileSync(updateFile, 'utf8'));
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(data));
} else {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ state: 'idle', version: null, progress: 0, error: null }));
}
} catch {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ state: 'idle' }));
}
return;
}
// 文件上传
if (url.pathname === "/api/upload") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
handleUpload(res, JSON.parse(body));
} catch {
jsonError(res, "JSON 格式错误");
}
});
return;
}
// ── 首次配置向导 API ──
// 检查命令是否存在
if (url.pathname === "/api/check-command") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { command } = JSON.parse(body);
res.writeHead(200, { "Content-Type": "application/json" });
const found = command === 'node'
? platform.commandExists('node') && platform.commandExists('npm')
: platform.commandExists(command);
res.end(JSON.stringify({ found, command }));
} catch { jsonError(res, "JSON 格式错误"); }
});
return;
}
// 安装 Claude Code
if (url.pathname === "/api/install-claude-code") {
req.on("data", () => {});
req.on("end", () => {
res.writeHead(200, { "Content-Type": "application/json" });
const invocation = platform.commandInvocation(
"npm",
["install", "-g", "@anthropic-ai/claude-code"]
);
const installEnv = process.platform === 'darwin'
? { ...process.env, PATH: [process.env.PATH, '/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin'].filter(Boolean).join(path.delimiter) }
: process.env;
const npmCommand = platform.resolveCommand(invocation.command, installEnv);
if (!npmCommand) {
res.end(JSON.stringify({ ok: false, output: '找不到 npm,请先完成 Node.js 安装后再重试' }));
return;
}
const install = spawn(npmCommand, invocation.args, {
stdio: ["pipe", "pipe", "pipe"],
env: installEnv,
});
let out = "", err = "";
install.stdout.on("data", (d) => (out += d.toString()));
install.stderr.on("data", (d) => (err += d.toString()));
install.on("close", (code) => {
res.end(JSON.stringify({ ok: code === 0, output: out + err }));
});
install.on("error", (e) => {
res.end(JSON.stringify({ ok: false, output: e.message }));
});
});
return;
}
// 后台静默安装 Node.js / Git(从 bundled-tools 嵌入包)
if (url.pathname === "/api/open-git-installer") {
req.on("data", () => {});
req.on("end", () => {
res.writeHead(200, { "Content-Type": "application/json" });
if (process.platform !== 'darwin') {
res.end(JSON.stringify({ ok: false, message: '此按钮仅适用于 macOS' }));
return;
}
try {
const child = spawn('/usr/bin/xcode-select', ['--install'], { stdio: 'ignore' });
let settled = false;
child.once('error', (error) => {
if (settled) return;
settled = true;
res.end(JSON.stringify({ ok: false, message: `无法打开 Git 安装器:${error.message}` }));
});
child.once('close', () => {
if (settled) return;
settled = true;
res.end(JSON.stringify({ ok: true, message: '已请求打开 Git 安装器;完成后点击重试' }));
});
} catch (error) {
res.end(JSON.stringify({ ok: false, message: `无法打开 Git 安装器:${error.message}` }));
}
});
return;
}
// 后台静默安装 Node.js / Git(从 bundled-tools 嵌入包)
if (url.pathname === "/api/install-tools") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { tools } = JSON.parse(body); // tools: ["node", "git"]
if (!tools || !Array.isArray(tools) || tools.length === 0) {
jsonError(res, "缺少 tools 参数");
return;
}
res.writeHead(200, {
"Content-Type": "application/x-ndjson",
"Cache-Control": "no-cache",
});
installer.installToolsStreaming(res, RESOURCE_DIR, tools);
} catch { jsonError(res, "JSON 格式错误"); }
});
return;
}
if (url.pathname === "/api/save-settings") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const settings = JSON.parse(body);
const allowed = [
"ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_MODEL",
];
const filtered = {};
for (const key of allowed) {
if (settings[key] !== undefined) {
filtered[key] = String(settings[key]).trim();
}
}
const ok = saveMakoSettings(filtered);
if (filtered.ANTHROPIC_MODEL) {
currentModel = filtered.ANTHROPIC_MODEL;
const proModel = process.env.ANTHROPIC_DEFAULT_OPUS_MODEL || 'deepseek-v4-pro';
const flashModel = process.env.ANTHROPIC_MODEL || 'deepseek-v4-flash';
if (currentModel === proModel && currentModel !== flashModel) {
currentModelMode = 'pro';
} else {
currentModelMode = 'flash';
}
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok }));
} catch { jsonError(res, "JSON 格式错误"); }
});
return;
}
// 测试 API 连接
if (url.pathname === "/api/test-connection") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
try {
const { endpoint, key, model } = JSON.parse(body);
let baseUrl = (endpoint || "https://api.deepseek.com").replace(/\/+$/, "");
// 去掉 /anthropic 后缀 — Claude Code 用兼容端点,但测试必须用 OpenAI 原生 /v1/chat/completions
const apiBase = baseUrl.replace(/\/anthropic\/?$/, '');
const testUrl = `${apiBase}/v1/chat/completions`;
const postData = JSON.stringify({
model: model || "deepseek-chat",
messages: [{ role: "user", content: "hi" }],
max_tokens: 5,
});
const https = require("https");
const httpMod = require("http");
const mod = testUrl.startsWith("https") ? https : httpMod;
let responded = false;
const respond = (payload) => {
if (responded) return;
responded = true;
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(payload));
};
const req2 = mod.request(testUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${key}`,
"Content-Length": Buffer.byteLength(postData),
},
timeout: 15000,
}, (apiRes) => {
let data2 = "";
apiRes.on("data", (d) => (data2 += d));
apiRes.on("end", () => {
if (apiRes.statusCode === 200) {
respond({ ok: true, message: "API 连接正常!茉子可以正常运转啦~" });
} else {
let errMsg = `HTTP ${apiRes.statusCode}`;
try {
const errJson = JSON.parse(data2);
if (errJson.error?.message) errMsg = errJson.error.message;
} catch {}
respond({ ok: false, message: errMsg });
}
});
});
req2.on("error", (e) => {
respond({ ok: false, message: `连接失败:${e.message}` });
});
req2.on("timeout", () => {
req2.destroy(new Error("请求超时"));
});
req2.write(postData);
req2.end();
} catch (e) {
jsonError(res, e.message);
}
});
return;
}
// 标记首次配置完成
if (url.pathname === "/api/finish-setup") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
// 默认保留所有安装包(安全默认值),只有用户明确取消勾选才删除
let keepTools = ["node", "git"];
try {
const parsed = JSON.parse(body || "{}");
if (Array.isArray(parsed.keepTools)) {
keepTools = parsed.keepTools;