-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbindEvents_debug.txt
More file actions
1726 lines (1523 loc) · 67.7 KB
/
bindEvents_debug.txt
File metadata and controls
1726 lines (1523 loc) · 67.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
const state = {
currentView: "overview",
modelsHash: "",
modelProviderSnapshots: {},
providerModalOpen: false,
logsCursor: null,
logsTimer: null,
logsLive: false,
systemTimer: null,
overviewTimer: null,
nodeCommandDefaults: [],
modelDefaultOptions: [],
cronJsonMode: false
};
// =========================================
// Spotlight 交互与全局光照
// =========================================
document.addEventListener("mousemove", (e) => {
const spotlights = document.querySelectorAll("[data-spotlight]");
for (const el of spotlights) {
const rect = el.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
let lens = el.querySelector(".spotlight-lens");
if (!lens) {
lens = document.createElement("div");
lens.className = "spotlight-lens";
el.appendChild(lens);
}
lens.style.background = `radial-gradient(circle at ${x}px ${y}px, rgba(255, 255, 255, 0.08) 0%, transparent 60%)`;
}
});
const viewLoaders = {
overview: loadOverview,
models: loadModels,
skills: loadSkills,
cron: loadCron,
nodes: loadNodes,
logs: initLogsView
};
function $(id) {
return document.getElementById(id);
}
async function api(path, options = {}) {
const token = localStorage.getItem("openclaw_token");
const mergedHeaders = {
"Content-Type": "application/json",
...(options.headers || {})
};
if (token) {
mergedHeaders["Authorization"] = `Bearer ${token}`;
}
const res = await fetch(path, {
...options,
headers: mergedHeaders
});
const data = await res.json().catch(() => ({}));
if (res.status === 401) {
localStorage.removeItem("openclaw_token");
window.location.href = "/login.html";
return;
}
if (!res.ok || data.ok === false) {
throw new Error(data.error || `request failed (${res.status})`);
}
return data;
}
// Blog Admin Toast Implementation
function showToast(message, type = 'info', duration = 3000) {
const container = document.getElementById('toast-container');
if (!container) return;
const toast = document.createElement('div');
toast.className = `toast ${type}`;
let iconClass = 'fa-solid fa-circle-info';
let title = '系统通知';
if (type === 'success') {
iconClass = 'fa-solid fa-check';
title = '操作成功';
} else if (type === 'error') {
iconClass = 'fa-solid fa-xmark';
title = '操作失败';
} else if (type === 'warning') {
iconClass = 'fa-solid fa-exclamation';
title = '警告';
}
toast.innerHTML = `
<div class="toast-icon">
<i class="${iconClass}"></i>
</div>
<div class="toast-content">
<div class="toast-title">${title}</div>
<div class="toast-message">${escapeHtml(message)}</div>
</div>
<button class="toast-close"><i class="fa-solid fa-xmark"></i></button>
`;
container.appendChild(toast);
// Close button event
const closeBtn = toast.querySelector('.toast-close');
closeBtn.addEventListener('click', () => {
removeToast(toast);
});
// Auto remove
if (duration > 0) {
setTimeout(() => {
removeToast(toast);
}, duration);
}
}
function removeToast(toast) {
if (toast.classList.contains('toast-exit')) return;
toast.classList.add('toast-exit');
toast.addEventListener('animationend', () => {
toast.remove();
});
}
function showError(targetId, err) {
const el = $(targetId);
if (!el) return;
el.textContent = `Error: ${err instanceof Error ? err.message : String(err)}`;
}
function renderTable(columns, rows) {
const thCells = columns
.map((c) => {
const cls = c.className ? ` class="${c.className}"` : "";
const align = c.align ? ` style="text-align:${c.align};"` : "";
return `<th${cls}${align}>${c.title}</th>`;
})
.join("");
const trRows = rows
.map((row) => {
const tdCells = columns
.map((c) => {
const cls = c.className ? ` class="${c.className}"` : "";
const align = c.align ? ` style="text-align:${c.align};"` : "";
return `<td${cls}${align}>${c.render(row)}</td>`;
})
.join("");
return `<tr>${tdCells}</tr>`;
})
.join("");
return `<div class="table-wrap"><table><thead><tr>${thCells}</tr></thead><tbody>${trRows}</tbody></table></div>`;
}
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getLogLevel(line) {
const text = String(line || "");
if (/\b(error|failed|failure|exception|fatal|panic|denied)\b/i.test(text)) return "error";
if (/\b(warn|warning|deprecated|retry)\b/i.test(text)) return "warn";
if (/\b(info|connected|started|success|ready)\b/i.test(text)) return "info";
return "default";
}
function highlightLogKeyword(line, keyword) {
const source = String(line || "");
if (!keyword) return escapeHtml(source);
const pattern = new RegExp(escapeRegExp(keyword), "gi");
let result = "";
let cursor = 0;
let match = pattern.exec(source);
while (match !== null) {
result += escapeHtml(source.slice(cursor, match.index));
result += `<mark class="log-highlight">${escapeHtml(match[0])}</mark>`;
cursor = match.index + match[0].length;
if (match[0].length === 0) break;
match = pattern.exec(source);
}
result += escapeHtml(source.slice(cursor));
return result;
}
function renderLogLine(line, keyword) {
const level = getLogLevel(line);
return `<span class="log-line log-${level}">${highlightLogKeyword(line, keyword)}</span>`;
}
function appendLogLines(lines, keyword) {
const output = $("logs-output");
if (!output || lines.length === 0) return;
const html = lines.map((line) => renderLogLine(line, keyword)).join("\n");
if (output.innerHTML) output.insertAdjacentText("beforeend", "\n");
output.insertAdjacentHTML("beforeend", html);
output.scrollTop = output.scrollHeight;
}
// Safe arithmetic expression evaluator (numbers, + - * /, parentheses, whitespace only)
function evaluateArithmetic(expr) {
const s = String(expr || '').replace(/\s/g, '');
if (!s) return 0;
if (!/^[0-9+\-*/().]+$/.test(s)) {
throw new Error('Invalid expression');
}
let pos = 0;
function parseExpression() {
let value = parseTerm();
while (pos < s.length) {
const char = s[pos];
if (char === '+') { pos++; value += parseTerm(); }
else if (char === '-') { pos++; value -= parseTerm(); }
else break;
}
return value;
}
function parseTerm() {
let value = parseFactor();
while (pos < s.length) {
const char = s[pos];
if (char === '*') { pos++; value *= parseFactor(); }
else if (char === '/') {
pos++;
const divisor = parseFactor();
if (divisor === 0) throw new Error('Division by zero');
value /= divisor;
} else break;
}
return value;
}
function parseFactor() {
if (pos >= s.length) throw new Error('Unexpected end');
const char = s[pos];
if (char === '(') {
pos++;
const value = parseExpression();
if (pos >= s.length || s[pos] !== ')') throw new Error('Missing closing parenthesis');
pos++;
return value;
}
const start = pos;
let hasDecimal = false;
while (pos < s.length) {
const c = s[pos];
if (c >= '0' && c <= '9') pos++;
else if (c === '.' && !hasDecimal) { hasDecimal = true; pos++; }
else break;
}
if (start === pos) throw new Error('Expected number');
const num = parseFloat(s.substring(start, pos));
if (isNaN(num)) throw new Error('Invalid number');
return num;
}
const result = parseExpression();
if (pos < s.length) throw new Error('Unexpected character');
return Math.round(result);
}
function setView(view) {
state.currentView = view;
for (const section of document.querySelectorAll(".view")) {
section.classList.toggle("active", section.id === `view-${view}`);
}
for (const item of document.querySelectorAll("#nav-menu .nav-item")) {
item.classList.toggle("active", item.dataset.view === view);
}
const load = viewLoaders[view];
if (load) load();
if (view === "overview") {
loadSystemLoad();
startOverviewTimers();
} else {
stopOverviewTimers();
}
if (view === "logs") {
startLogStream();
} else {
stopLogStream();
}
}
async function refreshCurrentView() {
const load = viewLoaders[state.currentView];
if (load) await load();
}
async function loadHealth() {
try {
const health = await api("/api/health");
const modeRaw = String(health?.gateway?.authMode || "unknown").toLowerCase();
const modeMap = {
token: "令牌",
password: "密码",
none: "无",
unknown: "未知"
};
const mode = modeMap[modeRaw] || modeRaw;
$("health-pill").textContent = `认证模式:${mode}`;
} catch (err) {
$("health-pill").textContent = "网关离线";
console.error(err);
}
}
function setPerfValue(valueId, percent) {
const safePercent = Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : 0;
const valueEl = $(valueId);
if (valueEl) valueEl.textContent = `${safePercent.toFixed(1)}%`;
}
async function loadSystemLoad() {
try {
const data = await api("/api/system-load");
const cpu = data?.system?.cpu || {};
const memory = data?.system?.memory || {};
const cpuPercent = Number.isFinite(cpu.usagePercent) ? cpu.usagePercent : cpu.normalizedLoadPercent || 0;
setPerfValue("cpu-value", cpuPercent);
const memPercent = Number(memory.usagePercent || 0);
setPerfValue("mem-value", memPercent);
} catch (err) {
setPerfValue("cpu-value", 0);
setPerfValue("mem-value", 0);
console.error(err);
}
}
function startOverviewTimers() {
if (!state.systemTimer) {
state.systemTimer = setInterval(() => {
if (state.currentView === "overview") loadSystemLoad();
}, 5000);
}
if (!state.overviewTimer) {
state.overviewTimer = setInterval(() => {
if (state.currentView === "overview") loadOverview();
}, 30000);
}
}
function stopOverviewTimers() {
if (state.systemTimer) {
clearInterval(state.systemTimer);
state.systemTimer = null;
}
if (state.overviewTimer) {
clearInterval(state.overviewTimer);
state.overviewTimer = null;
}
}
function renderEmpty(icon, title, subtitle) {
return `
<div class="empty-placeholder">
<div class="empty-icon"><i class="${icon}"></i></div>
<div style="font-size: 1.1rem; color: var(--text-secondary); font-weight: 500;">${title}</div>
<div style="font-size: 0.9rem; margin-top: 8px;">${subtitle}</div>
</div>
`;
}
function renderSkeleton(rows = 3) {
let lines = "";
for (let i = 0; i < rows; i++) {
lines += `<div class="skeleton-text" style="width: ${80 + Math.random() * 20}%"></div>`;
}
return `<div style="padding: 20px;">${lines}</div>`;
}
async function loadOverview() {
const container = $("overview-content");
container.innerHTML = renderSkeleton(5);
try {
const data = await api("/api/overview");
const channels = data.channels?.channels || {};
const channelValues = Object.values(channels);
if (channelValues.length === 0 && (data.sessions?.sessions || []).length === 0) {
container.innerHTML = renderEmpty("fa-solid fa-wind", "暂无活跃数据", "阿洛娜还没发现任何会话或频道记录呢~");
return;
}
const connectedChannels = channelValues.filter((entry) => entry?.connected).length;
const sessions = data.sessions?.sessions || [];
const cronJobs = data.cronList?.jobs || [];
const nodeList = data.nodes?.nodes || [];
const nodeOnline = nodeList.filter((node) => node.connected).length;
const errors = (data.logs?.lines || []).filter((line) => /error|failed|denied/i.test(line));
const metrics = [
{ label: "活跃会话", value: sessions.length, icon: "fa-regular fa-comments", color: "#64b5f6" },
{ label: "计划任务", value: cronJobs.filter((j) => j.enabled).length, icon: "fa-regular fa-clock", color: "#81c784" },
{ label: "在线节点", value: `${nodeOnline}/${nodeList.length}`, icon: "fa-solid fa-server", color: "#fff176" },
{ label: "最近异常", value: errors.length, icon: "fa-solid fa-triangle-exclamation", color: "#e57373" }
];
const statsHtml = metrics.map(m => `
<div class="stat-card" style="display: flex; align-items: center; justify-content: flex-start; gap: 16px; padding: 20px 24px;">
<div style="width: 48px; height: 48px; border-radius: 14px; background: rgba(128, 128, 128, 0.15); display: flex; align-items: center; justify-content: center;">
<i class="${m.icon}" style="color: ${m.color}; font-size: 1.6rem;"></i>
</div>
<div style="display: flex; flex-direction: column; align-items: flex-start;">
<div class="stat-label" style="font-size: 0.85rem; text-transform: uppercase; letter-spacing: 1px; color: var(--text-muted); margin-bottom: 4px;">${m.label}</div>
<div class="stat-value" style="font-size: 1.8rem; font-weight: 600; line-height: 1; color: var(--text-primary);">${m.value}</div>
</div>
</div>
`).join("");
const sessionsHtml = sessions.slice(0, 10).map((r) => {
return `
<div style="padding: 12px 16px; border-bottom: 1px solid var(--border-default); display: flex; flex-direction: column; gap: 8px;">
<div style="display: flex; justify-content: space-between; align-items: flex-start;">
<strong style="word-break: break-all; font-size: 0.95rem; color: var(--foreground); font-weight: 500;">${escapeHtml(r.label || r.displayName || r.key)}</strong>
<span style="color: var(--foreground-muted); white-space: nowrap; font-size: 0.8rem;"><i class="fa-regular fa-clock" style="margin-right: 4px;"></i>${r.updatedAt ? new Date(r.updatedAt).toLocaleTimeString() : "-"}</span>
</div>
<div>
<span class="status-badge" style="background: rgba(94, 106, 210, 0.15); border: 1px solid rgba(94, 106, 210, 0.3); color: var(--accent); white-space: nowrap; padding: 4px 10px; border-radius: 6px; font-size: 0.75rem;"><i class="fa-solid fa-microchip" style="margin-right: 6px;"></i>${escapeHtml(r.model || "-")}</span>
</div>
</div>
`;
}).join("");
const channelAccounts = data.channels?.channelAccounts || {};
const channelRows = Object.entries(channels).map(([name, ch]) => {
const accounts = Array.isArray(channelAccounts[name]) ? channelAccounts[name] : [];
const hasConnected = ch?.connected === true || accounts.some((acc) => acc?.connected === true);
const hasRunning = ch?.running === true || accounts.some((acc) => acc?.running === true);
const configured = ch?.configured === true;
let stateLabel = "离线";
let statusColor = "var(--warning)";
let statusBg = "rgba(251, 191, 36, 0.15)";
let statusBorder = "rgba(251, 191, 36, 0.3)";
if (!configured) {
stateLabel = "未配置";
statusColor = "var(--danger)";
statusBg = "rgba(239, 68, 68, 0.15)";
statusBorder = "rgba(239, 68, 68, 0.3)";
} else if (hasConnected) {
stateLabel = "已连接";
statusColor = "var(--success)";
statusBg = "rgba(16, 185, 129, 0.15)";
statusBorder = "rgba(16, 185, 129, 0.3)";
} else if (hasRunning) {
stateLabel = "运行中";
statusColor = "var(--success)";
statusBg = "rgba(16, 185, 129, 0.15)";
statusBorder = "rgba(16, 185, 129, 0.3)";
}
const detail = ch?.lastError || ch?.mode || (hasRunning ? "服务已启动" : "等待启动");
return { name, detail, stateLabel, statusColor, statusBg, statusBorder };
});
const channelHtml = channelRows.map((r) => {
return `
<div style="padding: 12px 16px; border-bottom: 1px solid var(--border-default); display: flex; flex-direction: column; gap: 8px;">
<div style="display: flex; justify-content: space-between; align-items: center;">
<strong style="white-space: nowrap; font-size: 0.95rem; color: var(--foreground); font-weight: 500;">${escapeHtml(r.name)}</strong>
<span style="color: ${r.statusColor}; background: ${r.statusBg}; border: 1px solid ${r.statusBorder}; padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 600; white-space: nowrap;">${r.stateLabel}</span>
</div>
<div>
<span style="color: var(--foreground-muted); font-size: 0.85rem; word-break: break-all;">${escapeHtml(r.detail || "-")}</span>
</div>
</div>
`;
}).join("");
container.innerHTML = `
<div class="dashboard-grid" style="gap: 24px; margin-bottom: 35px;">${statsHtml}</div>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 24px;">
<div class="glass-panel" data-spotlight style="margin-bottom: 0; display: flex; flex-direction: column;">
<div class="panel-header" style="border-bottom: 1px solid var(--border-default);"><span class="panel-title" style="color: var(--foreground);"><i class="fa-solid fa-list-ul" style="color: var(--accent); margin-right: 10px;"></i>最近活跃会话</span></div>
<div style="flex: 1; overflow-y: auto;">
${sessionsHtml || '<div style="padding: 24px; text-align: center; color: var(--foreground-muted); font-size: 0.9rem;">暂无活跃会话</div>'}
</div>
</div>
<div class="glass-panel" data-spotlight style="margin-bottom: 0; display: flex; flex-direction: column;">
<div class="panel-header" style="border-bottom: 1px solid var(--border-default);"><span class="panel-title" style="color: var(--foreground);"><i class="fa-solid fa-network-wired" style="color: var(--warning); margin-right: 10px;"></i>频道状态快照</span></div>
<div style="flex: 1; overflow-y: auto;">
${channelHtml || '<div style="padding: 24px; text-align: center; color: var(--foreground-muted); font-size: 0.9rem;">暂无频道数据</div>'}
</div>
</div>
</div>
`;
} catch (err) {
container.innerHTML = `<div class="glass-panel" style="padding: 20px; color: var(--danger)">${escapeHtml(err.message)}</div>`;
}
}
// (别名和默认模型相关控制已被移除)
function cloneProviderConfig(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
try {
return JSON.parse(JSON.stringify(value));
} catch {
return {};
}
}
function normalizeProviderEditorData(provider) {
const source = provider && typeof provider === "object" && !Array.isArray(provider) ? provider : {};
const modelsValue = Object.prototype.hasOwnProperty.call(source, "models") ? source.models : [];
return {
baseUrl:
(typeof source.baseUrl === "string" && source.baseUrl) ||
(typeof source.baseURL === "string" && source.baseURL) ||
(typeof source.url === "string" && source.url) ||
"",
apiKey: (typeof source.apiKey === "string" && source.apiKey) || "",
apiType:
(typeof source.apiType === "string" && source.apiType) ||
(typeof source.type === "string" && source.type) ||
"openai",
modelRows: normalizeProviderModels(modelsValue)
};
}
function normalizeProviderModelRow(entry, fallbackId = "") {
if (typeof entry === "string") {
return {
id: entry,
contextWindow: "",
reasoning: false,
input: "",
extras: {}
};
}
const source = entry && typeof entry === "object" && !Array.isArray(entry) ? cloneProviderConfig(entry) : {};
const id =
(typeof source.id === "string" && source.id) ||
(typeof source.model === "string" && source.model) ||
fallbackId ||
"";
let contextWindow = "";
if (source.contextWindow !== null && source.contextWindow !== undefined && source.contextWindow !== "") {
const parsedWindow = Number(source.contextWindow);
if (Number.isFinite(parsedWindow) && parsedWindow > 0) {
contextWindow = String(Math.trunc(parsedWindow));
}
}
const reasoning = source.reasoning === true;
const input = Array.isArray(source.input)
? source.input.map((value) => String(value).trim()).filter(Boolean).join(", ")
: "";
delete source.id;
delete source.model;
delete source.contextWindow;
delete source.reasoning;
delete source.input;
return {
id,
contextWindow,
reasoning,
input,
extras: source
};
}
// 常用提供商 SVG Icon (来自 simple-icons 白底版本) 及统一默认黑金质感配色
const DEFAULT_BRAND_COLOR = "#a3a8b4";
const SVG_ICONS = {
openai: `<svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor"><path d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0462 6.0462 0 0 0 5.45-3.1818 5.9847 5.9847 0 0 0 3.998-2.9 6.0462 6.0462 0 0 0-.426-7.0971zM14.224 22.7508a4.4256 4.4256 0 0 1-2.876-1.04l.1417-.08v-7.625l-2.0916-1.205v-5.91l4.8258 2.7668v13.1118zM6.9234 19.9822a4.4256 4.4256 0 0 1-.5157-3.0248l.1417.08 6.6415 3.823 2.0911 1.205-3.0247 5.234a4.4256 4.4256 0 0 1-5.3339-7.3172zm-4.3228-5.3217a4.4256 4.4256 0 0 1 2.3603-1.9848v7.625l2.0916 1.205 2.8851-4.9975-4.8256-2.7668v-12.193a4.4256 4.4256 0 0 1-2.5114 13.1121zm1.7513-10.02a4.4256 4.4256 0 0 1 2.876 1.04l-.1417.08v7.625L5.0041 12.001A4.4256 4.4256 0 0 1 9.778 2.6405zm10.4252.1815a4.4256 4.4256 0 0 1 .5157 3.0248l-.1417-.08-6.6415-3.823-2.0911-1.205 3.0247-5.234a4.4256 4.4256 0 0 1 5.3339 7.3172zm4.3228 5.3217a4.4256 4.4256 0 0 1-2.3603 1.9848v-7.625l-2.0916-1.205-2.8851 4.9975 4.8256 2.7668v12.193a4.4256 4.4256 0 0 1 2.5114-13.1121z"/></svg>`,
anthropic: `<svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 3L11.8 13.3L8 6H6.1L10.8 14.5L9.6 16.7L1.8 2.6H0L8.7 18.2L9.6 19.8L20 1H17.5M16.9 11.2L12.7 18.8H18L22.2 11.2H16.9Z"/></svg>`,
google: `<svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor"><path d="M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z"/></svg>`
};
const PROVIDER_BRANDS = {
openai: { color: DEFAULT_BRAND_COLOR, isSvg: true, icon: SVG_ICONS.openai, name: "OpenAI" },
anthropic: { color: DEFAULT_BRAND_COLOR, isSvg: true, icon: SVG_ICONS.anthropic, name: "Anthropic" },
google: { color: DEFAULT_BRAND_COLOR, isSvg: true, icon: SVG_ICONS.google, name: "Google" },
gemini: { color: DEFAULT_BRAND_COLOR, isSvg: true, icon: SVG_ICONS.google, name: "Gemini" },
deepseek: { color: DEFAULT_BRAND_COLOR, isSvg: false, icon: "fa-solid fa-wave-square", name: "DeepSeek" },
openrouter: { color: DEFAULT_BRAND_COLOR, isSvg: false, icon: "fa-solid fa-route", name: "OpenRouter" },
qwen: { color: DEFAULT_BRAND_COLOR, isSvg: false, icon: "fa-solid fa-brain", name: "Qwen" },
ollama: { color: DEFAULT_BRAND_COLOR, isSvg: false, icon: "fa-brands fa-kickstarter-k", name: "Ollama" },
siliconflow: { color: DEFAULT_BRAND_COLOR, isSvg: false, icon: "fa-solid fa-microchip", name: "SiliconFlow" },
custom: { color: DEFAULT_BRAND_COLOR, isSvg: false, icon: "fa-solid fa-server", name: "提供商" }
};
function getProviderBrand(key, rawType) {
const typeKey = (rawType || "").toLowerCase();
const k = (key || "").toLowerCase();
// 1. 优先尝试直接名称包含的品牌匹配(因为 key 通常是用户的命名,具有直接指导意义)
for (const [brandKey, bObj] of Object.entries(PROVIDER_BRANDS)) {
if (brandKey !== 'custom' && k.includes(brandKey)) {
return { ...bObj };
}
}
// 2. 如果名称没匹配上,再看他的底层驱动引擎是否为已知的官方大厂(但必须排除 openai,因为许多第三方 API 中转站也用 openai 类型)
if (typeKey && typeKey !== 'openai' && PROVIDER_BRANDS[typeKey]) {
return { ...PROVIDER_BRANDS[typeKey] };
}
// 完全抹去自定义商和 newapi 的越权显示,全面统一为默认的黑灰金质感 + `fa-server` 图标
return { ...PROVIDER_BRANDS.custom };
}
function normalizeProviderModels(modelsValue, ensureOne = true) {
const rows = [];
if (Array.isArray(modelsValue)) {
for (const item of modelsValue) {
rows.push(normalizeProviderModelRow(item));
}
} else if (modelsValue && typeof modelsValue === "object") {
for (const [key, value] of Object.entries(modelsValue)) {
if (value && typeof value === "object" && !Array.isArray(value)) {
const objectValue = cloneProviderConfig(value);
if (!objectValue.id && !objectValue.model) objectValue.id = key;
rows.push(normalizeProviderModelRow(objectValue, key));
} else {
rows.push(normalizeProviderModelRow(key, key));
}
}
}
if (ensureOne && rows.length === 0) rows.push(normalizeProviderModelRow(""));
return rows;
}
function providerModelRowTemplate(rowData = {}) {
const row = {
id: rowData.id || "",
contextWindow: rowData.contextWindow || "",
reasoning: rowData.reasoning === true,
input: rowData.input || "",
extras: rowData.extras && typeof rowData.extras === "object" && !Array.isArray(rowData.extras) ? rowData.extras : {}
};
return `
<div class="provider-model-row" data-provider-model-row>
<input type="text" class="provider-model-id" placeholder="模型 ID(如 gpt-4o-mini)" value="${escapeHtml(row.id)}" />
<input type="number" min="1" step="1" class="provider-model-context" placeholder="上下文窗口" value="${escapeHtml(row.contextWindow)}" />
<label class="provider-model-reasoning">
<input type="checkbox" class="provider-model-reasoning-toggle" ${row.reasoning ? "checked" : ""} />
推理
</label>
<input type="text" class="provider-model-input" placeholder="输入类型(逗号分隔,可留空)" value="${escapeHtml(row.input)}" />
<input type="hidden" class="provider-model-extras" value="${escapeHtml(JSON.stringify(row.extras))}" />
<button type="button" class="provider-model-remove" data-provider-model-remove title="移除模型" aria-label="移除模型">
<i class="fa-solid fa-minus"></i>
</button>
</div>
`;
}
function providerCardTemplate(providerKey = "", provider = {}, originalKey = "") {
const info = normalizeProviderEditorData(provider);
const apiTypeOptions = ["openai", "anthropic", "azure-openai", "gemini", "custom"];
if (info.apiType && !apiTypeOptions.includes(info.apiType)) {
apiTypeOptions.unshift(info.apiType);
}
const optionsHtml = apiTypeOptions
.map((type) => `<option value="${type}"${type === info.apiType ? " selected" : ""}>${type}</option>`)
.join("");
const modelRowsHtml = info.modelRows.map((row) => providerModelRowTemplate(row)).join("");
// 提取提供商级别的额外 JSON 配置(如 temperature, 等等)
const providerExtraInfo = cloneProviderConfig(provider);
delete providerExtraInfo.baseUrl;
delete providerExtraInfo.baseURL;
delete providerExtraInfo.url;
delete providerExtraInfo.apiKey;
delete providerExtraInfo.apiType;
delete providerExtraInfo.type;
delete providerExtraInfo.models;
const initialJsonStr = Object.keys(providerExtraInfo).length > 0 ? JSON.stringify(providerExtraInfo, null, 2) : "";
const brand = getProviderBrand(providerKey, info.apiType);
const iconHTML = brand.isSvg ? brand.icon : `<i class="${brand.icon}"></i>`;
return `
<article class="provider-edit-card" data-provider-card data-original-key="${escapeHtml(originalKey)}">
<div class="provider-card-head" style="margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between;">
<div class="provider-card-title"><span style="display:inline-flex; width:22px; height:22px; justify-content:center; align-items:center; margin-right:8px; color:var(--accent);">${iconHTML}</span><span style="font-weight:600;">Provider 配置块</span></div>
<button type="button" class="provider-card-remove panel-action-btn" data-provider-remove title="删除 Provider" aria-label="删除 Provider" style="border-color: rgba(239, 68, 68, 0.3); color: #ef4444;">
<i class="fa-regular fa-trash-can"></i> 删除
</button>
</div>
<div class="provider-card-grid skeuo-input-group" style="gap:16px;">
<div class="config-row" style="margin:0;">
<label>Provider Key (唯一标识)</label>
<input type="text" class="provider-key skeuo-input" placeholder="如 openrouter" value="${escapeHtml(providerKey)}" />
</div>
<div class="config-row" style="margin:0;">
<label>Base URL</label>
<input type="text" class="provider-base-url skeuo-input" placeholder="https://openrouter.ai/api/v1 (可为空)" value="${escapeHtml(info.baseUrl)}" />
</div>
<div class="config-row" style="margin:0;">
<label>API Key</label>
<div class="provider-secret-wrap" style="position:relative; width: 100%;">
<input type="password" class="provider-api-key skeuo-input" placeholder="sk-..." autocomplete="off" value="${escapeHtml(info.apiKey)}" style="padding-right: 40px;" />
<button type="button" class="provider-secret-toggle" data-secret-toggle aria-label="显示 API Key" title="显示 API Key" style="position:absolute; right:10px; top:50%; transform:translateY(-50%); background:none; border:none; color:var(--text-muted); cursor:pointer;">
<i class="fa-regular fa-eye"></i>
</button>
</div>
</div>
<div class="config-row" style="margin:0;">
<label>API Type</label>
<select class="provider-api-type skeuo-input">${optionsHtml}</select>
</div>
<div class="config-row" style="margin: 8px 0;">
<label>包含的模型列表</label>
<div class="provider-model-list" style="display:flex; flex-direction:column; gap:8px;">${modelRowsHtml}</div>
<button type="button" class="provider-model-add panel-action-btn" data-provider-model-add style="margin-top: 10px; border-style: dashed; width: 100%;">
<i class="fa-solid fa-plus"></i> 追加一个模型
</button>
</div>
<div class="config-row provider-json-row" style="margin: 12px 0 0 0;">
<label style="display:flex; justify-content:space-between;">
<span>提供商级高级覆盖 (JSON)</span>
<span class="provider-json-error json-error-text" style="display:none;"><i class="fa-solid fa-triangle-exclamation"></i> 格式异常</span>
</label>
<textarea class="provider-json-config skeuo-textarea" placeholder="{\n "temperature": 0.7,\n "top_p": 1\n}">${escapeHtml(initialJsonStr)}</textarea>
<small class="form-hint" style="margin-top:6px;">将应用于此 Provider 下属所有模型的覆盖参数,必须为合法的 JSON 对象。</small>
</div>
</div>
</article>
`;
}
function appendProviderModelRow(targetList, rowData = {}) {
if (!targetList) return;
targetList.insertAdjacentHTML("beforeend", providerModelRowTemplate(rowData));
}
function providerCardHasContent(card) {
if (!card) return false;
const key = card.querySelector(".provider-key")?.value.trim() || "";
const baseUrl = card.querySelector(".provider-base-url")?.value.trim() || "";
const apiKey = card.querySelector(".provider-api-key")?.value.trim() || "";
if (key || baseUrl || apiKey) return true;
const rows = Array.from(card.querySelectorAll("[data-provider-model-row]"));
return rows.some((row) => {
const modelId = row.querySelector(".provider-model-id")?.value.trim() || "";
const contextWindow = row.querySelector(".provider-model-context")?.value.trim() || "";
const reasoning = row.querySelector(".provider-model-reasoning-toggle")?.checked === true;
const input = row.querySelector(".provider-model-input")?.value.trim() || "";
return Boolean(modelId || contextWindow || reasoning || input);
});
}
function appendProviderEditorCard() {
const container = $("models-providers-editor");
if (!container) return;
const cards = Array.from(container.querySelectorAll("[data-provider-card]"));
if (cards.length === 1 && !providerCardHasContent(cards[0])) {
cards[0].querySelector(".provider-key")?.focus();
return;
}
container.insertAdjacentHTML("beforeend", providerCardTemplate("", {}, ""));
const input = container.querySelector(".provider-edit-card:last-child .provider-key");
input?.focus();
}
function renderProviderEditors(providers) {
const container = $("models-providers-editor");
if (!container) return;
const entries = Object.entries(providers || {});
if (entries.length === 0) {
container.innerHTML = providerCardTemplate("", {}, "");
return;
}
container.innerHTML = entries
.map(([key, provider]) => providerCardTemplate(key, provider, key))
.join("");
}
function getProviderModelRows(provider) {
const rows = normalizeProviderModels(provider?.models, false);
return rows.filter((row) => row.id);
}
function getContextTier(contextWindow) {
const size = Number(contextWindow) || 0;
if (size >= 128000) return { tone: "xl", label: "Ultra" };
if (size >= 64000) return { tone: "lg", label: "Long" };
if (size >= 32000) return { tone: "md", label: "Wide" };
return { tone: "sm", label: "Fast" };
}
function renderProviderMatrix(providers) {
const matrix = $("models-provider-matrix");
if (!matrix) return;
const entries = Object.entries(providers || {});
if (entries.length === 0) {
matrix.innerHTML = `
<div class="empty-placeholder" style="grid-column: 1 / -1; padding: 40px;">
<i class="fa-solid fa-plug-circle-xmark empty-icon"></i>
<h3 style="color:var(--text-primary); font-size:1.1rem;">还没有接入任何算力核心</h3>
<p>点击上方按钮接入第一个大模型提供商</p>
</div>
`;
return;
}
const cards = entries
.map(([key, provider]) => {
const rows = getProviderModelRows(provider);
const modelCount = rows.length;
const apiType =
(typeof provider?.apiType === "string" && provider.apiType) ||
(typeof provider?.type === "string" && provider.type) ||
"openai";
const brand = getProviderBrand(key, apiType);
// 生成内部模型标签块(移除小圆点)
const modelChips = rows.map((r, i) => {
if (i >= 8) return ""; // 最多展示前8个,防撑爆
return `<span class="model-chip">${escapeHtml(r.id)}</span>`;
}).join('');
const overCount = modelCount > 8 ? `<span class="model-chip" style="background: rgba(255,255,255,0.05);">+${modelCount - 8}</span>` : "";
const iconHTML = brand.isSvg ? brand.icon : `<i class="${brand.icon}"></i>`;
return `
<article class="provider-card" data-provider-key="${escapeHtml(key)}">
<div class="provider-header">
<div class="provider-brand">
<div class="provider-logo-btn" data-provider-card-manage data-provider-key="${escapeHtml(key)}" title="修改 ${escapeHtml(key)} 设置">
${iconHTML}
</div>
<div class="provider-info">
<h4>${escapeHtml(key)}</h4>
<div class="provider-status active"><i class="fa-solid fa-circle"></i> 在线可用</div>
</div>
</div>
</div>
<div class="model-chips-container" style="margin-top: auto; padding-top: 10px;">
${modelChips}
${overCount}
<span class="model-chip" data-provider-card-manage data-provider-key="${escapeHtml(key)}" style="background:none; border-style:dashed; cursor:pointer;" title="配置更多">
<i class="fa-solid fa-ellipsis"></i>
</span>
</div>
</article>
`;
})
.join("");
matrix.innerHTML = cards;
}
// (底层模型胶囊池渲染已移除)
function setProviderModalOpen(open) {
const modal = $("models-provider-modal");
if (!modal) return;
state.providerModalOpen = open;
modal.classList.toggle("open", open);
modal.setAttribute("aria-hidden", open ? "false" : "true");
document.body.classList.toggle("provider-modal-open", open);
}
function focusProviderEditorByKey(providerKey) {
if (!providerKey) return;
const cards = Array.from(document.querySelectorAll("#models-providers-editor [data-provider-card]"));
const target = cards.find((card) => {
const originalKey = card.getAttribute("data-original-key") || "";
const currentKey = card.querySelector(".provider-key")?.value.trim() || "";
return originalKey === providerKey || currentKey === providerKey;
});
if (!target) return;
target.classList.add("focus-ring");
setTimeout(() => target.classList.remove("focus-ring"), 900);
target.scrollIntoView({ behavior: "smooth", block: "center" });
target.querySelector(".provider-key")?.focus();
}
function openProviderModal({ appendNew = false, focusKey = "" } = {}) {
setProviderModalOpen(true);
if (appendNew) appendProviderEditorCard();
if (focusKey) {
requestAnimationFrame(() => focusProviderEditorByKey(focusKey));
}
}
function closeProviderModal() {
setProviderModalOpen(false);
}
function collectProviders() {
const container = $("models-providers-editor");
const cards = container ? Array.from(container.querySelectorAll("[data-provider-card]")) : [];
const providers = {};
const seenKeys = new Set();
// 用于拦截弹窗并显示错误的状态位
let hasError = false;
for (let i = 0; i < cards.length; i += 1) {
const card = cards[i];
const key = card.querySelector(".provider-key")?.value.trim() || "";
const baseUrl = card.querySelector(".provider-base-url")?.value.trim() || "";
const apiKey = card.querySelector(".provider-api-key")?.value.trim() || "";
const apiType = card.querySelector(".provider-api-type")?.value.trim() || "openai";
const jsonInput = card.querySelector(".provider-json-config");
const jsonErrorText = card.querySelector(".provider-json-error");
// 初始化错误提示类和文字隐现
if (jsonInput) jsonInput.classList.remove("json-error");
if (jsonErrorText) jsonErrorText.style.display = "none";
let extraConfig = {};
if (jsonInput && jsonInput.value.trim()) {
try {
extraConfig = JSON.parse(jsonInput.value);
if (typeof extraConfig !== "object" || Array.isArray(extraConfig)) {
throw new Error("Must be an object");
}
} catch (e) {
jsonInput.classList.add("json-error");
if (jsonErrorText) jsonErrorText.style.display = "flex";
hasError = true;
showToast(`Provider '${key}' 的高级 JSON 格式错误: ${e.message}`, "error");
continue;
}
}
const modelRows = Array.from(card.querySelectorAll("[data-provider-model-row]"));
const models = [];
for (let rowIndex = 0; rowIndex < modelRows.length; rowIndex += 1) {
const modelRow = modelRows[rowIndex];
const modelId = modelRow.querySelector(".provider-model-id")?.value.trim() || "";
const contextWindowRaw = modelRow.querySelector(".provider-model-context")?.value.trim() || "";
const reasoning = modelRow.querySelector(".provider-model-reasoning-toggle")?.checked === true;
const inputText = modelRow.querySelector(".provider-model-input")?.value.trim() || "";
const extrasRaw = modelRow.querySelector(".provider-model-extras")?.value || "{}";
if (!modelId && !contextWindowRaw && !reasoning && !inputText) continue;
if (!modelId) throw new Error(`Provider ${key || `#${i + 1}`} 的第 ${rowIndex + 1} 个模型缺少 ID`);
const inputValues = inputText
.split(",")
.map((value) => value.trim())
.filter(Boolean);
let contextWindow = null;
if (contextWindowRaw) {
const parsedWindow = Number(contextWindowRaw);
if (!Number.isInteger(parsedWindow) || parsedWindow <= 0) {
throw new Error(`Provider ${key || `#${i + 1}`} 的模型 ${modelId} 上下文窗口必须是正整数`);
}
contextWindow = parsedWindow;