@bolloon/bolloon-agent 0.1.33 → 0.1.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.auto-evolve-calls +1 -0
- package/.last-auto-evolve-baseline +1 -0
- package/Bolloon.md +103 -0
- package/README.md +7 -2
- package/dist/agents/pi-sdk.js +264 -12
- package/dist/bollharness-integration/index.js +8 -1
- package/dist/bootstrap/bootstrap.js +114 -0
- package/dist/bootstrap/context-collector.js +296 -0
- package/dist/bootstrap/lifecycle-hooks.js +109 -0
- package/dist/bootstrap/project-context.js +151 -0
- package/dist/heartbeat/Watchdog.js +9 -1
- package/dist/index.js +11 -0
- package/dist/llm/pi-ai.js +31 -21
- package/dist/network/p2p-direct.js +59 -2
- package/dist/pi-ecosystem/index.js +9 -6
- package/dist/pi-ecosystem-judgment/adaptive-scan.js +231 -0
- package/dist/pi-ecosystem-judgment/causal-judge.js +449 -0
- package/dist/pi-ecosystem-judgment/decision.js +5 -2
- package/dist/pi-ecosystem-judgment/detect-hook.js +168 -0
- package/dist/pi-ecosystem-judgment/distill-prompt.js +226 -0
- package/dist/pi-ecosystem-judgment/evolve-judgment.js +170 -0
- package/dist/pi-ecosystem-judgment/human-value-pipeline.js +21 -0
- package/dist/pi-ecosystem-judgment/human-value-store.js +283 -22
- package/dist/pi-ecosystem-judgment/injection-gate.js +166 -0
- package/dist/pi-ecosystem-judgment/monitor-gate.js +188 -0
- package/dist/security/builtin-guards.js +124 -0
- package/dist/security/context-router-tool.js +106 -0
- package/dist/security/react-harness.js +143 -0
- package/dist/security/tool-gate.js +235 -0
- package/dist/social/heartbeat.js +19 -2
- package/dist/utils/auto-evolve-policy.js +117 -0
- package/dist/utils/clamp.js +7 -0
- package/dist/utils/double.js +6 -0
- package/dist/web/api-config.html +3 -3
- package/dist/web/client.js +1328 -351
- package/dist/web/index.html +34 -31
- package/dist/web/server.js +1128 -58
- package/dist/web/style.css +370 -0
- package/lefthook.yml +29 -0
- package/package.json +4 -2
- package/scripts/auto-evolve-loop.ts +376 -0
- package/scripts/auto-evolve-oneshot.sh +155 -0
- package/scripts/auto-evolve-snapshot.sh +136 -0
- package/scripts/detect-schema-changes.sh +48 -0
- package/scripts/diff-reviewer.ts +159 -0
- package/scripts/weekly-report.ts +364 -0
- package/src/agents/pi-sdk.ts +293 -15
- package/src/bollharness-integration/index.ts +8 -32
- package/src/bootstrap/bootstrap.ts +132 -0
- package/src/bootstrap/context-collector.ts +342 -0
- package/src/bootstrap/lifecycle-hooks.ts +176 -0
- package/src/bootstrap/project-context.ts +163 -0
- package/src/heartbeat/Watchdog.ts +9 -1
- package/src/index.ts +11 -0
- package/src/llm/pi-ai.ts +33 -22
- package/src/network/p2p-direct.ts +59 -3
- package/src/security/builtin-guards.ts +162 -0
- package/src/security/context-router-tool.ts +122 -0
- package/src/security/react-harness.ts +177 -0
- package/src/security/tool-gate.ts +294 -0
- package/src/social/ant-colony/index.js +19 -0
- package/src/social/heartbeat.ts +18 -2
- package/src/utils/auto-evolve-policy.ts +138 -0
- package/src/utils/clamp.ts +5 -0
- package/src/web/api-config.html +3 -3
- package/src/web/client.js +1328 -351
- package/src/web/index.html +34 -31
- package/src/web/server.ts +1179 -53
- package/src/web/style.css +370 -0
- package/staging/auto-evolve/clean-001/.review-verdict +9 -0
- package/staging/auto-evolve/clean-001/clean-001.patch +14 -0
- package/staging/auto-evolve/e2e-001/.patch-id +1 -0
- package/staging/auto-evolve/e2e-001/.review-verdict +12 -0
- package/staging/auto-evolve/e2e-001/e2e-001.patch +11 -0
- package/staging/auto-evolve/test-bad/.review-verdict +12 -0
- package/staging/auto-evolve/test-bad/test-bad.patch +11 -0
- package/src/social/ant-colony/AdaptiveHeartbeat.ts +0 -131
- package/src/social/ant-colony/PheromoneEngine.ts +0 -302
- package/src/social/ant-colony/index.ts +0 -18
- package/src/social/ant-colony/types.ts +0 -94
package/dist/web/server.js
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'url';
|
|
|
5
5
|
import * as fs from 'fs/promises';
|
|
6
6
|
import * as fsSync from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
|
+
import * as os from 'os';
|
|
8
9
|
import { createHyperswarmCommunicator, createTopic, KeyManager, AgentAuthManager, } from '@diap/sdk';
|
|
9
10
|
import { documentReader } from '../documents/reader.js';
|
|
10
11
|
import { initMinimax, getMinimax } from '../constraints/index.js';
|
|
@@ -281,8 +282,54 @@ let sseClients = new Set();
|
|
|
281
282
|
// v3: 远端 channel UI 元数据缓存 — key: peerId, value: sanitize 过的 channel 列表
|
|
282
283
|
// in-memory only, 进程重启清空 (judgment 内容永远不在这里)
|
|
283
284
|
let remoteChannelCache = new Map();
|
|
285
|
+
// 2026-06-10: 持久化 remote channel cache 到 ~/.bolloon/remote-channels-cache.json
|
|
286
|
+
// 之前是纯内存 Map, nodeA 重启后所有对端 channel 列表丢失, 需要等对面再推一次
|
|
287
|
+
const REMOTE_CACHE_FILE = `${process.env.HOME || '/tmp'}/.bolloon/remote-channels-cache.json`;
|
|
288
|
+
async function loadRemoteChannelCacheFromDisk() {
|
|
289
|
+
try {
|
|
290
|
+
const { readFile, mkdir } = await import('fs/promises');
|
|
291
|
+
const { existsSync } = await import('fs');
|
|
292
|
+
if (!existsSync(REMOTE_CACHE_FILE))
|
|
293
|
+
return;
|
|
294
|
+
const raw = await readFile(REMOTE_CACHE_FILE, 'utf-8');
|
|
295
|
+
const obj = JSON.parse(raw);
|
|
296
|
+
if (obj && typeof obj === 'object') {
|
|
297
|
+
for (const [pk, list] of Object.entries(obj)) {
|
|
298
|
+
if (Array.isArray(list)) {
|
|
299
|
+
remoteChannelCache.set(pk, list);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
console.log(`[v3-meta] 从磁盘恢复 ${remoteChannelCache.size} 个 peer 的 channel cache`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
console.warn('[v3-meta] 恢复 remote channel cache 失败 (非致命):', err.message);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
async function persistRemoteChannelCache() {
|
|
310
|
+
try {
|
|
311
|
+
const { writeFile, mkdir } = await import('fs/promises');
|
|
312
|
+
const { existsSync } = await import('fs');
|
|
313
|
+
if (!existsSync(`${process.env.HOME || '/tmp'}/.bolloon`)) {
|
|
314
|
+
await mkdir(`${process.env.HOME || '/tmp'}/.bolloon`, { recursive: true });
|
|
315
|
+
}
|
|
316
|
+
const obj = {};
|
|
317
|
+
for (const [pk, list] of remoteChannelCache.entries()) {
|
|
318
|
+
obj[pk] = list;
|
|
319
|
+
}
|
|
320
|
+
await writeFile(REMOTE_CACHE_FILE, JSON.stringify(obj, null, 2), 'utf-8');
|
|
321
|
+
}
|
|
322
|
+
catch (err) {
|
|
323
|
+
console.warn('[v3-meta] 持久化 remote channel cache 失败 (非致命):', err.message);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
// 启动时立即同步读一次 (异步, 不阻塞)
|
|
327
|
+
loadRemoteChannelCacheFromDisk();
|
|
284
328
|
// v3: P2PDirect 引用 (Hyperswarm 薄包装) - 模块级, 因为 web server 闭包里不可用
|
|
285
329
|
let v3P2PRef = null;
|
|
330
|
+
// 2026-06-10: watchdog 提升到 module-level, 让 broadcast() / 模块级业务函数能埋点喂活动
|
|
331
|
+
// 之前在 createWebServer 闭包内, 闭包外的 broadcast() 拿不到 → 误判 30min 无活动 → 自杀.
|
|
332
|
+
let watchdogRef = null;
|
|
286
333
|
// v3: 等待中的 history RPC (B 端 chat-history endpoint 用) — rpcId → { resolve, reject }
|
|
287
334
|
const v3PendingHistoryGets = new Map();
|
|
288
335
|
let channelSessions = new Map(); // key: channelId
|
|
@@ -318,7 +365,6 @@ function sanitizeChannelForPeer(ch, peerPublicKey) {
|
|
|
318
365
|
createdAt: ch.createdAt,
|
|
319
366
|
updatedAt: ch.updatedAt,
|
|
320
367
|
hasWallet: !!ch.walletAddress,
|
|
321
|
-
boundJudgmentCount: Array.isArray(ch.bound_judgment_ids) ? ch.bound_judgment_ids.length : 0,
|
|
322
368
|
share_id: ch.share_id,
|
|
323
369
|
// 🔒 不返回: bound_judgment_ids, walletAddress, walletBinding, autoInvokeTools, sessions, shared_with_peers
|
|
324
370
|
};
|
|
@@ -556,6 +602,14 @@ async function handleV3P2PMessage(parsed, conn, comm) {
|
|
|
556
602
|
catch (saveErr) {
|
|
557
603
|
console.warn(`[v3] 存 user 消息失败 (不影响 chat):`, saveErr.message);
|
|
558
604
|
}
|
|
605
|
+
// v3 修复: 同步给 A 自己的 UI — broadcast SSE 事件让 A 的 owner 实时看到 B 的消息
|
|
606
|
+
broadcast({
|
|
607
|
+
type: 'user',
|
|
608
|
+
content: text,
|
|
609
|
+
channelId,
|
|
610
|
+
source: 'remote',
|
|
611
|
+
fromPublicKey: senderKey
|
|
612
|
+
}, channelId);
|
|
559
613
|
// v3 新增: 告诉 B "我开始想了, 用了哪些 judgment" — 让 B 看到决策依据
|
|
560
614
|
const judgmentHint = await buildJudgmentHint(ch, channelId);
|
|
561
615
|
const usedJudgments = await extractJudgmentsFromHint(ch);
|
|
@@ -604,7 +658,13 @@ async function handleV3P2PMessage(parsed, conn, comm) {
|
|
|
604
658
|
let fullResponse = '';
|
|
605
659
|
// v3 新增: 流式 token 节流推给 B — 让 B 看到过程
|
|
606
660
|
let lastFlushAt = 0;
|
|
661
|
+
let usedJudgmentIds = [];
|
|
607
662
|
const streamCallback = (event) => {
|
|
663
|
+
// P0.5: 注入门回传
|
|
664
|
+
if (event?.type === 'used_judgments' && Array.isArray(event.usedIds)) {
|
|
665
|
+
usedJudgmentIds = event.usedIds;
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
608
668
|
if (event.type === 'token') {
|
|
609
669
|
fullResponse += event.content;
|
|
610
670
|
if (fullResponse.length - lastFlushAt >= 20) {
|
|
@@ -618,7 +678,7 @@ async function handleV3P2PMessage(parsed, conn, comm) {
|
|
|
618
678
|
}
|
|
619
679
|
};
|
|
620
680
|
const agent = await getAgentForChannel(channelId, ch.did || '', ch.name, ch.didDocRef);
|
|
621
|
-
fullResponse = await agent.promptStream(fullPrompt, streamCallback);
|
|
681
|
+
fullResponse = await agent.promptStream(fullPrompt, streamCallback, undefined, channelId);
|
|
622
682
|
// v3 新增: 存 A 的 assistant 消息到 session — B 拉历史时能看到完整对话
|
|
623
683
|
try {
|
|
624
684
|
const existing = await loadSession(channelId, 'default');
|
|
@@ -629,6 +689,7 @@ async function handleV3P2PMessage(parsed, conn, comm) {
|
|
|
629
689
|
id: `msg-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
630
690
|
type: 'ai',
|
|
631
691
|
content: fullResponse,
|
|
692
|
+
...(usedJudgmentIds.length > 0 ? { metadata: { usedJudgmentIds } } : {}),
|
|
632
693
|
timestamp: new Date().toISOString()
|
|
633
694
|
});
|
|
634
695
|
session.lastUpdated = new Date().toISOString();
|
|
@@ -638,6 +699,12 @@ async function handleV3P2PMessage(parsed, conn, comm) {
|
|
|
638
699
|
catch (saveErr) {
|
|
639
700
|
console.warn(`[v3] 存 assistant 消息失败 (不影响):`, saveErr.message);
|
|
640
701
|
}
|
|
702
|
+
// v3 修复: 同步给 A 自己的 UI — broadcast AI 回复给 A 的 owner 实时看到
|
|
703
|
+
broadcast({
|
|
704
|
+
type: 'ai',
|
|
705
|
+
content: fullResponse,
|
|
706
|
+
channelId
|
|
707
|
+
}, channelId);
|
|
641
708
|
// 3. 把完整回复发给 B
|
|
642
709
|
const reply = JSON.stringify({
|
|
643
710
|
v: 3, op: 'agent.chat.reply',
|
|
@@ -908,6 +975,16 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
908
975
|
process.on('unhandledRejection', (reason, promise) => {
|
|
909
976
|
console.error('[警告] 未处理的 Promise 拒绝:', reason);
|
|
910
977
|
});
|
|
978
|
+
// Bolloon Bootstrap (幂等, 重复调不会重复挂定时器)
|
|
979
|
+
// 这里独立调一次以保证 CLI-only 模式 (无 index.ts 引导) 也能 bootstrap
|
|
980
|
+
try {
|
|
981
|
+
const { bootstrapBolloon } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
982
|
+
const bs = await bootstrapBolloon({ cwd: process.cwd() });
|
|
983
|
+
console.log(`[createWebServer] bootstrap 完成 (${bs.durationMs}ms)`);
|
|
984
|
+
}
|
|
985
|
+
catch (err) {
|
|
986
|
+
console.warn('[createWebServer] bootstrap 失败 (非致命):', err);
|
|
987
|
+
}
|
|
911
988
|
// 重置旧的 agent session,确保使用新的 LLM 配置
|
|
912
989
|
const { resetAgentSession } = await import('../agents/pi-sdk.js');
|
|
913
990
|
resetAgentSession();
|
|
@@ -921,6 +998,50 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
921
998
|
keypair: null
|
|
922
999
|
};
|
|
923
1000
|
let p2pCommunicator = null;
|
|
1001
|
+
// v3: 定期 broadcast — 每个 peer 只收到分享给他的 channel (按 peer 个性化)
|
|
1002
|
+
// 走 known_peers (持久化) + sendTo (自动 joinPeer 重连), 不只 conns
|
|
1003
|
+
// 定义在此处 (所有 try 外部), 确保 route handlers 也能访问
|
|
1004
|
+
const v3BroadcastOwn = async () => {
|
|
1005
|
+
if (!v3P2PRef)
|
|
1006
|
+
return { sent: 0, total: 0 };
|
|
1007
|
+
const channels = await loadChannels();
|
|
1008
|
+
const { listPeers } = await import('../network/known-peers.js');
|
|
1009
|
+
const peers = await listPeers();
|
|
1010
|
+
const myPk = v3P2PRef.getPublicKey();
|
|
1011
|
+
// 2026-06-10: 本机名字一起携带, 对端能直接显示 + 落到自己的 known_peers
|
|
1012
|
+
let myName = process.env.BOLLOON_USER_NAME || process.env.USER || 'node';
|
|
1013
|
+
try {
|
|
1014
|
+
const { readFileSync, existsSync } = await import('fs');
|
|
1015
|
+
const cfgPath = `${process.env.HOME || '/tmp'}/.bolloon/config.json`;
|
|
1016
|
+
if (existsSync(cfgPath)) {
|
|
1017
|
+
const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
|
|
1018
|
+
if (cfg.userName)
|
|
1019
|
+
myName = cfg.userName;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
catch { }
|
|
1023
|
+
let sent = 0;
|
|
1024
|
+
for (const peer of peers) {
|
|
1025
|
+
if (peer.publicKey === myPk)
|
|
1026
|
+
continue;
|
|
1027
|
+
const sharedForPeer = channels
|
|
1028
|
+
.map(ch => sanitizeChannelForPeer(ch, peer.publicKey))
|
|
1029
|
+
.filter((x) => x !== null);
|
|
1030
|
+
if (sharedForPeer.length > 0) {
|
|
1031
|
+
const msg = JSON.stringify({
|
|
1032
|
+
v: 3, op: 'agent.meta.list.reply',
|
|
1033
|
+
payload: { channels: sharedForPeer, name: myName, fromPublicKey: myPk }
|
|
1034
|
+
});
|
|
1035
|
+
const ok = v3P2PRef.sendTo(peer.publicKey, msg);
|
|
1036
|
+
if (ok) {
|
|
1037
|
+
sent++;
|
|
1038
|
+
console.log(`[v3] broadcast: ${peer.name || peer.publicKey.substring(0, 8)} → ${sharedForPeer.length} 个 channel`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
console.log(`[v3] broadcast 完成: sent=${sent}/${peers.length} 个 peer`);
|
|
1043
|
+
return { sent, total: peers.length };
|
|
1044
|
+
};
|
|
924
1045
|
try {
|
|
925
1046
|
console.log('开始生成 P2P 身份...');
|
|
926
1047
|
// 生成 DIAP 身份
|
|
@@ -1017,6 +1138,82 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1017
1138
|
return Promise.resolve();
|
|
1018
1139
|
}
|
|
1019
1140
|
};
|
|
1141
|
+
// v3 新增: 好友申请 RPC — 任何对端可以发, 推到前端 UI 让用户接受
|
|
1142
|
+
if (parsed.op === 'agent.friend.request') {
|
|
1143
|
+
console.log(`[v3-friend] 收到 ${evt.fromPublicKey.substring(0, 12)}... 的好友申请: ${parsed.payload?.name || '(无名字)'}`);
|
|
1144
|
+
broadcast({
|
|
1145
|
+
type: 'friend-request',
|
|
1146
|
+
fromPublicKey: evt.fromPublicKey,
|
|
1147
|
+
fromName: parsed.payload?.name || ('peer-' + evt.fromPublicKey.substring(0, 8)),
|
|
1148
|
+
message: parsed.payload?.message || '想加你为 P2P 好友',
|
|
1149
|
+
requestId: parsed.payload?.requestId, // 2026-06-10: 透传 requestId 给前端
|
|
1150
|
+
timestamp: Date.now()
|
|
1151
|
+
}, 'p2p-global');
|
|
1152
|
+
// 2026-06-10 新增: 立刻发 ack 回给发送方, 让发送方 UI 知道"对方收到了"
|
|
1153
|
+
try {
|
|
1154
|
+
const ackRpc = JSON.stringify({
|
|
1155
|
+
v: 3,
|
|
1156
|
+
op: 'agent.friend.request.ack',
|
|
1157
|
+
payload: {
|
|
1158
|
+
requestId: parsed.payload?.requestId,
|
|
1159
|
+
receivedBy: v3P2PRef?.getPublicKey(),
|
|
1160
|
+
timestamp: Date.now()
|
|
1161
|
+
}
|
|
1162
|
+
});
|
|
1163
|
+
v3P2PRef?.sendTo(evt.fromPublicKey, ackRpc);
|
|
1164
|
+
}
|
|
1165
|
+
catch (err) {
|
|
1166
|
+
console.warn('[v3-friend] 发 ack 失败 (不阻塞):', err.message);
|
|
1167
|
+
}
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
// 2026-06-10 新增: 发送方收到对方 ack → SSE 推前端, 显示"对方已收到"
|
|
1171
|
+
if (parsed.op === 'agent.friend.request.ack') {
|
|
1172
|
+
console.log(`[v3-friend] 收到 ack: requestId=${(parsed.payload?.requestId || '').substring(0, 8)} 来自 ${evt.fromPublicKey.substring(0, 12)}...`);
|
|
1173
|
+
broadcast({
|
|
1174
|
+
type: 'friend-request-ack',
|
|
1175
|
+
requestId: parsed.payload?.requestId,
|
|
1176
|
+
receivedBy: parsed.payload?.receivedBy,
|
|
1177
|
+
timestamp: Date.now()
|
|
1178
|
+
}, 'p2p-global');
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
// v3 修复: agent.meta.list.reply 也走 v3P2PRef.on('data') (因为 handleV3P2PMessage 只走老通道)
|
|
1182
|
+
if (parsed.op === 'agent.meta.list.reply') {
|
|
1183
|
+
const list = parsed.payload?.channels || [];
|
|
1184
|
+
remoteChannelCache.set(evt.fromPublicKey, list);
|
|
1185
|
+
// 2026-06-10: 持久化到 ~/.bolloon/remote-channels-cache.json, 重启后不丢
|
|
1186
|
+
persistRemoteChannelCache();
|
|
1187
|
+
// 2026-06-10: 接收侧记录对方名字 (来自 list.reply payload.name), 落 known_peers
|
|
1188
|
+
const senderName = parsed.payload?.name;
|
|
1189
|
+
if (senderName && typeof senderName === 'string') {
|
|
1190
|
+
import('../network/known-peers.js').then(({ addOrUpdatePeer }) => addOrUpdatePeer(senderName, evt.fromPublicKey)).catch(err => console.warn('[v3] 记录对端名字失败:', err.message));
|
|
1191
|
+
}
|
|
1192
|
+
console.log(`[v3] 收到 ${evt.fromPublicKey.substring(0, 12)}... 的 ${list.length} 个 channel, 已缓存 (sender=${senderName || '?'})`);
|
|
1193
|
+
broadcast({
|
|
1194
|
+
type: 'remote-channel-update',
|
|
1195
|
+
peerId: evt.fromPublicKey,
|
|
1196
|
+
peerName: senderName, // 2026-06-10: 一并带名字到 UI
|
|
1197
|
+
channels: list
|
|
1198
|
+
}, 'p2p-global');
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
// 2026-06-10: 收到对方请求本机的 channel 列表 (启动时主动发请求, 加速 cache 填充)
|
|
1202
|
+
if (parsed.op === 'agent.meta.list.request') {
|
|
1203
|
+
console.log(`[v3-meta] 收到 ${evt.fromPublicKey.substring(0, 12)}... 的 channel 列表请求 → 立刻回包`);
|
|
1204
|
+
// 不能 await (在 on('data') sync 回调里), 改用 .then 异步处理
|
|
1205
|
+
loadChannels().then(channels => {
|
|
1206
|
+
const sharedForPeer = channels
|
|
1207
|
+
.map(ch => sanitizeChannelForPeer(ch, evt.fromPublicKey))
|
|
1208
|
+
.filter((x) => x !== null);
|
|
1209
|
+
const msg = JSON.stringify({
|
|
1210
|
+
v: 3, op: 'agent.meta.list.reply',
|
|
1211
|
+
payload: { channels: sharedForPeer }
|
|
1212
|
+
});
|
|
1213
|
+
v3P2PRef.sendTo(evt.fromPublicKey, msg);
|
|
1214
|
+
}).catch(err => console.warn('[v3-meta] 回应 channel 列表失败:', err.message));
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1020
1217
|
handleV3P2PMessage(parsed, { id: evt.fromPublicKey, publicKey: evt.fromPublicKey }, commShim);
|
|
1021
1218
|
}
|
|
1022
1219
|
}
|
|
@@ -1026,6 +1223,8 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1026
1223
|
});
|
|
1027
1224
|
// 新连接进来 → 主动发我分享给 ta 的 channel 列表
|
|
1028
1225
|
v3P2PRef.on('connection', (evt) => {
|
|
1226
|
+
// 2026-06-10: 喂 watchdog —— 新连接到来是真实业务活动
|
|
1227
|
+
watchdogRef?.recordActivity?.();
|
|
1029
1228
|
setTimeout(async () => {
|
|
1030
1229
|
try {
|
|
1031
1230
|
const channels = await loadChannels();
|
|
@@ -1066,45 +1265,50 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1066
1265
|
}
|
|
1067
1266
|
// 触发一次 broadcast 推送给所有重连的 peer
|
|
1068
1267
|
setTimeout(() => v3BroadcastOwn(), 2000);
|
|
1268
|
+
// 2026-06-10: 同时主动请求每个 known peer 把 ta 的 channel 列表推过来
|
|
1269
|
+
// 避免对面 publicKey 没变但 cache 丢了(本机重启) → 一直空
|
|
1270
|
+
setTimeout(() => requestChannelsFromAllPeers(), 3500);
|
|
1069
1271
|
}
|
|
1070
1272
|
catch (err) {
|
|
1071
1273
|
console.error('[v3] 自动重连失败:', err.message);
|
|
1072
1274
|
}
|
|
1073
1275
|
}, 5000); // 5s 后再重连, 让 swarm 充分 bootstrap
|
|
1276
|
+
// 2026-06-10 新增: 主动向所有 known peer 发起 channel 列表请求
|
|
1277
|
+
async function requestChannelsFromAllPeers() {
|
|
1278
|
+
if (!v3P2PRef)
|
|
1279
|
+
return;
|
|
1280
|
+
try {
|
|
1281
|
+
const { listPeers } = await import('../network/known-peers.js');
|
|
1282
|
+
const peers = await listPeers();
|
|
1283
|
+
const myPk = v3P2PRef.getPublicKey();
|
|
1284
|
+
const req = JSON.stringify({ v: 3, op: 'agent.meta.list.request', payload: { fromPublicKey: myPk } });
|
|
1285
|
+
let sent = 0;
|
|
1286
|
+
for (const peer of peers) {
|
|
1287
|
+
if (peer.publicKey === myPk)
|
|
1288
|
+
continue;
|
|
1289
|
+
// 用 sendToWithWait, 等 conn 就绪再发 (同 Step 5 sendToWithWait 修复)
|
|
1290
|
+
const r = await v3P2PRef.sendToWithWait(peer.publicKey, req, 3000);
|
|
1291
|
+
if (r === 'SENT')
|
|
1292
|
+
sent++;
|
|
1293
|
+
}
|
|
1294
|
+
console.log(`[v3-meta] requestChannelsFromAllPeers → sent=${sent}/${peers.length - 1}`);
|
|
1295
|
+
}
|
|
1296
|
+
catch (err) {
|
|
1297
|
+
console.warn('[v3-meta] requestChannelsFromAllPeers failed:', err.message);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
// 立即跑一次 + 每 30s 兜底 (跟 v3BroadcastOwn 一样的节奏)
|
|
1301
|
+
setTimeout(requestChannelsFromAllPeers, 4000);
|
|
1302
|
+
setInterval(requestChannelsFromAllPeers, 30000);
|
|
1074
1303
|
}
|
|
1075
1304
|
catch (err) {
|
|
1076
1305
|
console.error('[v3] P2PDirect 启动失败:', err.message);
|
|
1077
1306
|
v3P2PRef = null;
|
|
1078
1307
|
}
|
|
1079
|
-
//
|
|
1080
|
-
const v3BroadcastOwn = () => {
|
|
1081
|
-
if (!v3P2PRef)
|
|
1082
|
-
return;
|
|
1083
|
-
loadChannels().then(channels => {
|
|
1084
|
-
const conns = v3P2PRef.conns;
|
|
1085
|
-
if (!conns)
|
|
1086
|
-
return;
|
|
1087
|
-
for (const [peerPk, conn] of conns.entries()) {
|
|
1088
|
-
if (conn?.destroyed)
|
|
1089
|
-
continue;
|
|
1090
|
-
const sharedForPeer = channels
|
|
1091
|
-
.map(ch => sanitizeChannelForPeer(ch, peerPk))
|
|
1092
|
-
.filter((x) => x !== null);
|
|
1093
|
-
if (sharedForPeer.length > 0) {
|
|
1094
|
-
const msg = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: sharedForPeer } });
|
|
1095
|
-
try {
|
|
1096
|
-
conn.write(Buffer.from(msg));
|
|
1097
|
-
}
|
|
1098
|
-
catch { }
|
|
1099
|
-
}
|
|
1100
|
-
}
|
|
1101
|
-
console.log(`[v3] broadcast 个性化: ${conns.size} 个 peer, 各自收到分享的 channel`);
|
|
1102
|
-
}).catch(err => console.error('[v3] broadcast 失败:', err.message));
|
|
1103
|
-
};
|
|
1308
|
+
// 首次广播: 等 swarm bootstrap 完成后推一次
|
|
1104
1309
|
setTimeout(v3BroadcastOwn, 3000);
|
|
1105
|
-
setTimeout
|
|
1106
|
-
|
|
1107
|
-
setTimeout(v3BroadcastOwn, 40000);
|
|
1310
|
+
// v3 修复: 用 setInterval 替代一次性 setTimeout, 确保分享变更后能持续推送给 peer
|
|
1311
|
+
setInterval(v3BroadcastOwn, 30000);
|
|
1108
1312
|
// 保留 @diap/sdk 的旧实例 (它的 Hyperswarm 实例能帮 P2PDirect 做 DHT bootstrap)
|
|
1109
1313
|
try {
|
|
1110
1314
|
const rawSeed = crypto.getRandomValues(new Uint8Array(32));
|
|
@@ -1176,7 +1380,10 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1176
1380
|
const channelId = req.query.channelId;
|
|
1177
1381
|
res.setHeader('Content-Type', 'text/event-stream');
|
|
1178
1382
|
res.setHeader('Cache-Control', 'no-cache');
|
|
1179
|
-
|
|
1383
|
+
// 2026-06-11: 改 keep-alive → close
|
|
1384
|
+
// 原因: SSE 长连接占着 keep-alive 槽 (HTTP/1.1 + 浏览器 max 6 并发), 后续同源 fetch 排队 30s+
|
|
1385
|
+
// 设 close 让浏览器把 SSE 当长期流, 不抢占普通请求的 keep-alive 槽
|
|
1386
|
+
res.setHeader('Connection', 'close');
|
|
1180
1387
|
// 反向代理 (nginx/cloudflair) 需要: 禁用缓冲 + 立即 flush
|
|
1181
1388
|
res.setHeader('X-Accel-Buffering', 'no');
|
|
1182
1389
|
res.flushHeaders();
|
|
@@ -1208,16 +1415,53 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1208
1415
|
const realChannelName = channel?.name || '';
|
|
1209
1416
|
const realChannelDidDoc = channel?.didDocRef;
|
|
1210
1417
|
broadcast({ type: 'user', content: text }, channelId);
|
|
1418
|
+
// 2026-06-11: /message 端点立即返回 202, LLM 后续处理挪到 setImmediate 后台跑
|
|
1419
|
+
// 之前 res.json 在 try 块末尾 (line 1815), 需要等 LLM (5-15s) + 落盘 + suggestRename (5-8s) = 13s+
|
|
1420
|
+
// 客户端 fetch 占用 13s, 视觉像"卡死", 切其他 channel 也感觉"无法加载"
|
|
1421
|
+
// 修法: 立即 res.json(202), try 块主体仍跑 (LLM 流 + 落盘) 但不阻塞 HTTP 响应
|
|
1422
|
+
// 关键: res.json 之后不能再调用 res.json (会抛 ERR_HTTP_HEADERS_SENT), 所以 try 块末尾的 res.json 必须用 res.headersSent 守卫
|
|
1423
|
+
res.status(202).json({ ok: true, async: true, channelId, sessionId: currentSessionId });
|
|
1424
|
+
console.log(`[v3-async] /message 立即返回 202, channel=${channelId}, text length=${text.length}`);
|
|
1211
1425
|
// 提前捕获 wallet/autoTools 到本地变量, 避免下面 try 块内的 inner const channel
|
|
1212
1426
|
// (line ~638) 与这里外层的 const channel 形成 shadowing 让 TS 误报"使用前未声明"
|
|
1213
1427
|
const boundWalletAddress = channel?.walletAddress;
|
|
1214
1428
|
const autoToolsEnabled = channel?.autoInvokeTools !== false; // 默认开启
|
|
1215
1429
|
// 捕获外层 channel 到独立变量, 避免被 try 块内 (line 740+) 的 const channel 遮蔽
|
|
1216
1430
|
const channelForJudgment = channel;
|
|
1431
|
+
// per-channel queue 检查: 已在跑就入队, 等当前跑完自动接上
|
|
1432
|
+
const runState = getOrCreateRunState(channelId);
|
|
1433
|
+
if (runState.running) {
|
|
1434
|
+
runState.queue.push({ channelId, text, boundWalletAddress, autoToolsEnabled });
|
|
1435
|
+
broadcastQueueUpdate(channelId);
|
|
1436
|
+
console.log(`[queue] /message 入队 channel=${channelId}, queue len=${runState.queue.length}`);
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
1439
|
+
runState.running = true;
|
|
1440
|
+
runState.abortController = new AbortController();
|
|
1441
|
+
broadcastQueueUpdate(channelId);
|
|
1217
1442
|
try {
|
|
1218
1443
|
const agent = await getAgentForChannel(channelId, realChannelDid, realChannelName, realChannelDidDoc);
|
|
1219
1444
|
let fullResponse = '';
|
|
1445
|
+
// P0.5: 注入门回传的 usedIds, 落 session message metadata, UI 可查
|
|
1446
|
+
let usedJudgmentIds = [];
|
|
1220
1447
|
const streamCallback = (event) => {
|
|
1448
|
+
// P0.5: 捕获注入门回传
|
|
1449
|
+
if (event.type === 'used_judgments' && Array.isArray(event.usedIds)) {
|
|
1450
|
+
usedJudgmentIds = event.usedIds;
|
|
1451
|
+
// 同步推给前端 (用于 finalizeTimelineAsMessage 时给 addMessage 传 usedIds)
|
|
1452
|
+
broadcast({ type: 'used_judgments', usedIds: usedJudgmentIds }, channelId);
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
// 阶段事件 (注入门 / D 触发)
|
|
1456
|
+
if (event.type === 'phase') {
|
|
1457
|
+
broadcast({
|
|
1458
|
+
type: 'phase',
|
|
1459
|
+
phase: event.phase,
|
|
1460
|
+
detail: event.detail,
|
|
1461
|
+
usedCount: event.usedCount,
|
|
1462
|
+
}, channelId);
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1221
1465
|
// 同时发送给流式显示和工作流显示
|
|
1222
1466
|
if (event.type === 'token' || event.type === 'thinking') {
|
|
1223
1467
|
broadcast({ type: 'stream', streamType: event.type, content: event.content }, channelId);
|
|
@@ -1256,6 +1500,107 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1256
1500
|
const judgmentHint = await buildJudgmentHint(channelForJudgment, channelId);
|
|
1257
1501
|
if (judgmentHint)
|
|
1258
1502
|
contextHint += judgmentHint;
|
|
1503
|
+
// 2026-06-10: 注入 skills 列表 (本机 ~/.bolloon/skills/ 下所有 skills)
|
|
1504
|
+
// 让 LLM 知道有哪些 skill 可用, 在回复中提示用户
|
|
1505
|
+
try {
|
|
1506
|
+
const { loadSkillsFromPaths, defaultSkillPaths, describeSkill } = await import('../agents/skill-loader.js');
|
|
1507
|
+
const paths = defaultSkillPaths();
|
|
1508
|
+
const skills = await loadSkillsFromPaths(paths);
|
|
1509
|
+
if (skills.length > 0) {
|
|
1510
|
+
contextHint += `[系统上下文] 本机已加载的 skills (${skills.length} 个, 你可以提示用户主动调用):\n`;
|
|
1511
|
+
for (const s of skills.slice(0, 20)) { // 上限 20 避免 prompt 过长
|
|
1512
|
+
const desc = (s.description || '').slice(0, 80);
|
|
1513
|
+
contextHint += ` - /${s.name}${desc ? ' — ' + desc : ''}\n`;
|
|
1514
|
+
}
|
|
1515
|
+
contextHint += '调用语法: 用户说 "/技能名 ..." 或 你回复时建议 "/技能名 ..." 让用户主动触发.\n\n';
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
catch (err) {
|
|
1519
|
+
// 静默失败 — skills 不是核心, 加载失败不阻塞
|
|
1520
|
+
}
|
|
1521
|
+
// 2026-06-10: 注入 human values 摘要 (最常用的 judgment / 价值偏好)
|
|
1522
|
+
// 与 judgment 不同: values 是更宏观的"用户偏好", judgment 是针对具体决策的约束
|
|
1523
|
+
try {
|
|
1524
|
+
const { loadAllJudgments } = await import('../pi-ecosystem-judgment/human-value-store.js');
|
|
1525
|
+
const allJudgments = await loadAllJudgments().catch(() => []);
|
|
1526
|
+
// 把所有 judgment 视作软参考 (跟 buildJudgmentHint 的 candidates 同理)
|
|
1527
|
+
if (Array.isArray(allJudgments) && allJudgments.length > 0) {
|
|
1528
|
+
contextHint += `[系统上下文] 用户的核心价值倾向 (来自 ${allJudgments.length} 条历史 judgment, 软参考, 体现而非复述):\n`;
|
|
1529
|
+
for (const j of allJudgments.slice(0, 8)) {
|
|
1530
|
+
const decision = (j.decision || '').slice(0, 80);
|
|
1531
|
+
contextHint += ` - ${decision}\n`;
|
|
1532
|
+
}
|
|
1533
|
+
contextHint += '\n';
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
catch (err) {
|
|
1537
|
+
// 静默失败
|
|
1538
|
+
}
|
|
1539
|
+
// 2026-06-10: 注入 documents 列表 (本机 documents/ 目录的文档元数据)
|
|
1540
|
+
// 让 LLM 知道有文档存在, 用户可主动要求读
|
|
1541
|
+
try {
|
|
1542
|
+
const { documentStore } = await import('../documents/store.js');
|
|
1543
|
+
const docs = await documentStore.getReceivedDocuments(50).catch(() => []);
|
|
1544
|
+
if (Array.isArray(docs) && docs.length > 0) {
|
|
1545
|
+
contextHint += `[系统上下文] 本机 documents (${docs.length} 篇, 用户可让你读):\n`;
|
|
1546
|
+
for (const d of docs.slice(0, 10)) {
|
|
1547
|
+
const name = d.fileName || d.id || '(未命名)';
|
|
1548
|
+
const size = d.fileSize ? ` (${Math.round(d.fileSize / 1024)}KB)` : '';
|
|
1549
|
+
const sender = d.fromNodeId ? ` [来自 ${d.fromNodeIdShort || d.fromNodeId.substring(0, 8)}…]` : '';
|
|
1550
|
+
contextHint += ` - ${name}${size}${sender}\n`;
|
|
1551
|
+
}
|
|
1552
|
+
contextHint += '用户提到某文档时, 你可以调用读文档工具读取并总结.\n\n';
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
catch (err) {
|
|
1556
|
+
// 静默失败
|
|
1557
|
+
}
|
|
1558
|
+
// 2026-06-11: 注入此 channel 专属的 persona + 关联文档 (从 channel 字段读, LLM 长期记忆)
|
|
1559
|
+
const chPersona = channelForJudgment?.persona;
|
|
1560
|
+
if (chPersona && typeof chPersona === 'object') {
|
|
1561
|
+
contextHint += '[系统上下文] 此 channel 的人设 (你是这个角色):\n';
|
|
1562
|
+
if (chPersona.name)
|
|
1563
|
+
contextHint += ` 名字: ${chPersona.name}\n`;
|
|
1564
|
+
if (chPersona.description)
|
|
1565
|
+
contextHint += ` 描述: ${chPersona.description}\n`;
|
|
1566
|
+
if (chPersona.personality)
|
|
1567
|
+
contextHint += ` 性格: ${chPersona.personality}\n`;
|
|
1568
|
+
if (chPersona.greeting)
|
|
1569
|
+
contextHint += ` 问候: ${chPersona.greeting}\n`;
|
|
1570
|
+
if (Array.isArray(chPersona.capabilities) && chPersona.capabilities.length > 0) {
|
|
1571
|
+
contextHint += ` 能力: ${chPersona.capabilities.join('、')}\n`;
|
|
1572
|
+
}
|
|
1573
|
+
if (Array.isArray(chPersona.interests) && chPersona.interests.length > 0) {
|
|
1574
|
+
contextHint += ` 兴趣: ${chPersona.interests.join('、')}\n`;
|
|
1575
|
+
}
|
|
1576
|
+
contextHint += '回复时应自然体现这个角色 (不要硬搬原文, 像这个角色说话即可).\n\n';
|
|
1577
|
+
}
|
|
1578
|
+
const linkedIds = channelForJudgment?.linkedDocumentIds;
|
|
1579
|
+
if (Array.isArray(linkedIds) && linkedIds.length > 0) {
|
|
1580
|
+
try {
|
|
1581
|
+
const { documentStore } = await import('../documents/store.js');
|
|
1582
|
+
contextHint += `[系统上下文] 此 channel 关联了 ${linkedIds.length} 篇文档 (已自动加载内容, 你应基于它们回答):\n`;
|
|
1583
|
+
let loaded = 0;
|
|
1584
|
+
for (const docId of linkedIds.slice(0, 10)) {
|
|
1585
|
+
const doc = await documentStore.readDocument(docId).catch(() => null);
|
|
1586
|
+
if (!doc)
|
|
1587
|
+
continue;
|
|
1588
|
+
const name = doc.metadata?.fileName || docId;
|
|
1589
|
+
const content = (doc.content || '').slice(0, 1500); // 单篇 1.5KB 上限, 总 prompt 防爆
|
|
1590
|
+
contextHint += `\n--- 文档: ${name} ---\n${content}\n--- 文档结束 ---\n`;
|
|
1591
|
+
loaded++;
|
|
1592
|
+
}
|
|
1593
|
+
if (loaded === 0) {
|
|
1594
|
+
contextHint += `(但加载失败, 文档可能已被删除)\n\n`;
|
|
1595
|
+
}
|
|
1596
|
+
else {
|
|
1597
|
+
contextHint += '\n';
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
catch (err) {
|
|
1601
|
+
console.warn('[v3-persona] 加载关联文档失败 (非致命):', err.message);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1259
1604
|
// v3 新增: 注入"可用渠道"目录, 让 LLM 知道可以 @-mention 哪些 channel
|
|
1260
1605
|
// - 本地 channels (除了自己)
|
|
1261
1606
|
// - 远端 channels (remoteChannelCache 缓存的)
|
|
@@ -1274,11 +1619,34 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1274
1619
|
for (const c of remoteChannels) {
|
|
1275
1620
|
contextHint += ` - [远端, owner=${(c._ownerPublicKey || '').substring(0, 8)}…] @${c.name} (id=${c.id})\n`;
|
|
1276
1621
|
}
|
|
1277
|
-
contextHint += '语法: 当你想给其他渠道发消息, 在回复中写 "@渠道名 我要说的话" 即可. 消息会持久化到目标 channel 的 session, 你之后能看到"自己"在那里说的话.\n
|
|
1622
|
+
contextHint += '语法: 当你想给其他渠道发消息, 在回复中写 "@渠道名 我要说的话" 即可. 消息会持久化到目标 channel 的 session, 你之后能看到"自己"在那里说的话.\n';
|
|
1623
|
+
// 2026-06-10 强化: 当用户消息里出现 @渠道名, 默认是请你代为转发, 务必在回复里包含对应的 @ 转发
|
|
1624
|
+
if (remoteChannels.length > 0) {
|
|
1625
|
+
contextHint += '重要: 上面列表里 [远端] 标记的 channel 在另一台机器上, 你可以像 @本地 channel 一样 @ 它们 — 我会通过 P2P 自动把消息送达对方智能体, 对方智能体的回复也会同步回来.\n';
|
|
1626
|
+
contextHint += '当用户在消息里 @ 了某个 (本地或远端) channel, 默认意图是希望你代为转发 — 你应该在回复中写出对应的 "@渠道名 转发内容", 否则用户的请求不会被路由出去.\n\n';
|
|
1627
|
+
}
|
|
1628
|
+
else {
|
|
1629
|
+
contextHint += '\n';
|
|
1630
|
+
}
|
|
1278
1631
|
}
|
|
1279
1632
|
if (contextHint)
|
|
1280
1633
|
contextHint += '\n';
|
|
1281
|
-
|
|
1634
|
+
try {
|
|
1635
|
+
fullResponse = await agent.promptStream(contextHint + text, streamCallback, runState.abortController?.signal, channelId);
|
|
1636
|
+
}
|
|
1637
|
+
catch (err) {
|
|
1638
|
+
// abort 抛错: 保留已输出的部分 (fullResponse 可能是空字符串)
|
|
1639
|
+
if (runState.abortController?.signal.aborted || err?.name === 'AbortError') {
|
|
1640
|
+
console.log(`[chat] aborted channel=${channelId}`);
|
|
1641
|
+
}
|
|
1642
|
+
else {
|
|
1643
|
+
throw err;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
// abort 模式: 给 partial 拼后缀
|
|
1647
|
+
if (runState.abortController?.signal.aborted && fullResponse.trim().length > 0) {
|
|
1648
|
+
fullResponse = fullResponse + '\n\n_[生成已中断]_';
|
|
1649
|
+
}
|
|
1282
1650
|
// v3 新增: 解析 LLM 回复里的 @-mentions, 转发到目标 channel
|
|
1283
1651
|
await routeMentionsInReply(channelId, fullResponse, localChannels, remoteChannels);
|
|
1284
1652
|
broadcast({ type: 'ai', content: fullResponse }, channelId);
|
|
@@ -1287,30 +1655,85 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1287
1655
|
session.sessionId = currentSessionId;
|
|
1288
1656
|
// v3: 加 source 标记 (local = 内部 owner, remote = 远端访客)
|
|
1289
1657
|
session.messages.push({ id: crypto.randomUUID(), type: 'user', content: text, timestamp: new Date().toISOString(), source: 'local' });
|
|
1290
|
-
session.messages.push({
|
|
1658
|
+
session.messages.push({
|
|
1659
|
+
id: crypto.randomUUID(),
|
|
1660
|
+
type: 'ai',
|
|
1661
|
+
content: fullResponse,
|
|
1662
|
+
timestamp: new Date().toISOString(),
|
|
1663
|
+
source: 'local',
|
|
1664
|
+
// P0.5: 这条 AI 回复引用了哪些 judgment (注入门回传)
|
|
1665
|
+
...(usedJudgmentIds.length > 0 ? { metadata: { usedJudgmentIds } } : {}),
|
|
1666
|
+
});
|
|
1291
1667
|
session.lastUpdated = new Date().toISOString();
|
|
1292
1668
|
await saveSession(session);
|
|
1293
1669
|
const channels = await loadChannels();
|
|
1294
1670
|
const channel = channels.find(c => c.id === channelId);
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
channel.name = renameSuggestion;
|
|
1299
|
-
await saveChannels(channels);
|
|
1300
|
-
broadcast({ type: 'renamed', channelId, newName: renameSuggestion }, channelId);
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1671
|
+
// 2026-06-11: 移除 suggestRename 的二次 LLM 调用 — 之前每次用户发消息, 智能体 channel 都会再调一次 LLM (5-8s) 自动改名
|
|
1672
|
+
// 影响: (1) /message 端点被拖慢 5-8s (2) LLM 客户端排队, 其他 channel 跟着卡
|
|
1673
|
+
// 现在改名逻辑挪到 /api/agent-rename 端点, 用户主动触发才跑
|
|
1303
1674
|
if (channel) {
|
|
1304
1675
|
channel.updatedAt = new Date().toISOString();
|
|
1305
1676
|
await saveChannels(channels);
|
|
1306
1677
|
}
|
|
1307
1678
|
broadcast({ type: 'done' }, channelId);
|
|
1308
|
-
|
|
1679
|
+
// D 触发: AI 被动捕获判断力 (后台异步, 不阻塞主对话)
|
|
1680
|
+
setImmediate(() => {
|
|
1681
|
+
try {
|
|
1682
|
+
const lastTurns = session.messages.slice(-6).map((m) => ({
|
|
1683
|
+
role: (m.type === 'user' ? 'human' : 'agent'),
|
|
1684
|
+
content: m.content,
|
|
1685
|
+
}));
|
|
1686
|
+
if (lastTurns.length < 2)
|
|
1687
|
+
return;
|
|
1688
|
+
broadcast({ type: 'phase', phase: 'd_detect', detail: '监测对话...' }, channelId);
|
|
1689
|
+
import('../pi-ecosystem-judgment/human-value-pipeline.js')
|
|
1690
|
+
.then(async ({ detectAndDistillFromChannel, throttleDHook }) => {
|
|
1691
|
+
// channel 维度 5min 节流, 防对话卡顿时 LLM 反复触发
|
|
1692
|
+
if (!throttleDHook(channelId, 5 * 60_000)) {
|
|
1693
|
+
console.log(`[D-hook ${channelId}] throttled (within 5min)`);
|
|
1694
|
+
broadcast({ type: 'phase', phase: 'd_skip', detail: 'throttled' }, channelId);
|
|
1695
|
+
return null;
|
|
1696
|
+
}
|
|
1697
|
+
broadcast({ type: 'phase', phase: 'd_distill', detail: '蒸馏判断力...' }, channelId);
|
|
1698
|
+
return detectAndDistillFromChannel(lastTurns, { channelId });
|
|
1699
|
+
})
|
|
1700
|
+
.then((result) => {
|
|
1701
|
+
if (result && result.triggered) {
|
|
1702
|
+
console.log(`[D-hook ${channelId}] stored: ${result.reason}`, result.evolved);
|
|
1703
|
+
broadcast({ type: 'phase', phase: 'd_done', detail: result.reason }, channelId);
|
|
1704
|
+
}
|
|
1705
|
+
else if (result && result.reason) {
|
|
1706
|
+
console.log(`[D-hook ${channelId}] skipped: ${result.reason}`);
|
|
1707
|
+
broadcast({ type: 'phase', phase: 'd_skip', detail: result.reason }, channelId);
|
|
1708
|
+
}
|
|
1709
|
+
})
|
|
1710
|
+
.catch((err) => {
|
|
1711
|
+
console.warn(`[D-hook ${channelId}] failed:`, err);
|
|
1712
|
+
broadcast({ type: 'phase', phase: 'd_error', detail: String(err) }, channelId);
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
catch (err) {
|
|
1716
|
+
console.warn(`[D-hook ${channelId}] sync error:`, err);
|
|
1717
|
+
}
|
|
1718
|
+
});
|
|
1719
|
+
// 2026-06-11: 202 已发的话, 不要重复 res.json (会抛 ERR_HTTP_HEADERS_SENT)
|
|
1720
|
+
if (!res.headersSent)
|
|
1721
|
+
res.json({ ok: true });
|
|
1309
1722
|
}
|
|
1310
1723
|
catch (err) {
|
|
1311
1724
|
broadcast({ type: 'error', content: err.message }, channelId);
|
|
1312
1725
|
broadcast({ type: 'done' }, channelId);
|
|
1313
|
-
res.
|
|
1726
|
+
if (!res.headersSent)
|
|
1727
|
+
res.status(500).json({ error: err.message });
|
|
1728
|
+
}
|
|
1729
|
+
finally {
|
|
1730
|
+
// queue dequeue: 跑完或失败都要清状态
|
|
1731
|
+
// 当前实现: 自动接下一条需要把 ~200 行 try 块抽函数, 暂不抽.
|
|
1732
|
+
// 替代: 用户点 [队列 +N] 按钮时, 客户端发起一个特殊的 HTTP 请求触发下一条
|
|
1733
|
+
// (在 client.js 实现). 这里只清状态 + 广播.
|
|
1734
|
+
runState.running = false;
|
|
1735
|
+
runState.abortController = null;
|
|
1736
|
+
broadcastQueueUpdate(channelId);
|
|
1314
1737
|
}
|
|
1315
1738
|
});
|
|
1316
1739
|
// ---------- 频道元数据后台修复队列 ----------
|
|
@@ -1320,6 +1743,24 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1320
1743
|
const didFixQueue = new Set(); // 待修复的 channelId
|
|
1321
1744
|
let didFixRunning = false;
|
|
1322
1745
|
let didFixTimer = null;
|
|
1746
|
+
const channelRunState = new Map();
|
|
1747
|
+
function getOrCreateRunState(channelId) {
|
|
1748
|
+
let s = channelRunState.get(channelId);
|
|
1749
|
+
if (!s) {
|
|
1750
|
+
s = { running: false, queue: [], abortController: null };
|
|
1751
|
+
channelRunState.set(channelId, s);
|
|
1752
|
+
}
|
|
1753
|
+
return s;
|
|
1754
|
+
}
|
|
1755
|
+
function broadcastQueueUpdate(channelId) {
|
|
1756
|
+
const s = channelRunState.get(channelId);
|
|
1757
|
+
const queueLength = s ? s.queue.length : 0;
|
|
1758
|
+
const running = s ? s.running : false;
|
|
1759
|
+
try {
|
|
1760
|
+
broadcast({ type: 'queue_update', channelId, queueLength, running }, channelId);
|
|
1761
|
+
}
|
|
1762
|
+
catch { /* */ }
|
|
1763
|
+
}
|
|
1323
1764
|
function scheduleDidFix(channelId) {
|
|
1324
1765
|
didFixQueue.add(channelId);
|
|
1325
1766
|
if (didFixTimer)
|
|
@@ -1439,8 +1880,21 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1439
1880
|
app.get('/api/remote-channels', async (_req, res) => {
|
|
1440
1881
|
try {
|
|
1441
1882
|
const out = [];
|
|
1883
|
+
// 2026-06-11: 合并 known_peers + cache, 避免 cache 空时 UI 一个 peer 都看不到
|
|
1884
|
+
// (cache 是纯内存, 重启即丢; known_peers 持久化, 至少能让 UI 显示"这些 peer 我认识")
|
|
1885
|
+
const { listPeers } = await import('../network/known-peers.js');
|
|
1886
|
+
const knownPeers = await listPeers();
|
|
1887
|
+
const knownByPk = new Map();
|
|
1888
|
+
for (const p of knownPeers)
|
|
1889
|
+
knownByPk.set(p.publicKey, { name: p.name });
|
|
1442
1890
|
for (const [peerId, list] of remoteChannelCache.entries()) {
|
|
1443
|
-
out.push({ peerId, channels: list });
|
|
1891
|
+
out.push({ peerId, channels: list, peerName: knownByPk.get(peerId)?.name });
|
|
1892
|
+
}
|
|
1893
|
+
// known_peers 里但 cache 没的, 占位推进 out (channels=[]) 让 UI 能渲染 peer header
|
|
1894
|
+
for (const [peerId, info] of knownByPk.entries()) {
|
|
1895
|
+
if (!remoteChannelCache.has(peerId)) {
|
|
1896
|
+
out.push({ peerId, channels: [], peerName: info.name });
|
|
1897
|
+
}
|
|
1444
1898
|
}
|
|
1445
1899
|
res.json({ count: out.length, peers: out });
|
|
1446
1900
|
}
|
|
@@ -1448,6 +1902,27 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1448
1902
|
res.status(500).json({ error: err.message });
|
|
1449
1903
|
}
|
|
1450
1904
|
});
|
|
1905
|
+
// v3 测试专用: 直接注入远端频道缓存 (绕过 P2P)
|
|
1906
|
+
// 仅当 NODE_ENV=test 时可用
|
|
1907
|
+
app.post('/api/test/inject-remote-channel', async (req, res) => {
|
|
1908
|
+
if (process.env.NODE_ENV !== 'test') {
|
|
1909
|
+
return res.status(403).json({ error: 'only available in test mode' });
|
|
1910
|
+
}
|
|
1911
|
+
try {
|
|
1912
|
+
const { peerPublicKey, channel } = req.body || {};
|
|
1913
|
+
if (!peerPublicKey || !channel) {
|
|
1914
|
+
return res.status(400).json({ error: 'peerPublicKey and channel required' });
|
|
1915
|
+
}
|
|
1916
|
+
const list = remoteChannelCache.get(peerPublicKey) || [];
|
|
1917
|
+
list.push(channel);
|
|
1918
|
+
remoteChannelCache.set(peerPublicKey, list);
|
|
1919
|
+
broadcast({ type: 'remote-channel-update', peerId: peerPublicKey, channels: list }, 'p2p-global');
|
|
1920
|
+
res.json({ ok: true, count: list.length });
|
|
1921
|
+
}
|
|
1922
|
+
catch (err) {
|
|
1923
|
+
res.status(500).json({ error: err.message });
|
|
1924
|
+
}
|
|
1925
|
+
});
|
|
1451
1926
|
// v3: 主动向所有已连接 P2P peer 拉 channel 列表
|
|
1452
1927
|
// 用法: B 端用户点 "刷新远端智能体" → 触发本 endpoint
|
|
1453
1928
|
app.post('/api/remote-channels/refresh', async (_req, res) => {
|
|
@@ -1521,7 +1996,7 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1521
1996
|
});
|
|
1522
1997
|
app.post('/channels', async (req, res) => {
|
|
1523
1998
|
try {
|
|
1524
|
-
const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
|
|
1999
|
+
const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids, personaOverride, linkedDocumentIds } = req.body;
|
|
1525
2000
|
console.log(`[创建频道] 收到请求: name=${name}, agentId=${agentId}, wallet=${walletAddress ? 'yes' : 'no'}, boundJudgments=${Array.isArray(bound_judgment_ids) ? bound_judgment_ids.length : 0}`);
|
|
1526
2001
|
if (!name || !agentId) {
|
|
1527
2002
|
return res.status(400).json({ error: 'name and agentId required' });
|
|
@@ -1534,6 +2009,42 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1534
2009
|
const safeBoundIds = Array.isArray(bound_judgment_ids)
|
|
1535
2010
|
? bound_judgment_ids.filter((x) => typeof x === 'string' && x.length > 0)
|
|
1536
2011
|
: [];
|
|
2012
|
+
// 2026-06-11: persona 加载 — 优先用 personaOverride, 否则从 ~/.bolloon/persona.json 读全局默认
|
|
2013
|
+
let channelPersona;
|
|
2014
|
+
if (personaOverride && typeof personaOverride === 'object') {
|
|
2015
|
+
channelPersona = {
|
|
2016
|
+
name: personaOverride.name,
|
|
2017
|
+
description: personaOverride.description,
|
|
2018
|
+
personality: personaOverride.personality,
|
|
2019
|
+
greeting: personaOverride.greeting,
|
|
2020
|
+
capabilities: Array.isArray(personaOverride.capabilities) ? personaOverride.capabilities.slice(0, 20) : undefined,
|
|
2021
|
+
interests: Array.isArray(personaOverride.interests) ? personaOverride.interests.slice(0, 20) : undefined,
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
else {
|
|
2025
|
+
try {
|
|
2026
|
+
const { readFileSync, existsSync } = await import('fs');
|
|
2027
|
+
const personaPath = `${process.env.HOME || '/tmp'}/.bolloon/persona.json`;
|
|
2028
|
+
if (existsSync(personaPath)) {
|
|
2029
|
+
const p = JSON.parse(readFileSync(personaPath, 'utf-8'));
|
|
2030
|
+
channelPersona = {
|
|
2031
|
+
name: p.name,
|
|
2032
|
+
description: p.description,
|
|
2033
|
+
personality: p.personality,
|
|
2034
|
+
greeting: p.greeting,
|
|
2035
|
+
capabilities: Array.isArray(p.capabilities) ? p.capabilities.slice(0, 20) : undefined,
|
|
2036
|
+
interests: Array.isArray(p.interests) ? p.interests.slice(0, 20) : undefined,
|
|
2037
|
+
};
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
catch (err) {
|
|
2041
|
+
console.warn('[创建频道] 加载 persona.json 失败 (非致命):', err.message);
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
// 过滤 linkedDocumentIds: 只保留 string
|
|
2045
|
+
const safeLinkedDocIds = Array.isArray(linkedDocumentIds)
|
|
2046
|
+
? linkedDocumentIds.filter((x) => typeof x === 'string' && x.length > 0).slice(0, 50)
|
|
2047
|
+
: [];
|
|
1537
2048
|
// 先创建频道(不阻塞等待 DID 生成)
|
|
1538
2049
|
const channel = {
|
|
1539
2050
|
id,
|
|
@@ -1546,6 +2057,8 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1546
2057
|
walletRegisteredAt: validWallet ? new Date().toISOString() : undefined,
|
|
1547
2058
|
autoInvokeTools: autoInvokeTools !== false, // 默认 true
|
|
1548
2059
|
bound_judgment_ids: safeBoundIds,
|
|
2060
|
+
persona: channelPersona,
|
|
2061
|
+
linkedDocumentIds: safeLinkedDocIds,
|
|
1549
2062
|
sessions: [{
|
|
1550
2063
|
id: `sess_${Date.now()}`,
|
|
1551
2064
|
createdAt: new Date().toISOString(),
|
|
@@ -1704,7 +2217,7 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1704
2217
|
app.patch('/channels/:channelId', async (req, res) => {
|
|
1705
2218
|
try {
|
|
1706
2219
|
const { channelId } = req.params;
|
|
1707
|
-
const { name, walletAddress, autoInvokeTools, bound_judgment_ids, shared_with_peers } = req.body;
|
|
2220
|
+
const { name, walletAddress, autoInvokeTools, bound_judgment_ids, shared_with_peers, persona, linkedDocumentIds } = req.body;
|
|
1708
2221
|
const channels = await loadChannels();
|
|
1709
2222
|
const channel = channels.find(c => c.id === channelId);
|
|
1710
2223
|
if (!channel) {
|
|
@@ -1713,6 +2226,26 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1713
2226
|
if (typeof name === 'string' && name.trim()) {
|
|
1714
2227
|
channel.name = name.trim();
|
|
1715
2228
|
}
|
|
2229
|
+
// 2026-06-11: 改 persona (允许 null 重置回全局默认)
|
|
2230
|
+
if (persona !== undefined) {
|
|
2231
|
+
if (persona === null) {
|
|
2232
|
+
channel.persona = undefined;
|
|
2233
|
+
}
|
|
2234
|
+
else if (typeof persona === 'object') {
|
|
2235
|
+
channel.persona = {
|
|
2236
|
+
name: persona.name,
|
|
2237
|
+
description: persona.description,
|
|
2238
|
+
personality: persona.personality,
|
|
2239
|
+
greeting: persona.greeting,
|
|
2240
|
+
capabilities: Array.isArray(persona.capabilities) ? persona.capabilities.slice(0, 20) : channel.persona?.capabilities,
|
|
2241
|
+
interests: Array.isArray(persona.interests) ? persona.interests.slice(0, 20) : channel.persona?.interests,
|
|
2242
|
+
};
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
// 2026-06-11: 改关联文档列表 (数组整体替换, 空数组 = 解绑所有)
|
|
2246
|
+
if (Array.isArray(linkedDocumentIds)) {
|
|
2247
|
+
channel.linkedDocumentIds = linkedDocumentIds.filter((x) => typeof x === 'string' && x.length > 0).slice(0, 50);
|
|
2248
|
+
}
|
|
1716
2249
|
// walletAddress 允许 null/'' 来解绑
|
|
1717
2250
|
if (walletAddress !== undefined) {
|
|
1718
2251
|
if (walletAddress === null || walletAddress === '') {
|
|
@@ -1765,6 +2298,10 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1765
2298
|
}
|
|
1766
2299
|
channel.updatedAt = new Date().toISOString();
|
|
1767
2300
|
await saveChannels(channels);
|
|
2301
|
+
// v3 修复: 分享变更后立即广播给所有 peer, 不用等对方手动刷新
|
|
2302
|
+
if (shared_with_peers !== undefined) {
|
|
2303
|
+
v3BroadcastOwn().catch(err => console.error('[v3] broadcast after share update failed:', err));
|
|
2304
|
+
}
|
|
1768
2305
|
res.json(channel);
|
|
1769
2306
|
}
|
|
1770
2307
|
catch (err) {
|
|
@@ -1913,7 +2450,13 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1913
2450
|
broadcast({ type: 'regenerating', channelId }, channelId);
|
|
1914
2451
|
const agent = await getAgentForChannel(channelId, realChannelDid, realChannelName, realChannelDidDoc);
|
|
1915
2452
|
let fullResponse = '';
|
|
2453
|
+
let usedJudgmentIds = [];
|
|
1916
2454
|
const streamCallback = (event) => {
|
|
2455
|
+
// P0.5: 注入门回传
|
|
2456
|
+
if (event.type === 'used_judgments' && Array.isArray(event.usedIds)) {
|
|
2457
|
+
usedJudgmentIds = event.usedIds;
|
|
2458
|
+
return;
|
|
2459
|
+
}
|
|
1917
2460
|
if (event.type === 'token' || event.type === 'thinking') {
|
|
1918
2461
|
broadcast({ type: 'stream', streamType: event.type, content: event.content }, channelId);
|
|
1919
2462
|
}
|
|
@@ -1926,7 +2469,7 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1926
2469
|
};
|
|
1927
2470
|
// 重新生成时只发送用户消息 (v3: 同时注入 channel 绑定的判断力)
|
|
1928
2471
|
const regenHint = await buildJudgmentHint(channel, channelId);
|
|
1929
|
-
fullResponse = await agent.promptStream(regenHint + userMessage, streamCallback);
|
|
2472
|
+
fullResponse = await agent.promptStream(regenHint + userMessage, streamCallback, undefined, channelId);
|
|
1930
2473
|
broadcast({ type: 'ai', content: fullResponse }, channelId);
|
|
1931
2474
|
// 更新 session
|
|
1932
2475
|
const existingSession = await loadSession(channelId, currentSessionId);
|
|
@@ -1940,7 +2483,8 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
1940
2483
|
id: crypto.randomUUID(),
|
|
1941
2484
|
type: 'ai',
|
|
1942
2485
|
content: fullResponse,
|
|
1943
|
-
timestamp: new Date().toISOString()
|
|
2486
|
+
timestamp: new Date().toISOString(),
|
|
2487
|
+
...(usedJudgmentIds.length > 0 ? { metadata: { usedJudgmentIds } } : {}),
|
|
1944
2488
|
});
|
|
1945
2489
|
existingSession.lastUpdated = new Date().toISOString();
|
|
1946
2490
|
await saveSession(existingSession);
|
|
@@ -2427,13 +2971,26 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
2427
2971
|
res.status(500).json({ error: err.message });
|
|
2428
2972
|
}
|
|
2429
2973
|
});
|
|
2430
|
-
// v3: 暴露 P2PDirect 自己的 publicKey
|
|
2974
|
+
// v3: 暴露 P2PDirect 自己的 publicKey + 本机名字, 对方可用它主动 connect 并自动取名
|
|
2431
2975
|
app.get('/api/p2p-publickey', async (_req, res) => {
|
|
2432
2976
|
try {
|
|
2433
2977
|
if (!v3P2PRef) {
|
|
2434
2978
|
return res.status(503).json({ error: 'P2PDirect not started' });
|
|
2435
2979
|
}
|
|
2436
|
-
|
|
2980
|
+
const publicKey = v3P2PRef.getPublicKey();
|
|
2981
|
+
// 2026-06-10: 把本机 user/agent name 一起返回, 对方拿到后能直接用
|
|
2982
|
+
let name = process.env.BOLLOON_USER_NAME || process.env.USER || 'node';
|
|
2983
|
+
try {
|
|
2984
|
+
const { readFileSync, existsSync } = await import('fs');
|
|
2985
|
+
const cfgPath = `${process.env.HOME || '/tmp'}/.bolloon/config.json`;
|
|
2986
|
+
if (existsSync(cfgPath)) {
|
|
2987
|
+
const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
|
|
2988
|
+
if (cfg.userName)
|
|
2989
|
+
name = cfg.userName;
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
catch { }
|
|
2993
|
+
res.json({ publicKey, name, role: v3P2PRef.getRole() });
|
|
2437
2994
|
}
|
|
2438
2995
|
catch (err) {
|
|
2439
2996
|
res.status(500).json({ error: err.message });
|
|
@@ -2477,6 +3034,40 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
2477
3034
|
res.status(500).json({ error: err.message });
|
|
2478
3035
|
}
|
|
2479
3036
|
});
|
|
3037
|
+
// 2026-06-10: PATCH 重命名 / 改备注 / 同时影响 publicKey
|
|
3038
|
+
// 用法: PATCH /api/p2p-peers/:name { name?, notes?, publicKey? }
|
|
3039
|
+
app.patch('/api/p2p-peers/:name', async (req, res) => {
|
|
3040
|
+
try {
|
|
3041
|
+
const { addOrUpdatePeer, removePeer } = await import('../network/known-peers.js');
|
|
3042
|
+
const { readFile, writeFile } = await import('fs/promises');
|
|
3043
|
+
const { existsSync } = await import('fs');
|
|
3044
|
+
const filePath = `${process.env.HOME || '/tmp'}/.bolloon/known_peers.json`;
|
|
3045
|
+
if (!existsSync(filePath))
|
|
3046
|
+
return res.status(404).json({ error: 'no known_peers.json' });
|
|
3047
|
+
const data = JSON.parse(await readFile(filePath, 'utf-8'));
|
|
3048
|
+
const oldName = req.params.name;
|
|
3049
|
+
const oldEntry = data.peers[oldName];
|
|
3050
|
+
if (!oldEntry)
|
|
3051
|
+
return res.status(404).json({ error: `peer "${oldName}" not found` });
|
|
3052
|
+
const { name: newName, notes, publicKey: newPk } = req.body || {};
|
|
3053
|
+
const finalName = newName || oldName;
|
|
3054
|
+
const finalPk = newPk || oldEntry.publicKey;
|
|
3055
|
+
if (finalName !== oldName) {
|
|
3056
|
+
delete data.peers[oldName];
|
|
3057
|
+
}
|
|
3058
|
+
data.peers[finalName] = {
|
|
3059
|
+
...oldEntry,
|
|
3060
|
+
publicKey: finalPk,
|
|
3061
|
+
name: finalName,
|
|
3062
|
+
notes: notes !== undefined ? notes : oldEntry.notes
|
|
3063
|
+
};
|
|
3064
|
+
await writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8');
|
|
3065
|
+
res.json({ ok: true, peer: data.peers[finalName] });
|
|
3066
|
+
}
|
|
3067
|
+
catch (err) {
|
|
3068
|
+
res.status(500).json({ error: err.message });
|
|
3069
|
+
}
|
|
3070
|
+
});
|
|
2480
3071
|
// v3: 主动 connect 到对端的 P2PDirect publicKey
|
|
2481
3072
|
// 用法: POST /api/remote-channels/p2p-connect { targetPublicKey: "<hex>" }
|
|
2482
3073
|
app.post('/api/remote-channels/p2p-connect', async (req, res) => {
|
|
@@ -2513,6 +3104,99 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
2513
3104
|
res.status(500).json({ error: err.message });
|
|
2514
3105
|
}
|
|
2515
3106
|
});
|
|
3107
|
+
// v3: 主动给对端发好友申请 — 推到对端 UI 让对方接受
|
|
3108
|
+
// 用法: POST /api/friend-request { targetPublicKey, name, message }
|
|
3109
|
+
// 2026-06-10 改: 用 sendToWithWait 等握手完成, 不再 fire-and-forget; 返回结构化 code 让前端知道失败
|
|
3110
|
+
app.post('/api/friend-request', async (req, res) => {
|
|
3111
|
+
try {
|
|
3112
|
+
if (!v3P2PRef) {
|
|
3113
|
+
return res.status(503).json({ ok: false, code: 'P2P_NOT_STARTED', error: 'P2PDirect not started' });
|
|
3114
|
+
}
|
|
3115
|
+
const { targetPublicKey, name, message } = req.body || {};
|
|
3116
|
+
if (!targetPublicKey || typeof targetPublicKey !== 'string' || targetPublicKey.length !== 64) {
|
|
3117
|
+
return res.status(400).json({ ok: false, code: 'BAD_REQUEST', error: 'targetPublicKey (64 hex) required' });
|
|
3118
|
+
}
|
|
3119
|
+
// 先 joinPeer 触发握手 (注意: joinPeer 不阻塞到 conn 就绪)
|
|
3120
|
+
const swarm = v3P2PRef.swarm;
|
|
3121
|
+
if (swarm) {
|
|
3122
|
+
try {
|
|
3123
|
+
await swarm.joinPeer(Buffer.from(targetPublicKey, 'hex'));
|
|
3124
|
+
}
|
|
3125
|
+
catch { }
|
|
3126
|
+
}
|
|
3127
|
+
// 主动把对方加为本机 known_peers (本地视角认为对方是朋友)
|
|
3128
|
+
const { addOrUpdatePeer, findNameByPublicKey } = await import('../network/known-peers.js');
|
|
3129
|
+
const existing = await findNameByPublicKey(targetPublicKey);
|
|
3130
|
+
const peerName = name || existing || `peer-${targetPublicKey.substring(0, 8)}`;
|
|
3131
|
+
await addOrUpdatePeer(peerName, targetPublicKey);
|
|
3132
|
+
// 构造 RPC, 推到对端 — 对端会 SSE 推 friend-request 到前端
|
|
3133
|
+
const myPk = v3P2PRef.getPublicKey();
|
|
3134
|
+
const requestId = crypto.randomUUID();
|
|
3135
|
+
const rpc = JSON.stringify({
|
|
3136
|
+
v: 3,
|
|
3137
|
+
op: 'agent.friend.request',
|
|
3138
|
+
payload: {
|
|
3139
|
+
requestId, // 2026-06-10: 加 requestId, ack 时回带
|
|
3140
|
+
fromPublicKey: myPk,
|
|
3141
|
+
name: peerName,
|
|
3142
|
+
message: message || '想加你为 P2P 好友, 共享 channel 协作'
|
|
3143
|
+
}
|
|
3144
|
+
});
|
|
3145
|
+
// 2026-06-10: 用 sendToWithWait, 等 conn 真就绪后再发, 默认 5s 超时
|
|
3146
|
+
const result = await v3P2PRef.sendToWithWait(targetPublicKey, rpc, 5000);
|
|
3147
|
+
console.log(`[v3-friend] ${myPk.substring(0, 12)}... 发送好友申请给 ${targetPublicKey.substring(0, 12)}... (result=${result}, requestId=${requestId.substring(0, 8)})`);
|
|
3148
|
+
if (result !== 'SENT') {
|
|
3149
|
+
return res.status(502).json({
|
|
3150
|
+
ok: false,
|
|
3151
|
+
code: result, // NO_CONN / WRITE_FAIL
|
|
3152
|
+
error: result === 'NO_CONN'
|
|
3153
|
+
? '对方未在线, 请确认对方已启动 bolloon 并互联'
|
|
3154
|
+
: '写入 P2P 通道失败, 请重试',
|
|
3155
|
+
persistedAs: peerName // 本地仍持久化, 等对方上线再 retry 即可
|
|
3156
|
+
});
|
|
3157
|
+
}
|
|
3158
|
+
res.json({ ok: true, sent: true, code: 'SENT', persistedAs: peerName, requestId });
|
|
3159
|
+
}
|
|
3160
|
+
catch (err) {
|
|
3161
|
+
console.error('[v3-friend] friend-request 失败:', err);
|
|
3162
|
+
res.status(500).json({ ok: false, code: 'EXCEPTION', error: err.message });
|
|
3163
|
+
}
|
|
3164
|
+
});
|
|
3165
|
+
// v3: 接受对方的好友申请 — 把对方加为 known_peers, 立即推我的 channel 列表给 ta
|
|
3166
|
+
// 用法: POST /api/friend-accept { fromPublicKey, name }
|
|
3167
|
+
app.post('/api/friend-accept', async (req, res) => {
|
|
3168
|
+
try {
|
|
3169
|
+
if (!v3P2PRef) {
|
|
3170
|
+
return res.status(503).json({ error: 'P2PDirect not started' });
|
|
3171
|
+
}
|
|
3172
|
+
const { fromPublicKey, name } = req.body || {};
|
|
3173
|
+
if (!fromPublicKey || typeof fromPublicKey !== 'string' || fromPublicKey.length !== 64) {
|
|
3174
|
+
return res.status(400).json({ error: 'fromPublicKey (64 hex) required' });
|
|
3175
|
+
}
|
|
3176
|
+
// 持久化
|
|
3177
|
+
const { addOrUpdatePeer, findNameByPublicKey } = await import('../network/known-peers.js');
|
|
3178
|
+
const existing = await findNameByPublicKey(fromPublicKey);
|
|
3179
|
+
const peerName = name || existing || `peer-${fromPublicKey.substring(0, 8)}`;
|
|
3180
|
+
await addOrUpdatePeer(peerName, fromPublicKey);
|
|
3181
|
+
// joinPeer 确保连接存在 (连接可能已在 friend-request 时建立, 这里可能是 no-op)
|
|
3182
|
+
const swarm = v3P2PRef.swarm;
|
|
3183
|
+
if (swarm) {
|
|
3184
|
+
try {
|
|
3185
|
+
await swarm.joinPeer(Buffer.from(fromPublicKey, 'hex'));
|
|
3186
|
+
}
|
|
3187
|
+
catch { }
|
|
3188
|
+
}
|
|
3189
|
+
// v3 修复: 主动广播自己的 channel 列表给新好友,
|
|
3190
|
+
// 不能依赖 connection handler, 因为连接在 friend-request 阶段已建立, 不会触发新 connection 事件
|
|
3191
|
+
v3BroadcastOwn().catch(err => console.error('[v3] broadcast after friend-accept failed:', err));
|
|
3192
|
+
console.log(`[v3-friend] 接受好友申请: ${fromPublicKey.substring(0, 12)}... → ${peerName}`);
|
|
3193
|
+
res.json({ ok: true, persistedAs: peerName });
|
|
3194
|
+
}
|
|
3195
|
+
catch (err) {
|
|
3196
|
+
console.error('[v3-friend] friend-accept 失败:', err);
|
|
3197
|
+
res.status(500).json({ error: err.message });
|
|
3198
|
+
}
|
|
3199
|
+
});
|
|
2516
3200
|
// v3: 给远端 channel 发消息 (B 节点) - 通过 P2PDirect 转发到 A, A 跑 LLM, 回 B
|
|
2517
3201
|
// 用法: POST /api/remote-channels/chat-send
|
|
2518
3202
|
// { targetPublicKey, channelId, text }
|
|
@@ -2540,6 +3224,8 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
2540
3224
|
error: 'peer not connected. POST /api/remote-channels/p2p-connect first.'
|
|
2541
3225
|
});
|
|
2542
3226
|
}
|
|
3227
|
+
// 2026-06-10: 喂 watchdog — chat-send 成功是真实业务活动
|
|
3228
|
+
watchdogRef?.recordActivity?.();
|
|
2543
3229
|
console.log(`[v3] chat-send 转发到 ${targetPublicKey.substring(0, 12)}... (channelId=${channelId})`);
|
|
2544
3230
|
res.json({ ok: true, sent: true });
|
|
2545
3231
|
}
|
|
@@ -3123,6 +3809,24 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
3123
3809
|
res.status(500).json({ error: err.message });
|
|
3124
3810
|
}
|
|
3125
3811
|
});
|
|
3812
|
+
// 终止当前 channel 的 LLM 流 (UI 终止按钮)
|
|
3813
|
+
app.post('/api/chat/abort', async (req, res) => {
|
|
3814
|
+
try {
|
|
3815
|
+
const { channelId } = req.body;
|
|
3816
|
+
if (!channelId)
|
|
3817
|
+
return res.status(400).json({ error: 'channelId required' });
|
|
3818
|
+
const s = channelRunState.get(channelId);
|
|
3819
|
+
if (s?.abortController) {
|
|
3820
|
+
s.abortController.abort();
|
|
3821
|
+
console.log(`[abort] user aborted channel=${channelId}`);
|
|
3822
|
+
return res.json({ ok: true, aborted: true });
|
|
3823
|
+
}
|
|
3824
|
+
res.json({ ok: true, aborted: false });
|
|
3825
|
+
}
|
|
3826
|
+
catch (err) {
|
|
3827
|
+
res.status(500).json({ error: err.message });
|
|
3828
|
+
}
|
|
3829
|
+
});
|
|
3126
3830
|
// 主人审阅: 批准 draft
|
|
3127
3831
|
app.post('/api/chat/approve', async (req, res) => {
|
|
3128
3832
|
try {
|
|
@@ -3415,6 +4119,8 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
3415
4119
|
healthMonitor = createHealthMonitor();
|
|
3416
4120
|
// 把 watchdog 静默阈值拉到 30 分钟, 避免开发期 / 用户空闲时被误杀
|
|
3417
4121
|
watchdog = createWatchdog({ silentThresholdMs: 30 * 60 * 1000 });
|
|
4122
|
+
// 2026-06-10: 同步到 module-level, 让 broadcast() / P2P handler / chat-send 都能喂活动
|
|
4123
|
+
watchdogRef = watchdog;
|
|
3418
4124
|
console.log('[24h] Heartbeat modules loaded');
|
|
3419
4125
|
}
|
|
3420
4126
|
catch (err) {
|
|
@@ -3503,20 +4209,378 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
3503
4209
|
res.status(500).json({ error: err.message });
|
|
3504
4210
|
}
|
|
3505
4211
|
});
|
|
3506
|
-
app.get('/api/judgments', async (
|
|
4212
|
+
app.get('/api/judgments', async (req, res) => {
|
|
3507
4213
|
try {
|
|
3508
|
-
const {
|
|
4214
|
+
const { listJudgmentsByStatus, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
|
|
3509
4215
|
await initializeValueStore();
|
|
3510
|
-
const
|
|
3511
|
-
|
|
4216
|
+
const status = (typeof req.query.status === 'string' ? req.query.status : 'all');
|
|
4217
|
+
const all = await listJudgmentsByStatus(status);
|
|
3512
4218
|
all.sort((a, b) => (b.timestamp || '').localeCompare(a.timestamp || ''));
|
|
3513
|
-
res.json({ count: all.length, judgments: all });
|
|
4219
|
+
res.json({ count: all.length, status, judgments: all });
|
|
3514
4220
|
}
|
|
3515
4221
|
catch (err) {
|
|
3516
4222
|
console.error('[judgments] GET failed:', err);
|
|
3517
4223
|
res.status(500).json({ error: err.message });
|
|
3518
4224
|
}
|
|
3519
4225
|
});
|
|
4226
|
+
// 蒸馏 B 触发 (人类点按钮) — 同步执行演化对齐
|
|
4227
|
+
app.post('/api/judgments/distill-from-conversation', async (req, res) => {
|
|
4228
|
+
try {
|
|
4229
|
+
const { channelId, messageId, recentTurns } = req.body;
|
|
4230
|
+
if (!channelId) {
|
|
4231
|
+
return res.status(400).json({ error: 'channelId required' });
|
|
4232
|
+
}
|
|
4233
|
+
// 取 channel 最近的对话
|
|
4234
|
+
const channels = await loadChannels();
|
|
4235
|
+
const channel = channels.find((c) => c.id === channelId);
|
|
4236
|
+
if (!channel)
|
|
4237
|
+
return res.status(404).json({ error: 'channel not found' });
|
|
4238
|
+
const currentSessionId = channel.currentSessionId;
|
|
4239
|
+
if (!currentSessionId) {
|
|
4240
|
+
return res.status(400).json({ error: 'no active session in channel' });
|
|
4241
|
+
}
|
|
4242
|
+
const session = await loadSession(channelId, currentSessionId);
|
|
4243
|
+
if (!session)
|
|
4244
|
+
return res.status(404).json({ error: 'session not found' });
|
|
4245
|
+
// 取最近 N 轮 (默认 10), 转成 DistillTurn 格式
|
|
4246
|
+
const limit = Math.min(Math.max(recentTurns ?? 10, 2), 30);
|
|
4247
|
+
const turns = session.messages.slice(-limit).map((m) => ({
|
|
4248
|
+
role: (m.type === 'user' ? 'human' : 'agent'),
|
|
4249
|
+
content: m.content,
|
|
4250
|
+
}));
|
|
4251
|
+
const { distillAndStoreFromChannel } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4252
|
+
const result = await distillAndStoreFromChannel(turns, { channelId });
|
|
4253
|
+
res.json({
|
|
4254
|
+
ok: true,
|
|
4255
|
+
triggered: result.triggered,
|
|
4256
|
+
reason: result.reason,
|
|
4257
|
+
judgment: result.judgment,
|
|
4258
|
+
evolved: result.evolved,
|
|
4259
|
+
});
|
|
4260
|
+
}
|
|
4261
|
+
catch (err) {
|
|
4262
|
+
console.error('[judgments] distill-from-conversation failed:', err);
|
|
4263
|
+
res.status(500).json({ error: err.message });
|
|
4264
|
+
}
|
|
4265
|
+
});
|
|
4266
|
+
// 蒸馏 D 触发 (AI 被动) — 后台异步,不阻塞 HTTP 响应
|
|
4267
|
+
app.post('/api/judgments/detect-and-distill', async (req, res) => {
|
|
4268
|
+
try {
|
|
4269
|
+
const { channelId, turns } = req.body;
|
|
4270
|
+
// 先立即返回 202, 不等 LLM
|
|
4271
|
+
res.status(202).json({ ok: true, queued: true });
|
|
4272
|
+
if (!channelId || !Array.isArray(turns) || turns.length === 0) {
|
|
4273
|
+
return;
|
|
4274
|
+
}
|
|
4275
|
+
// 异步处理 (不 await, 不阻塞响应)
|
|
4276
|
+
setImmediate(async () => {
|
|
4277
|
+
try {
|
|
4278
|
+
const { detectAndDistillFromChannel } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4279
|
+
const result = await detectAndDistillFromChannel(turns, { channelId });
|
|
4280
|
+
if (result.triggered) {
|
|
4281
|
+
console.log(`[D-hook] ${channelId}: ${result.reason}`, result.evolved);
|
|
4282
|
+
}
|
|
4283
|
+
}
|
|
4284
|
+
catch (err) {
|
|
4285
|
+
console.warn('[D-hook] background failed:', err);
|
|
4286
|
+
}
|
|
4287
|
+
});
|
|
4288
|
+
}
|
|
4289
|
+
catch (err) {
|
|
4290
|
+
console.error('[judgments] detect-and-distill failed:', err);
|
|
4291
|
+
res.status(500).json({ error: err.message });
|
|
4292
|
+
}
|
|
4293
|
+
});
|
|
4294
|
+
// 判断力使用回溯 (P0.5): 给定 judgmentIds, 反查对应的 decision 文本
|
|
4295
|
+
// 用途: UI 上"这条 AI 回复引用了哪些原则"
|
|
4296
|
+
app.post('/api/judgments/resolve-usage', async (req, res) => {
|
|
4297
|
+
try {
|
|
4298
|
+
const { ids } = req.body;
|
|
4299
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
4300
|
+
return res.json({ items: [] });
|
|
4301
|
+
}
|
|
4302
|
+
const { loadAllJudgments } = await import('../pi-ecosystem-judgment/human-value-store.js');
|
|
4303
|
+
const all = await loadAllJudgments();
|
|
4304
|
+
const byId = new Map(all.map((j) => [j.id, j]));
|
|
4305
|
+
const items = ids
|
|
4306
|
+
.map((id) => byId.get(id))
|
|
4307
|
+
.filter((j) => Boolean(j))
|
|
4308
|
+
.map((j) => ({
|
|
4309
|
+
id: j.id,
|
|
4310
|
+
decision: j.decision,
|
|
4311
|
+
status: j.status ?? 'active',
|
|
4312
|
+
timestamp: j.timestamp,
|
|
4313
|
+
}));
|
|
4314
|
+
res.json({ items });
|
|
4315
|
+
}
|
|
4316
|
+
catch (err) {
|
|
4317
|
+
console.error('[judgments] resolve-usage failed:', err);
|
|
4318
|
+
res.status(500).json({ error: err.message });
|
|
4319
|
+
}
|
|
4320
|
+
});
|
|
4321
|
+
// 判断力违规日志 (P3 UI): 读 violations.jsonl
|
|
4322
|
+
app.get('/api/judgments/violations', async (req, res) => {
|
|
4323
|
+
try {
|
|
4324
|
+
const { getRecentViolations } = await import('../pi-ecosystem-judgment/monitor-gate.js');
|
|
4325
|
+
const limit = Math.min(Math.max(parseInt(String(req.query.limit ?? '20'), 10) || 20, 1), 200);
|
|
4326
|
+
const items = await getRecentViolations(limit);
|
|
4327
|
+
res.json({ count: items.length, items });
|
|
4328
|
+
}
|
|
4329
|
+
catch (err) {
|
|
4330
|
+
console.error('[judgments] violations failed:', err);
|
|
4331
|
+
res.status(500).json({ error: err.message });
|
|
4332
|
+
}
|
|
4333
|
+
});
|
|
4334
|
+
// 类 B 自适应扫描: 读 judgments.json + usage.jsonl, 给出 stale/rising/unused 建议
|
|
4335
|
+
// ?force=1 跳过 24h 缓存
|
|
4336
|
+
app.get('/api/judgments/adaptive-suggestions', async (req, res) => {
|
|
4337
|
+
try {
|
|
4338
|
+
const { getCachedScan } = await import('../pi-ecosystem-judgment/adaptive-scan.js');
|
|
4339
|
+
const force = String(req.query.force ?? '') === '1';
|
|
4340
|
+
const result = await getCachedScan(force);
|
|
4341
|
+
res.json(result);
|
|
4342
|
+
}
|
|
4343
|
+
catch (err) {
|
|
4344
|
+
console.error('[judgments] adaptive-scan failed:', err);
|
|
4345
|
+
res.status(500).json({ error: err.message });
|
|
4346
|
+
}
|
|
4347
|
+
});
|
|
4348
|
+
// Bootstrap Context 调试视图: 返出完整 BolloonContext
|
|
4349
|
+
app.get('/api/bolloon/context', async (req, res) => {
|
|
4350
|
+
try {
|
|
4351
|
+
const { getCachedBolloonContext } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4352
|
+
const force = String(req.query.force ?? '') === '1';
|
|
4353
|
+
const ctx = await getCachedBolloonContext({ cwd: process.cwd() }, force);
|
|
4354
|
+
res.json(ctx);
|
|
4355
|
+
}
|
|
4356
|
+
catch (err) {
|
|
4357
|
+
console.error('[bolloon] context failed:', err);
|
|
4358
|
+
res.status(500).json({ error: err.message });
|
|
4359
|
+
}
|
|
4360
|
+
});
|
|
4361
|
+
// 阶段 B: 周报 (weekly-report.ts 产物) — 仅 API 读取, 不做 UI tab
|
|
4362
|
+
// GET /api/reports → { files: ['2026-W24.md', ...] }
|
|
4363
|
+
// GET /api/reports/2026-W24 → { week, content }
|
|
4364
|
+
app.get('/api/reports', async (_req, res) => {
|
|
4365
|
+
try {
|
|
4366
|
+
const dir = path.join(os.homedir(), '.bolloon', 'reports');
|
|
4367
|
+
try {
|
|
4368
|
+
const entries = await fs.readdir(dir);
|
|
4369
|
+
const files = entries
|
|
4370
|
+
.filter((f) => f.endsWith('.md'))
|
|
4371
|
+
.sort()
|
|
4372
|
+
.reverse(); // 新的在前
|
|
4373
|
+
res.json({ dir, files });
|
|
4374
|
+
}
|
|
4375
|
+
catch {
|
|
4376
|
+
res.json({ dir, files: [] });
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4379
|
+
catch (err) {
|
|
4380
|
+
res.status(500).json({ error: err.message });
|
|
4381
|
+
}
|
|
4382
|
+
});
|
|
4383
|
+
app.get('/api/reports/:week', async (req, res) => {
|
|
4384
|
+
try {
|
|
4385
|
+
const week = req.params.week;
|
|
4386
|
+
// 严格校验, 防路径穿越
|
|
4387
|
+
if (!/^\d{4}-W\d{1,2}$/.test(week)) {
|
|
4388
|
+
return res.status(400).json({ error: 'week must match YYYY-Www' });
|
|
4389
|
+
}
|
|
4390
|
+
const file = path.join(os.homedir(), '.bolloon', 'reports', `${week}.md`);
|
|
4391
|
+
try {
|
|
4392
|
+
const content = await fs.readFile(file, 'utf-8');
|
|
4393
|
+
res.json({ week, content, length: content.length });
|
|
4394
|
+
}
|
|
4395
|
+
catch {
|
|
4396
|
+
res.status(404).json({ error: 'not found', week });
|
|
4397
|
+
}
|
|
4398
|
+
}
|
|
4399
|
+
catch (err) {
|
|
4400
|
+
res.status(500).json({ error: err.message });
|
|
4401
|
+
}
|
|
4402
|
+
});
|
|
4403
|
+
// 阶段 C 护栏 5: auto-evolve baseline 管理 (无 UI, 仅 API)
|
|
4404
|
+
// GET /api/auto-evolve/baselines → 列出所有 baseline tag
|
|
4405
|
+
// GET /api/auto-evolve/baselines/:tag/diff → 看某 baseline 的 diff 摘要
|
|
4406
|
+
// POST /api/auto-evolve/rollback {tag} → 回滚到指定 baseline
|
|
4407
|
+
app.get('/api/auto-evolve/baselines', async (_req, res) => {
|
|
4408
|
+
try {
|
|
4409
|
+
const { execFile } = await import('child_process');
|
|
4410
|
+
const { promisify } = await import('util');
|
|
4411
|
+
const pExec = promisify(execFile);
|
|
4412
|
+
const { stdout } = await pExec('git', [
|
|
4413
|
+
'tag', '-l', 'auto-evolve-baseline-*', '--format=%(refname:short)|%(contents)|%(objectname:short)|%(taggerdate:iso)',
|
|
4414
|
+
], { cwd: process.cwd() });
|
|
4415
|
+
const tags = stdout.trim().split('\n').filter(Boolean).map((line) => {
|
|
4416
|
+
const [tag, msg, sha, date] = line.split('|');
|
|
4417
|
+
return { tag, message: msg || '', sha, date };
|
|
4418
|
+
});
|
|
4419
|
+
res.json({ tags, count: tags.length });
|
|
4420
|
+
}
|
|
4421
|
+
catch (err) {
|
|
4422
|
+
res.status(500).json({ error: err.message });
|
|
4423
|
+
}
|
|
4424
|
+
});
|
|
4425
|
+
app.get('/api/auto-evolve/baselines/:tag/diff', async (req, res) => {
|
|
4426
|
+
try {
|
|
4427
|
+
const { execFile } = await import('child_process');
|
|
4428
|
+
const { promisify } = await import('util');
|
|
4429
|
+
const pExec = promisify(execFile);
|
|
4430
|
+
const tag = req.params.tag;
|
|
4431
|
+
if (!/^auto-evolve-baseline-[\w-]+$/.test(tag)) {
|
|
4432
|
+
return res.status(400).json({ error: 'tag must match auto-evolve-baseline-*' });
|
|
4433
|
+
}
|
|
4434
|
+
const { stdout } = await pExec('git', ['show', '--stat', '--no-color', tag], { cwd: process.cwd() });
|
|
4435
|
+
res.json({ tag, diff: stdout.slice(0, 5000) }); // 限长 5KB
|
|
4436
|
+
}
|
|
4437
|
+
catch (err) {
|
|
4438
|
+
res.status(500).json({ error: err.message });
|
|
4439
|
+
}
|
|
4440
|
+
});
|
|
4441
|
+
// Bootstrap Context → 拼好的 system prompt 片段 (供调试看注入效果)
|
|
4442
|
+
app.get('/api/bolloon/context/system-prompt', async (req, res) => {
|
|
4443
|
+
try {
|
|
4444
|
+
const { getCachedBolloonContext } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4445
|
+
const { formatContextForSystemPrompt } = await import('../bootstrap/project-context.js');
|
|
4446
|
+
const ctx = await getCachedBolloonContext({ cwd: process.cwd() });
|
|
4447
|
+
const systemAddition = formatContextForSystemPrompt(ctx, {
|
|
4448
|
+
maxChars: parseInt(String(req.query.max ?? '4000'), 10) || 4000,
|
|
4449
|
+
});
|
|
4450
|
+
res.json({ systemAddition, length: systemAddition.length, truncated: systemAddition.includes('截断模式') });
|
|
4451
|
+
}
|
|
4452
|
+
catch (err) {
|
|
4453
|
+
console.error('[bolloon] context/system-prompt failed:', err);
|
|
4454
|
+
res.status(500).json({ error: err.message });
|
|
4455
|
+
}
|
|
4456
|
+
});
|
|
4457
|
+
// 自适应接受/拒绝: 写 evolution.jsonl 留痕, 接受时同时 patch judgments.json
|
|
4458
|
+
// body: { action: 'accept'|'reject'|'revert', suggestion, appliedPatch? }
|
|
4459
|
+
// query: ?auto=1 → 类 B 自动路径, 受 auto-evolve-policy 网关保护
|
|
4460
|
+
// 缺省 → 用户在 UI 手动触发, 不查开关 (避免阻塞用户)
|
|
4461
|
+
app.post('/api/judgments/adaptive-apply', async (req, res) => {
|
|
4462
|
+
try {
|
|
4463
|
+
const isAuto = req.query.auto === '1' || req.query.auto === 'true';
|
|
4464
|
+
const { action, suggestion, appliedPatch } = req.body;
|
|
4465
|
+
if (!action || !suggestion?.judgmentId) {
|
|
4466
|
+
return res.status(400).json({ error: 'action and suggestion.judgmentId required' });
|
|
4467
|
+
}
|
|
4468
|
+
const { updateJudgmentStatus } = await import('../pi-ecosystem-judgment/human-value-store.js');
|
|
4469
|
+
const { logEvolution } = await import('../pi-ecosystem-judgment/adaptive-scan.js');
|
|
4470
|
+
// accept 时: 真正改库
|
|
4471
|
+
if (action === 'accept') {
|
|
4472
|
+
// 阶段 A: 自动路径需先过 auto-evolve-policy 网关
|
|
4473
|
+
if (isAuto) {
|
|
4474
|
+
const { requireDataLayerAutoEvolve } = await import('../utils/auto-evolve-policy.js');
|
|
4475
|
+
try {
|
|
4476
|
+
await requireDataLayerAutoEvolve('adaptive-apply.auto.deprecate');
|
|
4477
|
+
}
|
|
4478
|
+
catch (err) {
|
|
4479
|
+
return res.status(423).json({
|
|
4480
|
+
error: 'data-layer-auto-evolve-disabled',
|
|
4481
|
+
message: err.message,
|
|
4482
|
+
hint: '设 BOLLOON_AUTO_EVOLVE_DATA=1 或在 self-improve-policy.json 加 dataLayerAutoEvolve: true',
|
|
4483
|
+
});
|
|
4484
|
+
}
|
|
4485
|
+
}
|
|
4486
|
+
if (suggestion.action === 'deprecate') {
|
|
4487
|
+
// 标记 superseded (语义: 不再用, 但保留可回滚)
|
|
4488
|
+
await updateJudgmentStatus(suggestion.judgmentId, 'superseded', {
|
|
4489
|
+
evolutionReason: 'merged', // 借 merged 字段表达"被自适应废弃"
|
|
4490
|
+
});
|
|
4491
|
+
}
|
|
4492
|
+
else if (suggestion.action === 'boost') {
|
|
4493
|
+
// boost: 用户手动接受后, 不改库本身 (weight 在 getRelevantValues 里动态算),
|
|
4494
|
+
// 但写 evolution 留痕, 未来可以基于此调整算法
|
|
4495
|
+
// 当前不直接改库, 仅留痕
|
|
4496
|
+
}
|
|
4497
|
+
// 'review' 类不需要自动改库, 仅 log 接受
|
|
4498
|
+
}
|
|
4499
|
+
await logEvolution({
|
|
4500
|
+
ts: new Date().toISOString(),
|
|
4501
|
+
action,
|
|
4502
|
+
suggestion: suggestion,
|
|
4503
|
+
appliedPatch,
|
|
4504
|
+
});
|
|
4505
|
+
res.json({ ok: true });
|
|
4506
|
+
}
|
|
4507
|
+
catch (err) {
|
|
4508
|
+
console.error('[judgments] adaptive-apply failed:', err);
|
|
4509
|
+
res.status(500).json({ error: err.message });
|
|
4510
|
+
}
|
|
4511
|
+
});
|
|
4512
|
+
// 演化日志 (audit / 一键回滚源)
|
|
4513
|
+
app.get('/api/judgments/evolution-log', async (req, res) => {
|
|
4514
|
+
try {
|
|
4515
|
+
const { readEvolutionLog } = await import('../pi-ecosystem-judgment/adaptive-scan.js');
|
|
4516
|
+
const limit = Math.min(Math.max(parseInt(String(req.query.limit ?? '50'), 10) || 50, 1), 200);
|
|
4517
|
+
const items = await readEvolutionLog(limit);
|
|
4518
|
+
res.json({ count: items.length, items });
|
|
4519
|
+
}
|
|
4520
|
+
catch (err) {
|
|
4521
|
+
console.error('[judgments] evolution-log failed:', err);
|
|
4522
|
+
res.status(500).json({ error: err.message });
|
|
4523
|
+
}
|
|
4524
|
+
});
|
|
4525
|
+
// 阶段 2: Causal-judge 4 个 endpoint
|
|
4526
|
+
app.get('/api/judgments/causal/correlation', async (req, res) => {
|
|
4527
|
+
try {
|
|
4528
|
+
const { runCorrelationAnalysis } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4529
|
+
const topN = Math.min(Math.max(parseInt(String(req.query.topN ?? '5'), 10) || 5, 1), 50);
|
|
4530
|
+
const useLLM = String(req.query.useLLM ?? '1') !== '0';
|
|
4531
|
+
const items = await runCorrelationAnalysis({ topN, useLLM });
|
|
4532
|
+
res.json({ count: items.length, items });
|
|
4533
|
+
}
|
|
4534
|
+
catch (err) {
|
|
4535
|
+
console.error('[causal] correlation failed:', err);
|
|
4536
|
+
res.status(500).json({ error: err.message });
|
|
4537
|
+
}
|
|
4538
|
+
});
|
|
4539
|
+
app.get('/api/judgments/causal/intervention', async (req, res) => {
|
|
4540
|
+
try {
|
|
4541
|
+
const { runIntervention } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4542
|
+
const { judgmentId, scenario } = req.query;
|
|
4543
|
+
if (!judgmentId)
|
|
4544
|
+
return res.status(400).json({ error: 'judgmentId required' });
|
|
4545
|
+
const result = await runIntervention(judgmentId, { scenarioContext: scenario });
|
|
4546
|
+
res.json(result);
|
|
4547
|
+
}
|
|
4548
|
+
catch (err) {
|
|
4549
|
+
console.error('[causal] intervention failed:', err);
|
|
4550
|
+
res.status(500).json({ error: err.message });
|
|
4551
|
+
}
|
|
4552
|
+
});
|
|
4553
|
+
app.post('/api/judgments/causal/counterfactual', async (req, res) => {
|
|
4554
|
+
try {
|
|
4555
|
+
const { runCounterfactualAudit } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4556
|
+
const { userInput, aiReply, violatedPrinciples } = req.body;
|
|
4557
|
+
if (!userInput || !aiReply) {
|
|
4558
|
+
return res.status(400).json({ error: 'userInput and aiReply required' });
|
|
4559
|
+
}
|
|
4560
|
+
const audit = await runCounterfactualAudit({
|
|
4561
|
+
userInput,
|
|
4562
|
+
aiReply,
|
|
4563
|
+
violatedPrinciples: violatedPrinciples ?? [],
|
|
4564
|
+
});
|
|
4565
|
+
res.json(audit);
|
|
4566
|
+
}
|
|
4567
|
+
catch (err) {
|
|
4568
|
+
console.error('[causal] counterfactual failed:', err);
|
|
4569
|
+
res.status(500).json({ error: err.message });
|
|
4570
|
+
}
|
|
4571
|
+
});
|
|
4572
|
+
app.get('/api/judgments/causal/audit-log', async (req, res) => {
|
|
4573
|
+
try {
|
|
4574
|
+
const { readCounterfactualLog } = await import('../pi-ecosystem-judgment/human-value-pipeline.js');
|
|
4575
|
+
const limit = Math.min(Math.max(parseInt(String(req.query.limit ?? '20'), 10) || 20, 1), 200);
|
|
4576
|
+
const items = await readCounterfactualLog(limit);
|
|
4577
|
+
res.json({ count: items.length, items });
|
|
4578
|
+
}
|
|
4579
|
+
catch (err) {
|
|
4580
|
+
console.error('[causal] audit-log failed:', err);
|
|
4581
|
+
res.status(500).json({ error: err.message });
|
|
4582
|
+
}
|
|
4583
|
+
});
|
|
3520
4584
|
// 导入判断: 接受 { filename, content (base64), context }.
|
|
3521
4585
|
// 支持 .json / .yaml / .yml / .md / .txt / .html. 完全离线解析, 不调 LLM.
|
|
3522
4586
|
// 解析规则:
|
|
@@ -3759,8 +4823,12 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
3759
4823
|
// level 1 (内存爆) → 进程自杀, 依赖外层 supervisor / 用户重启 (Windows 任务计划/手动)
|
|
3760
4824
|
// 否则 Node.js 高 GC 压力下 HTTP 响应丢失, 客户端 fetch 永远 pending
|
|
3761
4825
|
watchdog.registerRestartStrategy(1, () => {
|
|
3762
|
-
|
|
3763
|
-
|
|
4826
|
+
// 2026-06-10: 改为不退出, 因为我们直接后台 tsx 启动没有外层 supervisor.
|
|
4827
|
+
// 误判主要因 recordActivity 仅在显式调用时刷新, 而 broadcast/SSE/连接均不触发.
|
|
4828
|
+
// 退出策略原文保留在注释里:
|
|
4829
|
+
// console.error('[Watchdog] memory critical, 进程退出 (期望外层重启)');
|
|
4830
|
+
// setTimeout(() => process.exit(1), 100);
|
|
4831
|
+
console.warn('[Watchdog] silentThreshold 触发, 但跳过 process.exit (无 supervisor)');
|
|
3764
4832
|
});
|
|
3765
4833
|
watchdog.start();
|
|
3766
4834
|
console.log('[24h] Watchdog started');
|
|
@@ -3919,6 +4987,8 @@ export async function createWebServer(port = 3000, options = {}) {
|
|
|
3919
4987
|
});
|
|
3920
4988
|
}
|
|
3921
4989
|
function broadcast(data, channelId) {
|
|
4990
|
+
// 2026-06-10: 喂 watchdog, 避免 30min 空闲被误判 (recordActivity 内有 5s 去抖)
|
|
4991
|
+
watchdogRef?.recordActivity?.();
|
|
3922
4992
|
const envelope = { ...data, channelId };
|
|
3923
4993
|
const message = `data: ${JSON.stringify(envelope)}\n\n`;
|
|
3924
4994
|
console.log(`[broadcast] type=${data.type}, channelId=${channelId}, clients=${sseClients.size}`);
|