Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
776 lines (722 loc) · 37.3 KB
/
Copy pathserver.js
File metadata and controls
776 lines (722 loc) · 37.3 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
/* 🖤 Black API · 双AI指挥台 —— 基于 human-llm 总机架构的双主线 AI 服务
*
* ①上下文主脑 AI:自动为外部用户服务,全权维护会话上下文,可被中途注入打断
* ②轻量监工 AI:操作员与它对话,它可查看会话/注入指令/追加回复/执行本机命令(受门控)
* 操作员:全程监督,可审核改写每一条回复,可一键接管
*
* 零依赖实现(Node ≥ 18)。启动:node server.js(换端口:$env:PORT=9001; node server.js)
*/
"use strict";
const http = require("http");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { spawn } = require("child_process");
// ---------- 路径 ----------
const ROOT = __dirname;
const PUBLIC_DIR = path.join(ROOT, "public");
const CONFIG_PATH = path.join(ROOT, "config.json");
// ---------- 配置 ----------
const config = {
port: Number(process.env.PORT) || 8900,
accessKey: "",
mode: "context-auto", // context-auto | manual
reviewMode: false, // 发送前需操作员批准
reviewTimeoutSec: 120,
execMode: "off", // off | allowlist | all
allowlist: [],
contextAI: { baseUrl: "", apiKey: "", model: "" },
overseerAI: { baseUrl: "", apiKey: "", model: "" },
};
try {
if (fs.existsSync(CONFIG_PATH)) {
const s = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"));
for (const k of ["accessKey", "mode", "execMode"]) if (typeof s[k] === "string") config[k] = s[k];
if (typeof s.reviewMode === "boolean") config.reviewMode = s.reviewMode;
if (Number.isFinite(s.reviewTimeoutSec)) config.reviewTimeoutSec = s.reviewTimeoutSec;
if (Array.isArray(s.allowlist)) config.allowlist = s.allowlist.filter((x) => typeof x === "string");
for (const k of ["contextAI", "overseerAI"]) {
if (s[k] && typeof s[k] === "object") {
config[k].baseUrl = String(s[k].baseUrl || "");
config[k].apiKey = String(s[k].apiKey || "");
config[k].model = String(s[k].model || "");
}
}
}
} catch (e) {
console.warn("[配置] 读取 config.json 失败,使用默认配置:" + e.message);
}
function saveConfig() {
const tmp = CONFIG_PATH + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), "utf8");
fs.renameSync(tmp, CONFIG_PATH);
}
// ---------- 运行时状态 ----------
const startedAt = Date.now();
const sessions = new Map(); // sessionId -> {id,createdAt,updatedAt,messages:[{role,content,t}]}
const injections = []; // 待注入 {id,session:"<id>"|"next",kind,text,createdAt}
const tickets = new Map(); // 人工模式待答工单
const drafts = new Map(); // 审核模式挂起草稿
const auditLog = []; // 审计环形日志(≤200)
let overseerHistory = []; // 监工对话历史
const sseClients = new Set();
function state() {
return {
mode: config.mode,
reviewMode: config.reviewMode,
reviewTimeoutSec: config.reviewTimeoutSec,
execMode: config.execMode,
allowlist: [...config.allowlist],
accessKeySet: Boolean(config.accessKey),
contextAI: pick(config.contextAI),
overseerAI: pick(config.overseerAI),
counts: { sessions: sessions.size, pendingTickets: tickets.size, drafts: drafts.size },
startedAt,
};
}
function pick(ai) { return { baseUrl: ai.baseUrl, model: ai.model, hasKey: Boolean(ai.apiKey) }; }
function broadcast(event, data) {
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const c of sseClients) { try { c.res.write(frame); } catch (_) { /* ignore */ } }
}
const broadcastState = () => broadcast("state", state());
const nudgeSessions = () => broadcast("session", { t: Date.now() });
function addAudit(actor, tool, argsSummary, outcome, detail) {
const entry = { t: Date.now(), actor, tool, summary: String(argsSummary || "").slice(0, 120), outcome, detail: detail == null ? "" : String(detail).slice(0, 600) };
auditLog.unshift(entry);
if (auditLog.length > 200) auditLog.pop();
broadcast("audit", entry);
return entry;
}
// ---------- 小工具 ----------
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const uuid = () => crypto.randomUUID();
const sha1 = (s) => crypto.createHash("sha1").update(String(s)).digest("hex");
const estTokens = (s) => Math.max(1, Math.ceil(String(s || "").length / 4));
const maskKey = (k) => (k ? k.slice(0, 3) + "***" + k.slice(-3) : "(空)");
const authHeadersFor = (ai) => (ai.apiKey ? { Authorization: "Bearer " + ai.apiKey } : {});
const contentText = (c) => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => (p && p.text) || "").join("") : JSON.stringify(c));
function readBody(req, limit = 2 * 1024 * 1024) {
return new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on("data", (c) => { size += c.length; if (size > limit) { reject(new Error("请求体超过 2MB 上限")); req.destroy(); return; } chunks.push(c); });
req.on("end", () => {
if (!chunks.length) return resolve({});
try { resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); } catch (_) { reject(new Error("JSON 解析失败")); }
});
req.on("error", reject);
});
}
function json(res, code, obj) {
const buf = Buffer.from(JSON.stringify(obj), "utf8");
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": buf.length });
res.end(buf);
}
const errJson = (res, code, message, type = "invalid_request_error", code2) => json(res, code, { error: { message, type, code: code2 } });
function cors(res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "authorization,content-type,x-api-key,x-session-id");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS");
}
function checkAuth(req) {
if (!config.accessKey) return true;
const m = /^Bearer\s+(.+)$/i.exec(String(req.headers.authorization || ""));
const key = (m ? m[1] : String(req.headers["x-api-key"] || "")).trim();
return key === config.accessKey;
}
// 指挥台 /api/* 门控:支持 Bearer 头与 ?key= 查询参数(EventSource 无法自定义请求头)
function checkApiAuth(req, url) {
if (!config.accessKey) return true;
const m = /^Bearer\s+(.+)$/i.exec(String(req.headers.authorization || ""));
const key = (m ? m[1] : String(req.headers["x-api-key"] || "")).trim();
if (key && key === config.accessKey) return true;
const qk = String(url.searchParams.get("key") || "").trim();
return Boolean(qk) && qk === config.accessKey;
}
// ---------- 会话存储 ----------
function ensureSession(req, bodyMessages) {
const firstUser = bodyMessages.find((m) => m.role === "user");
let sid = req.headers["x-session-id"];
if (!sid && firstUser) sid = "auto-" + sha1(contentText(firstUser.content)).slice(0, 12);
if (!sid) sid = "auto-" + uuid().slice(0, 8);
if (!sessions.has(sid)) sessions.set(sid, { id: sid, createdAt: Date.now(), updatedAt: Date.now(), messages: [] });
// LRU 上限 50 个会话
if (sessions.size > 50) {
let oldest = null;
for (const s of sessions.values()) if (!oldest || s.updatedAt < oldest.updatedAt) oldest = s;
if (oldest) sessions.delete(oldest.id);
}
return sessions.get(sid);
}
function mergeTurns(session, incoming) {
const norm = incoming.map((m) => ({ role: m.role, content: contentText(m.content), t: Date.now() }));
if (incoming.length > 1) {
// 客户端自带完整历史 → 以客户端为准(有状态客户端)
session.messages = norm.slice(-40);
} else {
// 单条消息的无状态客户端 → 由服务器维护上下文,追加即可
session.messages.push(...norm.slice(-40));
}
session.updatedAt = Date.now();
}
// ---------- 注入系统 ----------
function takeInjections(sessionId) {
const hit = injections.filter((i) => i.session === sessionId || i.session === "next");
for (const h of hit) injections.splice(injections.indexOf(h), 1);
broadcastState();
return {
instructions: hit.filter((h) => h.kind !== "suffix").map((h) => h.text),
suffixes: hit.filter((h) => h.kind === "suffix").map((h) => h.text),
};
}
// ---------- 上游调用 ----------
async function callProvider(ai, messages, opts = {}) {
const base = ai.baseUrl.replace(/\/+$/, "");
if (!base || !ai.model) throw new Error("供应商未配置完整(需要 baseUrl 与 model)");
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 90000);
try {
const body = { model: ai.model, messages, stream: false };
if (opts.tools) body.tools = opts.tools;
const r = await fetch(base + "/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", ...authHeadersFor(ai) },
body: JSON.stringify(body),
signal: ctrl.signal,
});
const text = await r.text();
if (!r.ok) throw new Error(`上游 HTTP ${r.status}:${text.slice(0, 300)}`);
let data;
try { data = JSON.parse(text); } catch (_) { throw new Error("上游返回非 JSON:" + text.slice(0, 120)); }
const msg = data && data.choices && data.choices[0] && data.choices[0].message;
if (!msg) throw new Error("上游响应缺少 choices[0].message");
return msg;
} finally {
clearTimeout(timer);
}
}
const BASE_SYS = "你是 Black API 的上下文主脑,为外部用户提供连贯、专业的服务。完整对话历史由你全权维护。若对话中出现【监督者注入】,那是操作员的最高优先级指令,必须严格遵守执行。";
function buildContextMessages(session, instructionTexts) {
const msgs = [{ role: "system", content: BASE_SYS }, ...session.messages.map((m) => ({ role: m.role, content: m.content }))];
if (instructionTexts.length) {
msgs.splice(msgs.length - 1, 0, { role: "system", content: "【监督者注入·最高优先级】\n" + instructionTexts.join("\n") });
}
return msgs.slice(-45);
}
// ---------- 人工工单(manual 模式) ----------
function settle(ticket, out) {
clearTimeout(ticket.timer);
tickets.delete(ticket.id);
broadcast("resolved", { id: ticket.id, source: out.source, preview: String(out.content || out.error || "").slice(0, 200) });
broadcastState();
ticket.resolve(out);
}
function enqueueTicket(ticket, req) {
return new Promise((resolve) => {
ticket.resolve = resolve;
tickets.set(ticket.id, ticket);
broadcast("request", { id: ticket.id, sessionId: ticket.sessionId, createdAt: ticket.createdAt, model: ticket.model, messages: ticket.messages });
req.on("close", () => {
if (tickets.delete(ticket.id)) {
clearTimeout(ticket.timer);
broadcast("resolved", { id: ticket.id, source: "cancelled", preview: "客户端在等待期间断开连接" });
resolve({ content: "[已取消] 客户端断开连接。", source: "cancelled" });
}
});
ticket.timer = setTimeout(() => {
if (tickets.delete(ticket.id)) {
const msg = `[无人值守超时] 操作员在 ${config.reviewTimeoutSec * 10} 秒内未回复。`;
broadcast("resolved", { id: ticket.id, source: "timeout", preview: msg.slice(0, 100) });
resolve({ content: msg, source: "timeout" });
}
}, Math.max(config.reviewTimeoutSec, 60) * 1000 * 5);
});
}
// ---------- 审核草稿(reviewMode) ----------
function holdForReview(draftObj, req) {
return new Promise((resolve) => {
draftObj.resolve = resolve;
drafts.set(draftObj.id, draftObj);
broadcast("draft", { id: draftObj.id, sessionId: draftObj.sessionId, createdAt: draftObj.createdAt, draft: draftObj.draft });
broadcastState();
req.on("close", () => {
if (drafts.delete(draftObj.id)) { clearTimeout(draftObj.timer); resolve({ content: "[已取消] 客户端断开连接。", source: "cancelled" }); }
});
draftObj.timer = setTimeout(() => {
if (drafts.delete(draftObj.id)) {
addAudit("system", "review-timeout", draftObj.sessionId, "✅ 超时自动放行草稿");
resolve({ content: draftObj.draft, source: "context-ai" });
}
}, config.reviewTimeoutSec * 1000);
});
}
function settleDraft(d, out) {
clearTimeout(d.timer);
drafts.delete(d.id);
d.resolve(out);
broadcastState();
}
// ---------- 命令执行门控 ----------
const APP_ALIASES = { notepad: "notepad", calc: "calc", explorer: "explorer", powershell: "powershell", cmd: "cmd", taskmgr: "taskmgr" };
function gateCommand(cmd) {
if (config.execMode === "off") return "命令执行已锁定(execMode=off),请在「配置」面板解锁";
if (config.execMode === "allowlist" && !config.allowlist.includes(cmd.trim())) {
return `命令不在白名单:"${String(cmd).trim().slice(0, 80)}"`;
}
return null;
}
function runShell(command) {
return new Promise((resolve) => {
const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { windowsHide: true });
let out = "", err = "";
const cap = (cur, chunk) => (cur + chunk).slice(-4000);
child.stdout.on("data", (d) => { out = cap(out, d.toString()); });
child.stderr.on("data", (d) => { err = cap(err, d.toString()); });
let timedOut = false;
const t = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, 20000);
child.on("close", (code) => {
clearTimeout(t);
resolve(timedOut ? { ok: false, timedOut: true, stdout: out, stderr: err, code } : { ok: true, stdout: out.trim(), stderr: err.trim(), code });
});
child.on("error", (e) => { clearTimeout(t); resolve({ ok: false, stderr: String(e.message), code: -1 }); });
});
}
async function execTool(name, args, actor) {
args = args || {};
let result;
try {
switch (name) {
case "list_sessions": {
const list = [...sessions.values()].sort((a, b) => b.updatedAt - a.updatedAt).map((s) => ({
id: s.id, turns: s.messages.length, updatedAt: s.updatedAt,
lastPreview: (s.messages.filter((m) => m.role === "user").pop() || {}).content?.slice(0, 80) || "",
}));
result = { ok: true, count: list.length, sessions: list };
break;
}
case "get_session": {
let id = args.session;
if (id === "last" || !id) {
let newest = null;
for (const s of sessions.values()) if (!newest || s.updatedAt > newest.updatedAt) newest = s;
id = newest ? newest.id : null;
}
const s = id && sessions.get(id);
result = s ? { ok: true, id: s.id, messages: s.messages } : { ok: false, error: "会话不存在:" + id };
break;
}
case "inject_instruction": {
if (!args.text) { result = { ok: false, error: "缺少注入文本" }; break; }
const inj = { id: uuid(), session: args.session || "next", kind: "instruction", text: String(args.text), createdAt: Date.now() };
injections.push(inj);
broadcast("injection", inj);
result = { ok: true, queued: inj.id, note: "将在该会话下一次主脑调用时生效(一次性)" };
break;
}
case "append_to_reply": {
if (!args.text) { result = { ok: false, error: "缺少附言文本" }; break; }
const inj = { id: uuid(), session: args.session || "next", kind: "suffix", text: String(args.text), createdAt: Date.now() };
injections.push(inj);
broadcast("injection", inj);
result = { ok: true, queued: inj.id, note: "将附加到下一次最终回复末尾" };
break;
}
case "run_command": {
const cmd = String(args.command || "").trim();
const denied = gateCommand(cmd);
if (denied) { result = { refused: true, reason: denied }; break; }
result = await runShell(cmd);
break;
}
case "open_app": {
const alias = APP_ALIASES[String(args.name || "").toLowerCase()];
if (!alias) { result = { refused: true, reason: "未知应用别名,可用:" + Object.keys(APP_ALIASES).join(",") }; break; }
const denied = gateCommand(alias);
if (denied) { result = { refused: true, reason: denied }; break; }
spawn("cmd.exe", ["/c", "start", "", alias], { windowsHide: true, detached: true }).unref();
result = { ok: true, opened: alias };
break;
}
default:
result = { ok: false, error: "未知工具:" + name };
}
} catch (e) {
result = { ok: false, error: String(e.message || e) };
}
const refused = result && result.refused;
addAudit(actor, name, JSON.stringify(args).slice(0, 120), refused ? "🚫 已拒绝" : "✅", refused ? result.reason : JSON.stringify(result).slice(0, 300));
return result;
}
// ---------- 监工工具循环 ----------
const TOOLS = [
{ type: "function", function: { name: "list_sessions", description: "列出当前所有活跃对话会话(含轮数与最近消息预览)", parameters: { type: "object", properties: {}, required: [] } } },
{ type: "function", function: { name: "get_session", description: "读取某会话完整消息记录。session 传会话ID或 'last' 表示最近活跃的会话", parameters: { type: "object", properties: { session: { type: "string", description: "会话ID或'last'" } }, required: ["session"] } } },
{ type: "function", function: { name: "inject_instruction", description: "向指定会话的下一次主脑调用注入最高优先级指令(一次性生效)。session 省略或传 'next' 表示下一个进来的会话", parameters: { type: "object", properties: { session: { type: "string" }, text: { type: "string", description: "要注入的指令内容" } }, required: ["text"] } } },
{ type: "function", function: { name: "append_to_reply", description: "向指定会话的下一次最终回复末尾附加一段文字(以【监督者附言】形式)。session 规则同上", parameters: { type: "object", properties: { session: { type: "string" }, text: { type: "string" } }, required: ["text"] } } },
{ type: "function", function: { name: "run_command", description: "在本机执行 PowerShell 命令。受执行模式门控:off 一律拒绝;allowlist 仅白名单内精确匹配放行;all 全放行", parameters: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } } },
{ type: "function", function: { name: "open_app", description: "打开本机应用,别名可选:notepad/calc/explorer/powershell/cmd/taskmgr(同样受门控)", parameters: { type: "object", properties: { name: { type: "string" } }, required: ["name"] } } },
];
async function overseeLoop(userMessage) {
const ai = config.overseerAI;
if (!ai.baseUrl || !ai.model) throw new Error("轻量监工未配置(请在配置面板填写 baseUrl 与 model)");
const sys = `你是 Black API 的轻量监工 AI。操作员通过你监督并干预"上下文主脑"与外部用户的对话。你可以调用工具:查看会话(list_sessions/get_session)、向会话注入一次性最高优先级指令(inject_instruction)、给回复附加文字(append_to_reply)、执行本机 PowerShell 命令(run_command)、打开应用(open_app)。当前命令执行模式:${config.execMode}${config.execMode === "allowlist" ? "(白名单:" + config.allowlist.join(";") + ")" : ""}。被拒绝的工具调用是正常的安全门控行为,请如实告知操作员。回答使用简短中文。`;
const msgs = [{ role: "system", content: sys }, ...overseerHistory.map((h) => ({ role: h.role, content: h.content })), { role: "user", content: userMessage }];
const steps = [];
for (let i = 0; i < 6; i++) {
const resp = await callProvider(ai, msgs, { tools: TOOLS });
if (Array.isArray(resp.tool_calls) && resp.tool_calls.length) {
msgs.push({ role: "assistant", content: resp.content || "", tool_calls: resp.tool_calls });
for (const tc of resp.tool_calls) {
let args = {};
try { args = JSON.parse(tc.function.arguments || "{}"); } catch (_) { /* 容错 */ }
const result = await execTool(tc.function.name, args, "overseer");
steps.push({ tool: tc.function.name, args, result });
msgs.push({ role: "tool", tool_call_id: tc.id, content: JSON.stringify(result).slice(0, 4000) });
}
continue;
}
overseerHistory.push({ role: "user", content: userMessage });
overseerHistory.push({ role: "assistant", content: resp.content || "", steps });
if (overseerHistory.length > 40) overseerHistory = overseerHistory.slice(-40);
broadcast("oversee", { role: "user", content: userMessage });
broadcast("oversee", { role: "assistant", content: resp.content || "", steps });
return { reply: resp.content || "(空回复)", steps };
}
return { reply: "(工具循环达到上限,未得出最终答复)", steps };
}
// ---------- /v1/chat/completions 主流程 ----------
async function handleChat(req, res) {
const body = await readBody(req);
const messages = body.messages;
if (!Array.isArray(messages) || messages.length === 0 ||
!messages.every((m) => m && typeof m === "object" && typeof m.role === "string")) {
return errJson(res, 400, "messages 必须为非空数组,且每个元素包含 role 字段");
}
const model = typeof body.model === "string" && body.model ? body.model : "black-context";
const created = Math.floor(Date.now() / 1000);
const eventId = uuid();
const session = ensureSession(req, messages);
mergeTurns(session, messages);
const lastUser = [...messages].reverse().find((m) => m.role === "user");
let final, servedBy;
if (config.mode === "manual") {
const out = await enqueueTicket({ id: uuid(), sessionId: session.id, createdAt: Date.now(), model, messages }, req);
if (out.error) return errJson(res, 502, out.error, "upstream_error");
final = out.content;
servedBy = out.source;
} else {
// 自动模式:上下文主脑 + 中途注入
const inj = takeInjections(session.id);
if (inj.instructions.length || inj.suffixes.length) {
addAudit("system", "injection-applied", session.id, "⚡", `指令×${inj.instructions.length} 附言×${inj.suffixes.length}`);
}
const input = buildContextMessages(session, inj.instructions);
let draft;
try {
const resp = await callProvider(config.contextAI, input);
draft = typeof resp.content === "string" ? resp.content : "";
if (!draft) throw new Error("主脑返回空内容");
} catch (e) {
return errJson(res, 502, "主脑调用失败:" + e.message, "upstream_error");
}
for (const suf of inj.suffixes) draft += "\n\n【监督者附言】" + suf;
if (config.reviewMode) {
const out = await holdForReview({ id: uuid(), sessionId: session.id, createdAt: Date.now(), draft, input }, req);
if (out.error) return errJson(res, 502, out.error, "upstream_error");
final = out.content;
servedBy = out.source; // operator-edit | rejected | context-ai(超时放行)
} else {
final = draft;
servedBy = "context-ai";
}
}
session.messages.push({ role: "assistant", content: final, t: Date.now() });
session.updatedAt = Date.now();
broadcast("resolved", { id: eventId, source: servedBy, preview: final.slice(0, 200) });
nudgeSessions();
if (body.stream) {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", "x-request-id": eventId });
const frame = (delta, finish) =>
`data: ${JSON.stringify({ id: "chatcmpl-" + eventId, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish === undefined ? null : finish }] })}\n\n`;
res.write(frame({ role: "assistant", content: "" }));
for (let i = 0; i < final.length; i += 24) { res.write(frame({ content: final.slice(i, i + 24) })); await sleep(30); }
res.write(frame({}, "stop"));
res.write("data: [DONE]\n\n");
return res.end();
}
const pt = estTokens(JSON.stringify(messages));
const ct = estTokens(final);
return json(res, 200, {
id: "chatcmpl-" + eventId,
object: "chat.completion",
created,
model,
choices: [{ index: 0, message: { role: "assistant", content: final }, finish_reason: "stop" }],
usage: { prompt_tokens: pt, completion_tokens: ct, total_tokens: pt + ct },
served_by: servedBy,
session_id: session.id,
});
}
// ---------- /api 路由 ----------
async function handleApi(req, res, pathname) {
const M = req.method;
// ----- 只读 -----
if (M === "GET" && pathname === "/api/state") return json(res, 200, state());
if (M === "GET" && pathname === "/api/sessions") {
const list = [...sessions.values()].sort((a, b) => b.updatedAt - a.updatedAt).map((s) => ({
id: s.id, createdAt: s.createdAt, updatedAt: s.updatedAt, turns: s.messages.length,
lastPreview: ((s.messages.filter((m) => m.role === "user").pop() || {}).content || "").slice(0, 80),
}));
return json(res, 200, list);
}
if (M === "GET" && pathname.startsWith("/api/session/")) {
const s = sessions.get(decodeURIComponent(pathname.slice("/api/session/".length)));
if (!s) return errJson(res, 404, "会话不存在");
return json(res, 200, { id: s.id, messages: [...s.messages].sort((a, b) => a.t - b.t) });
}
if (M === "GET" && pathname === "/api/injections") return json(res, 200, injections);
if (M === "GET" && pathname === "/api/pending") {
return json(res, 200, [...tickets.values()].map(({ id, sessionId, createdAt, model, messages }) => ({ id, sessionId, createdAt, model, messages })));
}
if (M === "GET" && pathname === "/api/drafts") {
return json(res, 200, [...drafts.values()].map(({ id, sessionId, createdAt, draft }) => ({ id, sessionId, createdAt, draft })));
}
if (M === "GET" && pathname === "/api/oversee/history") return json(res, 200, overseerHistory);
if (M === "GET" && pathname === "/api/audit") return json(res, 200, auditLog);
const body = await readBody(req);
// ----- 会话删除 -----
if (M === "DELETE" && pathname.startsWith("/api/session/")) {
const id = decodeURIComponent(pathname.slice("/api/session/".length));
sessions.delete(id);
nudgeSessions();
return json(res, 200, { ok: true });
}
// ----- 配置 -----
if (M === "POST" && pathname === "/api/config") {
const target = body.target;
if (target !== "contextAI" && target !== "overseerAI") return errJson(res, 400, 'target 必须为 "contextAI" 或 "overseerAI"');
const ai = config[target];
if (typeof body.baseUrl === "string") ai.baseUrl = body.baseUrl.trim().replace(/\/+$/, "");
if (typeof body.model === "string") ai.model = body.model.trim();
if (typeof body.apiKey === "string" && body.apiKey.trim() !== "") ai.apiKey = body.apiKey.trim();
saveConfig();
console.log("[配置] %s 已保存 baseUrl=%s model=%s apiKey=%s", target, ai.baseUrl, ai.model, maskKey(ai.apiKey));
broadcastState();
return json(res, 200, state());
}
if (M === "POST" && pathname === "/api/test-provider") {
const ai = config[body.target];
if (!ai) return errJson(res, 400, "target 无效");
const base = ai.baseUrl.replace(/\/+$/, "");
try {
const r = await fetch(base + "/models", { headers: authHeadersFor(ai), signal: AbortSignal.timeout(15000) });
const text = await r.text();
if (!r.ok) return json(res, 200, { ok: false, models: [], status: r.status, error: `HTTP ${r.status}:${text.slice(0, 200)}` });
const data = JSON.parse(text);
return json(res, 200, { ok: true, models: ((data && data.data) || []).map((x) => x && x.id).filter(Boolean), status: r.status, error: null });
} catch (e) {
return json(res, 200, { ok: false, models: [], status: null, error: String(e.message || e) });
}
}
if (M === "POST" && pathname === "/api/mode") {
if (body.mode !== "context-auto" && body.mode !== "manual") return errJson(res, 400, 'mode 必须为 "context-auto" 或 "manual"');
if (body.mode === "context-auto" && (!config.contextAI.baseUrl || !config.contextAI.model)) {
return errJson(res, 400, "主脑自动模式需要先配置上下文主脑模型(baseUrl 与 model)");
}
config.mode = body.mode;
saveConfig();
console.log("[模式] → " + (config.mode === "auto" ? "主脑自动" : config.mode));
broadcastState();
return json(res, 200, state());
}
if (M === "POST" && pathname === "/api/review") {
config.reviewMode = Boolean(body.enabled);
saveConfig();
broadcastState();
return json(res, 200, state());
}
if (M === "POST" && pathname === "/api/timeout") {
const n = Number(body.reviewTimeoutSec);
if (!Number.isInteger(n) || n < 10 || n > 1800) return errJson(res, 400, "reviewTimeoutSec 必须为 10..1800 的整数");
config.reviewTimeoutSec = n;
saveConfig();
broadcastState();
return json(res, 200, state());
}
if (M === "POST" && pathname === "/api/exec") {
if (!["off", "allowlist", "all"].includes(body.mode)) return errJson(res, 400, 'mode 必须为 "off"|"allowlist"|"all"');
config.execMode = body.mode;
saveConfig();
addAudit("operator", "exec-mode", body.mode, "🔧 切换执行模式");
broadcastState();
return json(res, 200, state());
}
if (M === "POST" && pathname === "/api/allowlist") {
if (body.clear) config.allowlist = [];
if (typeof body.add === "string" && body.add.trim() && !config.allowlist.includes(body.add.trim())) config.allowlist.push(body.add.trim());
if (typeof body.remove === "string") config.allowlist = config.allowlist.filter((x) => x !== body.remove.trim());
saveConfig();
broadcastState();
return json(res, 200, { allowlist: [...config.allowlist] });
}
if (M === "POST" && pathname === "/api/access-key") {
config.accessKey = typeof body.accessKey === "string" ? body.accessKey.trim() : "";
saveConfig();
broadcastState();
return json(res, 200, state());
}
// ----- 注入 -----
if (M === "POST" && pathname === "/api/inject") {
const text = typeof body.text === "string" ? body.text.trim() : "";
if (!text) return errJson(res, 400, "注入文本不能为空");
const inj = { id: uuid(), session: body.session || "next", kind: body.kind === "suffix" ? "suffix" : "instruction", text, createdAt: Date.now() };
injections.push(inj);
broadcast("injection", inj);
return json(res, 200, { ok: true, inj });
}
if (M === "POST" && pathname === "/api/inject/cancel") {
const idx = injections.findIndex((i) => i.id === body.id);
if (idx >= 0) injections.splice(idx, 1);
return json(res, 200, { ok: true });
}
// ----- 人工接答 -----
if (M === "POST" && pathname === "/api/reply") {
const t = tickets.get(body.id);
const content = typeof body.content === "string" ? body.content.trim() : "";
if (!t) return errJson(res, 404, "工单不存在或已处理", "invalid_request_error", "not_found");
if (!content) return errJson(res, 400, "回复内容不能为空");
settle(t, { content, source: "operator" });
return json(res, 200, { ok: true });
}
if (M === "POST" && pathname === "/api/skip") {
const t = tickets.get(body.id);
if (!t) return errJson(res, 404, "工单不存在或已处理", "invalid_request_error", "not_found");
settle(t, { content: "[已跳过] 操作员未处理该请求。", source: "skip" });
return json(res, 200, { ok: true });
}
// ----- 审核草稿 -----
if (M === "POST" && pathname === "/api/approve") {
const d = drafts.get(body.id);
if (!d) return errJson(res, 404, "草稿不存在或已处理", "invalid_request_error", "not_found");
const content = typeof body.content === "string" && body.content.trim() ? body.content.trim() : d.draft;
settleDraft(d, { content, source: content === d.draft ? "context-ai" : "operator-edit" });
return json(res, 200, { ok: true });
}
if (M === "POST" && pathname === "/api/reject") {
const d = drafts.get(body.id);
if (!d) return errJson(res, 404, "草稿不存在或已处理", "invalid_request_error", "not_found");
settleDraft(d, { content: "[该回复已被监督者否决]", source: "rejected" });
return json(res, 200, { ok: true });
}
// ----- 命令执行 -----
if (M === "POST" && pathname === "/api/run") {
const cmd = String(body.command || "").trim();
if (!cmd) return errJson(res, 400, "command 不能为空");
const result = await execTool("run_command", { command: cmd }, "operator");
return json(res, 200, result);
}
// ----- 监工 -----
if (M === "POST" && pathname === "/api/oversee") {
const msg = typeof body.message === "string" ? body.message.trim() : "";
if (!msg) return errJson(res, 400, "message 不能为空");
try {
const out = await overseeLoop(msg);
return json(res, 200, out);
} catch (e) {
return errJson(res, 502, "监工调用失败:" + e.message, "upstream_error");
}
}
if (M === "POST" && pathname === "/api/oversee/reset") {
overseerHistory = [];
return json(res, 200, { ok: true });
}
return errJson(res, 404, "Not Found: " + pathname);
}
// ---------- 静态文件 ----------
const MIME = {
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
};
function serveStatic(req, res, pathname) {
const rel = pathname === "/" ? "/index.html" : pathname;
let fp;
try { fp = path.normalize(path.join(PUBLIC_DIR, decodeURIComponent(rel))); } catch (_) { return errJson(res, 400, "Bad path"); }
if (!fp.startsWith(PUBLIC_DIR)) return errJson(res, 403, "Forbidden");
fs.readFile(fp, (err, buf) => {
if (err) return errJson(res, 404, "Not Found: " + pathname);
res.writeHead(200, { "Content-Type": MIME[path.extname(fp).toLowerCase()] || "application/octet-stream" });
res.end(buf);
});
}
// ---------- 总路由 ----------
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const pathname = url.pathname;
try {
if (req.method === "OPTIONS" && pathname.startsWith("/v1/")) { cors(res); res.writeHead(204); return res.end(); }
if (pathname.startsWith("/v1/")) {
cors(res);
if (!checkAuth(req)) {
res.setHeader("Connection", "close");
return errJson(res, 401, "访问密钥缺失或不正确(携带 Authorization: Bearer <密钥>)", "invalid_request_error", "invalid_api_key");
}
if (req.method === "GET" && pathname === "/v1/models") {
const data = [];
if (config.contextAI.model) data.push({ id: config.contextAI.model, object: "model", created: Math.floor(startedAt / 1000), owned_by: "black-context" });
data.push({ id: "black-context", object: "model", created: Math.floor(startedAt / 1000), owned_by: "you" });
return json(res, 200, { object: "list", data });
}
if (req.method === "POST" && pathname === "/v1/chat/completions") return await handleChat(req, res);
return errJson(res, 404, "Not Found: " + pathname);
}
if (pathname === "/healthz") {
return json(res, 200, { ok: true, uptime: Math.floor((Date.now() - startedAt) / 1000), counts: { sessions: sessions.size, pendingTickets: tickets.size, drafts: drafts.size } });
}
if (pathname === "/api/events" && req.method === "GET") {
if (!checkApiAuth(req, url)) return errJson(res, 401, "指挥台已启用访问密钥:请用 /api/events?key=<密钥> 连接");
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", "Access-Control-Allow-Origin": "*" });
res.write(`event: hello\ndata: ${JSON.stringify(state())}\n\n`);
const client = { res };
sseClients.add(client);
const ping = setInterval(() => { try { res.write(`event: ping\ndata: {"t":${Date.now()}}\n\n`); } catch (_) { /* ignore */ } }, 15000);
req.on("close", () => { clearInterval(ping); sseClients.delete(client); });
return;
}
if (pathname.startsWith("/api/")) {
if (!checkApiAuth(req, url)) {
res.setHeader("Connection", "close");
return errJson(res, 401, "指挥台已启用访问密钥:请求需携带 Authorization: Bearer <密钥> 或 ?key=<密钥>", "invalid_request_error", "invalid_api_key");
}
return await handleApi(req, res, pathname);
}
if (req.method === "GET") return serveStatic(req, res, pathname);
return errJson(res, 404, "Not Found");
} catch (e) {
console.error("[错误]", req.method, pathname, e);
if (!res.headersSent) errJson(res, 500, "服务器内部错误:" + e.message, "server_error");
else { try { res.end(); } catch (_) { /* ignore */ } }
}
});
server.on("error", (e) => {
if (e && e.code === "EADDRINUSE") {
console.error(`[启动失败] 端口 ${config.port} 已被占用。换端口:$env:PORT=9001; node server.js`);
process.exit(1);
}
throw e;
});
server.listen(config.port, "127.0.0.1", () => {
const base = `http://127.0.0.1:${config.port}`;
console.log("──────────────────────────────────────────────");
console.log("🖤 Black API · 双AI指挥台 已就绪");
console.log(` 指挥台 : ${base}`);
console.log(` API 端点 : ${base}/v1/chat/completions`);
console.log(" ①上下文主脑:自动带全会话上下文服务用户(右侧面板配置)");
console.log(" ②轻量监工 :与它对话即可查会话/注入指令/执行命令(受门控)");
console.log("──────────────────────────────────────────────");
});
process.on("SIGINT", () => {
console.log("\n[关闭] Black API 下线,再见。");
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1500).unref();
});