-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathserver.js
More file actions
1772 lines (1586 loc) · 59.5 KB
/
Copy pathserver.js
File metadata and controls
1772 lines (1586 loc) · 59.5 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
require("dotenv").config({ quiet: true });
const Fastify = require("fastify");
const fs = require("fs-extra");
const path = require("path");
const {
PROJECT_DIR,
ensureDataDir,
runtimeDirectory,
runtimeFile,
writeJsonAtomicSync
} = require("./runtime_paths");
const { isSpecialEventContent } = require("./special_events");
const { decideRequestAccess } = require("./network_access");
const {
formatDateTimeInTimeZone,
resolveTimeZone,
zonedWallTimeToDate
} = require("./time_utils");
const DEFAULT_BODY_LIMIT_MB = 50;
function readBodyLimitBytes() {
const configured = Number(process.env.REQUEST_BODY_LIMIT_MB);
const mb = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_BODY_LIMIT_MB;
return Math.floor(mb * 1024 * 1024);
}
const app = Fastify({
logger: true,
bodyLimit: readBodyLimitBytes()
});
app.register(require("@fastify/formbody"));
const PORT = Number(process.env.PORT) || 3000;
const TARGET_API_URL = process.env.TARGET_API_URL;
const TIME_ZONE = resolveTimeZone();
const IS_RAILWAY_RUNTIME = Boolean(
process.env.RAILWAY_ENVIRONMENT ||
process.env.RAILWAY_PROJECT_ID ||
process.env.RAILWAY_SERVICE_ID
);
// 批注 2026-08-10:默认路径仍是项目目录,保护本机/VPS 旧部署;Railway 挂载 Volume 后
// DATA_DIR(或平台提供的 RAILWAY_VOLUME_MOUNT_PATH)统一承载时间线、时间戳、预设和日记。
const DATA_DIR = ensureDataDir();
const TIMELINE_FILE = runtimeFile("enhanced_messages.json");
const TIMESTAMP_DB_FILE = runtimeFile("message_timestamps.json");
// 批注 2026-07-17:管理页保存 .env 后要让 PM2 刷新进程环境;保留原进程名,
// 只补 --update-env,避免用户改完推送配置却继续运行旧值。
const DEFAULT_RESTART_COMMAND = "pm2 restart gateway wake-up --update-env";
function readBooleanEnv(key, fallback = false) {
const raw = String(process.env[key] ?? "").trim().toLowerCase();
if (!raw) return fallback;
return ["1", "true", "yes", "on"].includes(raw);
}
function configuredModelName() {
// 批注 2026-07-15:/v1/models 要暴露部署者实际配置的模型名;
// 不能继续硬编码示例模型,否则 Kelivo 模型选择会和真实上游不一致。
return String(process.env.MODEL_NAME || "gateway-model").trim() || "gateway-model";
}
// ========================
// 多模态消息处理
// ========================
function shouldForwardMultimodalContent() {
// 批注 2026-07-15:默认把 Kelivo 的图片 content 数组原样交给视觉模型;
// 如果上游不是多模态模型,部署者仍可显式设 MULTIMODAL_MODE=text 退回旧的 [图片] 占位模式。
const mode = (process.env.MULTIMODAL_MODE || "passthrough").trim().toLowerCase();
return !["text", "plain", "placeholder", "false", "off", "0"].includes(mode);
}
function isDataImageUrl(value) {
return typeof value === "string" && /^data:image\//i.test(value);
}
function isImageContentPart(part) {
if (!part || typeof part !== "object") return false;
if (part.image_url) return true;
const type = typeof part.type === "string" ? part.type.toLowerCase() : "";
return type.includes("image");
}
function isFileContentPart(part) {
if (!part || typeof part !== "object") return false;
if (part.file) return true;
const type = typeof part.type === "string" ? part.type.toLowerCase() : "";
return type.includes("file");
}
function getTextFromContentPart(part) {
if (typeof part === "string") return part;
if (!part || typeof part !== "object") return "";
const type = typeof part.type === "string" ? part.type.toLowerCase() : "";
if (type === "text" || type === "input_text") return part.text || part.content || "";
if (typeof part.text === "string") return part.text;
return "";
}
function normalizeContentToText(content) {
if (typeof content === "string") return content;
if (content == null) return "";
if (Array.isArray(content)) {
const parts = content
.map(part => {
const text = getTextFromContentPart(part).trim();
if (text) return text;
if (isImageContentPart(part)) return "[图片]";
if (isFileContentPart(part)) return "[文件]";
return "";
})
.filter(Boolean);
return parts.join("\n");
}
if (isImageContentPart(content)) return "[图片]";
if (isFileContentPart(content)) return "[文件]";
return "[非文本内容]";
}
function normalizeMessageForTimeline(msg) {
return { ...msg, content: normalizeContentToText(msg.content) };
}
function prepareMessageForLLM(msg) {
if (msg.role === "assistant" && msg.tool_calls) return msg;
if (msg.role === "tool") return msg;
if (msg.role === "system") return { ...msg, content: normalizeContentToText(msg.content) };
if (typeof msg.content === "string") return msg;
if (Array.isArray(msg.content) && shouldForwardMultimodalContent()) return msg;
const textContent = normalizeContentToText(msg.content);
if (!textContent) return null;
return { ...msg, content: textContent };
}
function sanitizeForLog(value) {
if (typeof value === "string") {
if (isDataImageUrl(value)) {
const commaIndex = value.indexOf(",");
const prefix = commaIndex >= 0 ? value.slice(0, commaIndex + 1) : value.slice(0, 40);
return `${prefix}[base64 image omitted]`;
}
if (value.length > 1000) return `${value.slice(0, 1000)}... [truncated ${value.length - 1000} chars]`;
return value;
}
if (Array.isArray(value)) return value.map(sanitizeForLog);
if (value && typeof value === "object") {
const sanitized = {};
for (const [key, child] of Object.entries(value)) {
sanitized[key] = sanitizeForLog(child);
}
return sanitized;
}
return value;
}
function summarizeMessageForLog(msg) {
const parts = Array.isArray(msg?.content) ? msg.content : [msg?.content];
const textChars = parts.reduce((sum, part) => sum + getTextFromContentPart(part).length, 0);
return {
role: msg?.role || "",
content_type: Array.isArray(msg?.content) ? "multimodal" : typeof msg?.content,
text_chars: textChars || normalizeContentToText(msg?.content).length,
image_parts: parts.filter(isImageContentPart).length,
file_parts: parts.filter(isFileContentPart).length,
tool_calls: Array.isArray(msg?.tool_calls) ? msg.tool_calls.length : 0
};
}
function summarizeMessagesForLog(messages = []) {
const list = Array.isArray(messages) ? messages : [];
const roles = {};
let imageParts = 0;
let fileParts = 0;
let textChars = 0;
for (const msg of list) {
const item = summarizeMessageForLog(msg);
roles[item.role] = (roles[item.role] || 0) + 1;
imageParts += item.image_parts;
fileParts += item.file_parts;
textChars += item.text_chars;
}
return { total: list.length, roles, text_chars: textChars, image_parts: imageParts, file_parts: fileParts };
}
function escapeHtml(value) {
return String(value ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function safeJsonForInlineScript(value) {
return JSON.stringify(value)
.replace(/</g, "\\u003c")
.replace(/>/g, "\\u003e")
.replace(/&/g, "\\u0026")
.replace(/\u2028/g, "\\u2028")
.replace(/\u2029/g, "\\u2029");
}
// ========================
// 读取 timeline
// ========================
function loadTimeline() {
if (!fs.existsSync(TIMELINE_FILE)) return [];
try { return fs.readJsonSync(TIMELINE_FILE); } catch { return []; }
}
// ========================
// 保存 timeline(保留 SP)
// ========================
function saveTimeline(messages) {
const sp = messages.find(m => m.role === "system");
const nonSP = messages.filter(m => m.role !== "system");
const trimmed = nonSP.slice(-49);
const final = sp ? [sp, ...trimmed] : trimmed;
writeJsonAtomicSync(TIMELINE_FILE, final);
}
// ========================
// 提取时间戳(支持多种格式)
// ========================
function parseTimestampLabel(value) {
const text = String(value || "");
const match = text.match(/(?\s*(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T]?)(\d{1,2})[::](\d{2})/);
if (!match) return null;
const [, yyyy, , month, day, hour, minute] = match;
// 批注 2026-07-30:Kelivo 写进消息前缀的是用户配置时区的墙上时间;
// 公网/Railway 不能按服务器 UTC 解析,否则时间线和自动唤醒都会被推迟。
return zonedWallTimeToDate({ year: yyyy, month, day, hour, minute }, TIME_ZONE);
}
function stripLeadingTimestamp(content) {
// 批注 2026-07-15:兼容 Kelivo 有时把日期和时间贴在一起的前缀;
// 旧格式 "YYYY-MM-DD HH:mm" 继续保留,新格式 "YYYY-MM-DDHH:mm" 不再导致时间记忆/排序失效。
return String(content || "")
.replace(/^(?\s*\d{4}[-/]\d{1,2}[-/]\d{1,2}(?:[ T]?)\d{1,2}[::]\d{2}[)\s]*/, "")
.trim();
}
function extractTimestamp(content) {
return parseTimestampLabel(content);
}
// ========================
// 时间戳记忆库
// ========================
function loadTimestampDB() {
if (!fs.existsSync(TIMESTAMP_DB_FILE)) return {};
try { return fs.readJsonSync(TIMESTAMP_DB_FILE); } catch { return {}; }
}
function saveTimestampDB(db) {
writeJsonAtomicSync(TIMESTAMP_DB_FILE, db);
}
function makeFingerprint(msg) {
const raw = normalizeContentToText(msg.content);
const content = raw.trim().slice(0, 150);
return `${msg.role}::${content}`;
}
function makeFingerprintStripped(msg) {
const raw = normalizeContentToText(msg.content);
const content = stripLeadingTimestamp(raw).slice(0, 150);
return `${msg.role}::${content}`;
}
function extractTimestampWithMemory(msg, tsDB) {
const fromContent = extractTimestamp(normalizeContentToText(msg.content));
if (fromContent) return fromContent;
const fp = makeFingerprint(msg);
if (tsDB[fp]) return new Date(tsDB[fp]);
const fpStripped = makeFingerprintStripped(msg);
if (tsDB[fpStripped]) return new Date(tsDB[fpStripped]);
return null;
}
// ========================
// 消息判断
// ========================
function isSpecialEvent(msg) {
if (msg.role !== "assistant") return false;
return isSpecialEventContent(normalizeContentToText(msg.content));
}
function isRealMessageForTimeline(msg) {
if (msg.role === "system") return false;
if (msg.tool_calls) return false;
if (isSpecialEvent(msg)) return false;
const contentText = normalizeContentToText(msg.content);
if (msg.role === "user" && contentText.trim().startsWith("<system>")) return false;
return msg.role === "user" || msg.role === "assistant";
}
function isSystemRule(msg) {
if (msg.role === "system") return true;
const contentText = normalizeContentToText(msg.content);
if (msg.role === "user" && contentText.trim().startsWith("<system>")) return true;
return false;
}
// ========================
// 构建 Timeline
// ========================
function buildTimeline(kelivoMessages, tsDB) {
const oldTimeline = loadTimeline();
const newSystemMessages = kelivoMessages
.filter(msg => msg.role === "system")
.map(normalizeMessageForTimeline);
const latestSP = newSystemMessages.length > 0 ? newSystemMessages[newSystemMessages.length - 1] : null;
const oldSP = oldTimeline.find(msg => msg.role === "system");
const newRealMessages = kelivoMessages
.filter(isRealMessageForTimeline)
.map(normalizeMessageForTimeline);
const oldSpecialEvents = oldTimeline.filter(isSpecialEvent).sort((a, b) => {
const timeA = extractTimestampWithMemory(a, tsDB);
const timeB = extractTimestampWithMemory(b, tsDB);
if (timeA && timeB) return timeA - timeB;
return 0;
});
const merged = [...newRealMessages];
for (const event of oldSpecialEvents) {
const eventTime = extractTimestampWithMemory(event, tsDB);
if (!eventTime) { merged.push(event); continue; }
let inserted = false;
for (let i = 0; i < merged.length; i++) {
const msgTime = extractTimestampWithMemory(merged[i], tsDB);
if (msgTime && msgTime >= eventTime) {
merged.splice(i, 0, event);
inserted = true;
break;
}
}
if (!inserted) merged.push(event);
}
const seen = new Set();
const unique = merged.filter(msg => {
const key = JSON.stringify({ role: msg.role, content: msg.content });
if (seen.has(key)) return false;
seen.add(key);
return true;
});
const result = [];
if (latestSP) result.push({ ...latestSP, position: 0 });
else if (oldSP) result.push({ ...oldSP, position: 0 });
let realPos = 1;
const finalMessages = [];
let pendingSpecial = [];
for (const msg of unique) {
if (isSpecialEvent(msg)) {
pendingSpecial.push(msg);
} else {
if (pendingSpecial.length > 0) {
const prevRealPos = realPos - 1;
const step = 1 / (pendingSpecial.length + 1);
for (let i = 0; i < pendingSpecial.length; i++) {
finalMessages.push({ ...pendingSpecial[i], position: parseFloat((prevRealPos + step * (i + 1)).toFixed(4)) });
}
pendingSpecial = [];
}
finalMessages.push({ ...msg, position: realPos });
realPos++;
}
}
if (pendingSpecial.length > 0) {
const lastRealPos = realPos - 1;
for (let i = 0; i < pendingSpecial.length; i++) {
finalMessages.push({ ...pendingSpecial[i], position: parseFloat((lastRealPos + 0.3 * (i + 1)).toFixed(4)) });
}
}
result.push(...finalMessages);
return result;
}
// ========================
// 追加特殊事件
// ========================
function appendSpecialEvent(content) {
const timeline = loadTimeline();
let maxPos = 0;
for (const msg of timeline) {
if (msg.position && msg.position > maxPos) maxPos = msg.position;
}
const newEvent = { role: "assistant", content, position: maxPos + 0.5 };
timeline.push(newEvent);
saveTimeline(timeline);
// 批注 2026-07-15:特殊事件可能包含推送正文;日志只记录长度,避免公开部署时泄漏私密内容。
console.log(`\n已记录特殊事件 (position ${newEvent.position}, chars ${normalizeContentToText(content).length})\n`);
}
function stripPosition(messages) {
return messages.map(({ position, ...rest }) => rest);
}
let wakeUpLastHeartbeat = null;
// ========================
// 预设方案
// ========================
const PRESETS_FILE = runtimeFile("presets.json");
// .env 是启动配置而不是运行数据;继续固定在代码目录,Railway 则始终以 Variables 为权威来源。
const ENV_FILE = path.join(PROJECT_DIR, ".env");
const PREFERRED_ENV_ORDER = [
"TARGET_API_URL",
"TARGET_API_KEY",
"GATEWAY_API_KEY",
"MODEL_NAME",
"BARK_KEY",
"CUSTOM_ICON_URL",
"ALLOW_PUBLIC_API",
"PUSH_PROVIDER",
"NTFY_SERVER_URL",
"NTFY_TOPIC",
"NTFY_TOKEN",
"NTFY_PRIORITY",
"NTFY_TAGS",
"DIARY_ENABLED",
"DIARY_DIR",
"DATA_DIR",
"PUSH_TIMEOUT_MS",
"WAKE_UPSTREAM_TIMEOUT_MS",
"REQUEST_BODY_LIMIT_MB",
"MULTIMODAL_MODE",
"DAY_WAKE_AFTER_MINUTES",
"NIGHT_WAKE_AFTER_MINUTES",
"DAY_CHECK_INTERVAL_MINUTES",
"NIGHT_CHECK_INTERVAL_MINUTES",
"WAKE_DAY_START_HOUR",
"WAKE_DAY_END_HOUR",
"WEATHER_ENABLED",
"WEATHER_LOCATION_NAME",
"WEATHER_LAT",
"WEATHER_LON",
"WEATHER_UNITS",
"PORT",
"GATEWAY_BASE_URL",
"TIME_ZONE",
"RESTART_COMMAND",
"ADMIN_USER",
"ADMIN_PASSWORD"
];
function loadPresets() {
if (!fs.existsSync(PRESETS_FILE)) return [];
try { return fs.readJsonSync(PRESETS_FILE); } catch { return []; }
}
function savePresets(presets) {
writeJsonAtomicSync(PRESETS_FILE, presets);
}
function wantsJsonResponse(req) {
const contentType = req.headers["content-type"] || "";
const accept = req.headers.accept || "";
return contentType.includes("application/json") || accept.includes("application/json");
}
function loadEnvFileObject() {
const result = {};
try {
const envContent = fs.readFileSync(ENV_FILE, "utf-8");
for (const line of envContent.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eqIndex = trimmed.indexOf("=");
if (eqIndex <= 0) continue;
const key = trimmed.slice(0, eqIndex).trim();
const value = trimmed.slice(eqIndex + 1).trim();
result[key] = value;
}
} catch {}
return result;
}
function serializeEnvValue(value) {
return String(value ?? "").replace(/\r?\n/g, "\\n");
}
function writeEnvUpdates(updates) {
const merged = { ...loadEnvFileObject(), ...updates };
const orderedKeys = [
...PREFERRED_ENV_ORDER.filter(key => Object.prototype.hasOwnProperty.call(merged, key)),
...Object.keys(merged)
.filter(key => !PREFERRED_ENV_ORDER.includes(key))
.sort()
];
const lines = orderedKeys.map(key => `${key}=${serializeEnvValue(merged[key])}`);
fs.writeFileSync(ENV_FILE, lines.join("\n") + "\n");
}
function readRestartCommand() {
return readEnvValue("RESTART_COMMAND") || DEFAULT_RESTART_COMMAND;
}
// ========================
// 安全:管理页走 Basic Auth,/v1 按公开开关鉴权,内部写接口只允许同进程容器 localhost
// ========================
app.addHook("onRequest", (req, reply, done) => {
const requestPath = req.url.split("?")[0];
const ip = String(req.ip || req.connection.remoteAddress || "");
const headerKey = String(req.headers["x-gateway-api-key"] || req.headers["x-api-key"] || "").trim();
const access = decideRequestAccess({
path: requestPath,
ip,
isRailway: IS_RAILWAY_RUNTIME,
allowPublicApi: readBooleanEnv("ALLOW_PUBLIC_API", false),
configuredKey: readEnvValue("GATEWAY_API_KEY"),
authorization: req.headers.authorization,
headerKey
});
if (access.allow) return done();
if (access.authRejected) {
// 批注 2026-07-30:Kelivo 可能在模型探测或旧预设里继续带错 key;
// 只记路径和 header 类型,帮助排查缓存/重复请求,绝不把任意密钥写入日志。
console.warn(JSON.stringify({
event: "gateway_auth_rejected",
path: requestPath,
auth_source: access.authSource || "missing"
}));
}
reply.code(access.status || 403).send(access.status === 401 ? { error: access.error } : access.error);
});
app.get("/healthz", async () => ({ status: "ok" }));
// ========================
// Models
// ========================
app.get("/v1/models", async (req, reply) => {
reply.send({
object: "list",
data: [{ id: configuredModelName(), object: "model", created: 0, owned_by: "gateway" }]
});
});
// ========================
// Chat Completions
// ========================
app.post("/v1/chat/completions", async (req, reply) => {
try {
const body = req.body;
// 批注 2026-07-15:公开部署时日志不能默认写入完整上下文;
// 这里只保留请求摘要,避免 system prompt、记忆和聊天正文进入 pm2 日志。
console.log(JSON.stringify({
event: "kelivo_request",
model: body?.model || "",
stream: body?.stream === true,
messages: summarizeMessagesForLog(body?.messages || [])
}));
const kelivoMessages = body.messages || [];
const oldTimeline = loadTimeline();
const tsDB = loadTimestampDB();
let tsDBDirty = false;
for (const msg of kelivoMessages) {
if (msg.role === "system") continue;
if (msg.role === "tool") continue;
const ts = extractTimestamp(normalizeContentToText(msg.content));
if (!ts) continue;
const fp = makeFingerprint(msg);
const fpStripped = makeFingerprintStripped(msg);
if (!tsDB[fp]) { tsDB[fp] = ts.toISOString(); tsDBDirty = true; }
if (!tsDB[fpStripped]) { tsDB[fpStripped] = ts.toISOString(); tsDBDirty = true; }
}
if (tsDBDirty) saveTimestampDB(tsDB);
const finalTimeline = buildTimeline(kelivoMessages, tsDB);
saveTimeline(finalTimeline);
// Kelivo 发图时 content 常是数组。默认原样透传给视觉模型;
// 如上游不支持图片,可设置 MULTIMODAL_MODE=text 退回文本占位。
const llmMessages = kelivoMessages
.map(prepareMessageForLLM)
.filter(Boolean);
const oldEvents = stripPosition(
oldTimeline.filter(isSpecialEvent).sort((a, b) => {
const timeA = extractTimestampWithMemory(a, tsDB);
const timeB = extractTimestampWithMemory(b, tsDB);
if (timeA && timeB) return timeA - timeB;
return 0;
})
);
console.log("本次注入的特殊事件数量:", oldEvents.length);
for (const event of oldEvents) {
const eventTime = extractTimestampWithMemory(event, tsDB);
if (!eventTime) { llmMessages.push(event); continue; }
let inserted = false;
for (let i = 0; i < llmMessages.length; i++) {
const msgTime = extractTimestampWithMemory(llmMessages[i], tsDB);
if (msgTime && msgTime >= eventTime) {
llmMessages.splice(i, 0, event);
inserted = true;
break;
}
}
if (!inserted) llmMessages.push(event);
}
console.log(JSON.stringify({
event: "llm_forward_summary",
messages: summarizeMessagesForLog(llmMessages)
}));
// ---- 自动修复不完整的 tool 调用(双向清理) ----
// 第一遍:标记需要移除的索引
const removeSet = new Set();
// 检查 assistant tool_calls 是否完整
for (let i = 0; i < llmMessages.length; i++) {
const msg = llmMessages[i];
if (msg.role !== "assistant" || !msg.tool_calls) continue;
const expectedIds = msg.tool_calls.map(tc => tc.id);
const followingTools = [];
for (let j = i + 1; j < llmMessages.length; j++) {
const nxt = llmMessages[j];
if (nxt.role === "tool") {
followingTools.push(nxt);
} else {
break;
}
}
const foundIds = followingTools.map(t => t.tool_call_id);
const complete = expectedIds.every(id => foundIds.includes(id));
if (!complete) {
// 标记这条 assistant 为移除,同时标记它后面的所有 tool 消息也移除
removeSet.add(i);
for (let j = i + 1; j < llmMessages.length; j++) {
if (llmMessages[j].role === "tool") {
removeSet.add(j);
} else {
break;
}
}
console.log(`⚠️ 自动修复:移除不完整的 tool_calls (索引 ${i})`);
}
}
// 检查孤立 tool 消息(前面没有对应的 tool_calls)
for (let i = 0; i < llmMessages.length; i++) {
if (llmMessages[i].role !== "tool") continue;
// 向前查找最近的 assistant
let hasMatchingToolCalls = false;
for (let j = i - 1; j >= 0; j--) {
const prev = llmMessages[j];
if (prev.role === "assistant" && prev.tool_calls) {
// 检查这个 tool_call_id 是否在 assistant 的 tool_calls 中
const ids = prev.tool_calls.map(tc => tc.id);
if (ids.includes(llmMessages[i].tool_call_id)) {
hasMatchingToolCalls = true;
}
break;
} else if (prev.role === "tool") {
continue; // 继续向前找
} else {
break; // 遇到 user 或其他消息,停止
}
}
if (!hasMatchingToolCalls) {
removeSet.add(i);
console.log(`⚠️ 自动修复:移除孤立的 tool 消息 (索引 ${i})`);
}
}
// 按索引从大到小删除,避免索引错乱
const sortedRemove = Array.from(removeSet).sort((a, b) => b - a);
for (const idx of sortedRemove) {
llmMessages.splice(idx, 1);
}
if (!TARGET_API_URL || !process.env.TARGET_API_KEY) {
return reply.code(500).send({ error: "TARGET_API_URL / TARGET_API_KEY 未配置" });
}
const requestedStream = body?.stream === true;
// 请求模型
const response = await fetch(TARGET_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.TARGET_API_KEY}`
},
body: JSON.stringify({ ...body, messages: llmMessages })
});
const upstreamContentType = response.headers.get("content-type") || "";
const shouldStreamResponse = requestedStream || upstreamContentType.includes("text/event-stream");
// 批注 2026-07-11:Kelivo 关闭 stream 时需要收到普通 JSON;只在请求或上游确认为 SSE 时才按流式直通。
if (!shouldStreamResponse) {
const responseText = await response.text();
return reply
.code(response.status)
.header("Content-Type", upstreamContentType || "application/json")
.send(responseText);
}
if (!response.body) {
return reply.code(response.status).send({ error: "上游 API 没有返回可读取的响应体" });
}
reply.raw.writeHead(response.status, {
"Content-Type": upstreamContentType || "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive"
});
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
reply.raw.write(value);
}
reply.raw.end();
} catch (err) {
console.error(err);
reply.code(500).send({ error: err.message });
}
});
// ========================
// 内部接口:记录唤醒事件
// ========================
app.post("/internal/wake-event", async (req, reply) => {
try {
const { content } = req.body;
if (!content) return reply.code(400).send({ error: "content is required" });
appendSpecialEvent(content);
reply.send({ success: true });
} catch (err) {
console.error(err);
reply.code(500).send({ error: err.message });
}
});
// ========================
// 读取 .env 值
// ========================
function readEnvValue(key) {
// 批注 2026-07-30:Railway Variables 是云端部署的权威配置源;
// 容器内 .env 只作兜底,避免管理页保存出的临时文件覆盖平台变量。
if (IS_RAILWAY_RUNTIME && process.env[key]) return process.env[key];
try {
const envContent = fs.readFileSync(ENV_FILE, "utf-8");
const lines = envContent.split("\n");
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith(key + "=")) return trimmed.substring(key.length + 1).trim();
}
} catch {}
return process.env[key] || "";
}
function readEnvValueOrDefault(key, fallback) {
const value = readEnvValue(key);
return value === "" ? fallback : value;
}
function normalizePositiveInteger(value, key, fallback) {
const n = Number(value);
if (Number.isFinite(n) && n >= 1) return String(Math.floor(n));
return readEnvValueOrDefault(key, fallback);
}
function normalizeHour(value, key, fallback, min, max) {
const n = Number(value);
if (Number.isFinite(n) && n >= min && n <= max) return String(Math.floor(n));
return readEnvValueOrDefault(key, fallback);
}
function normalizeBooleanString(value, key, fallback) {
const raw = String(value ?? "").trim().toLowerCase();
if (["true", "1", "yes", "on"].includes(raw)) return "true";
if (["false", "0", "no", "off"].includes(raw)) return "false";
return readEnvValueOrDefault(key, fallback);
}
function normalizeWeatherUnits(value) {
return String(value || "").trim().toLowerCase() === "fahrenheit" ? "fahrenheit" : "metric";
}
function diaryDirectoryPath() {
const configured = readEnvValueOrDefault("DIARY_DIR", "diary");
return runtimeDirectory(configured, "diary");
}
function readDiaryEntries(limit = 20) {
const dir = diaryDirectoryPath();
try {
if (!fs.existsSync(dir)) return [];
// 批注 2026-07-15:管理页只读展示 wake-up 生成的本地日记;
// 只读取 DIARY_DIR 下的 .md 文件,避免把任意路径内容暴露到 admin 页面。
return fs.readdirSync(dir)
.filter(name => /^[^/\\]+\.md$/i.test(name))
.sort((a, b) => b.localeCompare(a))
.slice(0, limit)
.map(name => {
const filePath = path.join(dir, name);
const stat = fs.statSync(filePath);
const content = fs.readFileSync(filePath, "utf-8").slice(0, 24000);
return { name, updated_at: stat.mtime.toISOString(), content };
});
} catch (err) {
return [{ name: "读取日记失败", updated_at: new Date().toISOString(), content: err.message || String(err) }];
}
}
// ========================
// HTTP Basic Auth
// ========================
function basicAuth(req, reply, done) {
const auth = req.headers.authorization || "";
const [scheme, encoded] = auth.split(" ");
if (scheme !== "Basic" || !encoded) {
reply.code(401).header("WWW-Authenticate", 'Basic realm="Admin"').send("Unauthorized");
return;
}
const decoded = Buffer.from(encoded, "base64").toString();
const colonIndex = decoded.indexOf(":");
const user = decoded.substring(0, colonIndex);
const password = decoded.substring(colonIndex + 1);
if (user === process.env.ADMIN_USER && password === process.env.ADMIN_PASSWORD) {
done();
} else {
reply.code(401).header("WWW-Authenticate", 'Basic realm="Admin"').send("Unauthorized");
}
}
// ========================
// 管理页面 GET /admin
// ========================
app.get("/admin", { preHandler: basicAuth }, async (req, reply) => {
const serverUptime = Math.floor(process.uptime());
const wakeUpStatus = wakeUpLastHeartbeat
? `在线(上次心跳: ${formatDateTimeInTimeZone(new Date(wakeUpLastHeartbeat), TIME_ZONE)})`
: "离线或未启动";
const currentUrl = readEnvValue("TARGET_API_URL");
const currentModel = readEnvValue("MODEL_NAME");
const currentIcon = readEnvValue("CUSTOM_ICON_URL");
const gatewayKeyStatus = readEnvValue("GATEWAY_API_KEY") ? "已配置" : "未配置";
const wakeConfig = {
dayWakeAfter: readEnvValueOrDefault("DAY_WAKE_AFTER_MINUTES", "60"),
nightWakeAfter: readEnvValueOrDefault("NIGHT_WAKE_AFTER_MINUTES", "120"),
dayCheckInterval: readEnvValueOrDefault("DAY_CHECK_INTERVAL_MINUTES", "10"),
nightCheckInterval: readEnvValueOrDefault("NIGHT_CHECK_INTERVAL_MINUTES", "120"),
dayStartHour: readEnvValueOrDefault("WAKE_DAY_START_HOUR", "10"),
dayEndHour: readEnvValueOrDefault("WAKE_DAY_END_HOUR", "24")
};
const weatherConfig = {
enabled: readEnvValueOrDefault("WEATHER_ENABLED", "false"),
locationName: readEnvValue("WEATHER_LOCATION_NAME"),
lat: readEnvValue("WEATHER_LAT"),
lon: readEnvValue("WEATHER_LON"),
units: readEnvValueOrDefault("WEATHER_UNITS", "metric")
};
const diaryEntries = readDiaryEntries(20);
const diaryHtml = diaryEntries.length
? diaryEntries.map(entry => `
<details class="diary-entry">
<summary>
<span>${escapeHtml(entry.name)}</span>
<em>${escapeHtml(formatDateTimeInTimeZone(new Date(entry.updated_at), TIME_ZONE))}</em>
</summary>
<pre>${escapeHtml(entry.content)}</pre>
</details>
`).join("")
: `<div class="diary-empty">还没有日记。模型在 wake-up 回复里输出 [DIARY]...[/DIARY] 后会保存到这里。</div>`;
const authToken = Buffer.from(`${process.env.ADMIN_USER}:${process.env.ADMIN_PASSWORD}`).toString("base64");
const runtimeConfigNotice = IS_RAILWAY_RUNTIME
? `<div class="hint">Railway 检测到:此页面保存的是当前容器的 .env。Railway Variables 会优先提供运行时配置,且未挂载 Volume 的文件会在重新部署后丢失;请在 Railway Variables 修改唤醒数值并重新部署。</div>`
: "";
const presets = loadPresets();
const presetsJson = safeJsonForInlineScript(presets);
const authHeaderJson = safeJsonForInlineScript(`Basic ${authToken}`);
const html = `<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HEARTBEAT · Runtime</title>
<!-- 引入思源宋体 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;600;700&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: "Noto Serif SC", Georgia, "Times New Roman", serif;
background: linear-gradient(135deg, #f8f0f3 0%, #f5e6eb 100%);
background-image:
radial-gradient(circle at 20% 80%, rgba(230, 190, 200, 0.15) 0%, transparent 50%),
radial-gradient(circle at 80% 20%, rgba(210, 170, 180, 0.1) 0%, transparent 50%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 30px 20px;
}
.container {
max-width: 480px;
width: 100%;
background: rgba(255, 255, 255, 0.75);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-radius: 24px;
padding: 40px 32px;
box-shadow:
0 2px 10px rgba(180, 120, 130, 0.05),
0 15px 40px rgba(180, 120, 130, 0.15),
0 0 0 1px rgba(255, 255, 255, 0.8) inset;
transition: all 0.4s ease;
}
.container:hover {
box-shadow:
0 2px 10px rgba(180, 120, 130, 0.08),
0 20px 50px rgba(180, 120, 130, 0.2),
0 0 0 1px rgba(255, 255, 255, 0.9) inset;
}
h2 {
text-align: center;
font-size: 32px;
font-weight: 700;
color: #8a4a58;
margin-bottom: 4px;
letter-spacing: 6px;
font-family: "Times New Roman", "Georgia", "Noto Serif SC", serif;
font-style: normal;
text-transform: uppercase;
}
.subtitle {
text-align: center;
font-size: 12px;
color: #a87a85;
margin-bottom: 32px;
letter-spacing: 4px;
text-transform: uppercase;
font-style: italic;
opacity: 0.85;
}
.status {
background: rgba(255, 250, 252, 0.6);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border-radius: 14px;
padding: 16px 20px;
margin-bottom: 24px;
border: 1px solid rgba(230, 200, 208, 0.4);
}
.status p {
margin: 6px 0;
font-size: 13px;
color: #6d5057;
font-weight: 400;
line-height: 1.5;
text-transform: uppercase;
letter-spacing: 1px;
}
.status strong {
color: #8a4a58;
font-weight: 600;
letter-spacing: 0.5px;
}