@bolloon/bolloon-agent 0.1.33 → 0.1.34

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/src/web/server.ts CHANGED
@@ -73,6 +73,17 @@ interface Channel {
73
73
  name: string;
74
74
  agentId: string;
75
75
  did?: string;
76
+ // 2026-06-11: channel 级 persona + 关联文档 (从 ~/.bolloon/persona.json 复制或独立覆盖)
77
+ persona?: {
78
+ name?: string;
79
+ description?: string;
80
+ personality?: string;
81
+ greeting?: string;
82
+ capabilities?: string[];
83
+ interests?: string[];
84
+ };
85
+ // 关联的文档 ID 列表 (启动 LLM 时自动加载到 context)
86
+ linkedDocumentIds?: string[];
76
87
  publicKey?: string;
77
88
  cid?: string;
78
89
  /** 轻量引用:从 didDocument 只挑出 cid/ipnsName, 不存整份文档 */
@@ -419,8 +430,52 @@ let sseClients: Set<SSEClient> = new Set();
419
430
  // v3: 远端 channel UI 元数据缓存 — key: peerId, value: sanitize 过的 channel 列表
420
431
  // in-memory only, 进程重启清空 (judgment 内容永远不在这里)
421
432
  let remoteChannelCache: Map<string, Array<Record<string, unknown>>> = new Map();
433
+
434
+ // 2026-06-10: 持久化 remote channel cache 到 ~/.bolloon/remote-channels-cache.json
435
+ // 之前是纯内存 Map, nodeA 重启后所有对端 channel 列表丢失, 需要等对面再推一次
436
+ const REMOTE_CACHE_FILE = `${process.env.HOME || '/tmp'}/.bolloon/remote-channels-cache.json`;
437
+ async function loadRemoteChannelCacheFromDisk(): Promise<void> {
438
+ try {
439
+ const { readFile, mkdir } = await import('fs/promises');
440
+ const { existsSync } = await import('fs');
441
+ if (!existsSync(REMOTE_CACHE_FILE)) return;
442
+ const raw = await readFile(REMOTE_CACHE_FILE, 'utf-8');
443
+ const obj = JSON.parse(raw);
444
+ if (obj && typeof obj === 'object') {
445
+ for (const [pk, list] of Object.entries(obj)) {
446
+ if (Array.isArray(list)) {
447
+ remoteChannelCache.set(pk, list as Array<Record<string, unknown>>);
448
+ }
449
+ }
450
+ console.log(`[v3-meta] 从磁盘恢复 ${remoteChannelCache.size} 个 peer 的 channel cache`);
451
+ }
452
+ } catch (err) {
453
+ console.warn('[v3-meta] 恢复 remote channel cache 失败 (非致命):', (err as Error).message);
454
+ }
455
+ }
456
+ async function persistRemoteChannelCache(): Promise<void> {
457
+ try {
458
+ const { writeFile, mkdir } = await import('fs/promises');
459
+ const { existsSync } = await import('fs');
460
+ if (!existsSync(`${process.env.HOME || '/tmp'}/.bolloon`)) {
461
+ await mkdir(`${process.env.HOME || '/tmp'}/.bolloon`, { recursive: true });
462
+ }
463
+ const obj: Record<string, unknown> = {};
464
+ for (const [pk, list] of remoteChannelCache.entries()) {
465
+ obj[pk] = list;
466
+ }
467
+ await writeFile(REMOTE_CACHE_FILE, JSON.stringify(obj, null, 2), 'utf-8');
468
+ } catch (err) {
469
+ console.warn('[v3-meta] 持久化 remote channel cache 失败 (非致命):', (err as Error).message);
470
+ }
471
+ }
472
+ // 启动时立即同步读一次 (异步, 不阻塞)
473
+ loadRemoteChannelCacheFromDisk();
422
474
  // v3: P2PDirect 引用 (Hyperswarm 薄包装) - 模块级, 因为 web server 闭包里不可用
423
475
  let v3P2PRef: import('../network/p2p-direct.js').P2PDirect | null = null;
476
+ // 2026-06-10: watchdog 提升到 module-level, 让 broadcast() / 模块级业务函数能埋点喂活动
477
+ // 之前在 createWebServer 闭包内, 闭包外的 broadcast() 拿不到 → 误判 30min 无活动 → 自杀.
478
+ let watchdogRef: any = null;
424
479
  // v3: 等待中的 history RPC (B 端 chat-history endpoint 用) — rpcId → { resolve, reject }
425
480
  const v3PendingHistoryGets: Map<string, { resolve: (data: any) => void; reject: (err: Error) => void }> = new Map();
426
481
  let channelSessions: Map<string, AgentSession> = new Map(); // key: channelId
@@ -461,7 +516,6 @@ function sanitizeChannelForPeer(
461
516
  createdAt: ch.createdAt,
462
517
  updatedAt: ch.updatedAt,
463
518
  hasWallet: !!ch.walletAddress,
464
- boundJudgmentCount: Array.isArray(ch.bound_judgment_ids) ? ch.bound_judgment_ids.length : 0,
465
519
  share_id: ch.share_id,
466
520
  // 🔒 不返回: bound_judgment_ids, walletAddress, walletBinding, autoInvokeTools, sessions, shared_with_peers
467
521
  };
@@ -706,6 +760,15 @@ async function handleV3P2PMessage(parsed: any, conn: P2PConnection, comm: Hypers
706
760
  console.warn(`[v3] 存 user 消息失败 (不影响 chat):`, (saveErr as Error).message);
707
761
  }
708
762
 
763
+ // v3 修复: 同步给 A 自己的 UI — broadcast SSE 事件让 A 的 owner 实时看到 B 的消息
764
+ broadcast({
765
+ type: 'user',
766
+ content: text,
767
+ channelId,
768
+ source: 'remote',
769
+ fromPublicKey: senderKey
770
+ }, channelId);
771
+
709
772
  // v3 新增: 告诉 B "我开始想了, 用了哪些 judgment" — 让 B 看到决策依据
710
773
  const judgmentHint = await buildJudgmentHint(ch, channelId);
711
774
  const usedJudgments = await extractJudgmentsFromHint(ch);
@@ -788,6 +851,13 @@ async function handleV3P2PMessage(parsed: any, conn: P2PConnection, comm: Hypers
788
851
  console.warn(`[v3] 存 assistant 消息失败 (不影响):`, (saveErr as Error).message);
789
852
  }
790
853
 
854
+ // v3 修复: 同步给 A 自己的 UI — broadcast AI 回复给 A 的 owner 实时看到
855
+ broadcast({
856
+ type: 'ai',
857
+ content: fullResponse,
858
+ channelId
859
+ }, channelId);
860
+
791
861
  // 3. 把完整回复发给 B
792
862
  const reply = JSON.stringify({
793
863
  v: 3, op: 'agent.chat.reply',
@@ -1116,6 +1186,47 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1116
1186
  };
1117
1187
  let p2pCommunicator: HyperswarmCommunicator | null = null;
1118
1188
 
1189
+ // v3: 定期 broadcast — 每个 peer 只收到分享给他的 channel (按 peer 个性化)
1190
+ // 走 known_peers (持久化) + sendTo (自动 joinPeer 重连), 不只 conns
1191
+ // 定义在此处 (所有 try 外部), 确保 route handlers 也能访问
1192
+ const v3BroadcastOwn = async () => {
1193
+ if (!v3P2PRef) return { sent: 0, total: 0 };
1194
+ const channels = await loadChannels();
1195
+ const { listPeers } = await import('../network/known-peers.js');
1196
+ const peers = await listPeers();
1197
+ const myPk = v3P2PRef.getPublicKey();
1198
+ // 2026-06-10: 本机名字一起携带, 对端能直接显示 + 落到自己的 known_peers
1199
+ let myName = process.env.BOLLOON_USER_NAME || process.env.USER || 'node';
1200
+ try {
1201
+ const { readFileSync, existsSync } = await import('fs');
1202
+ const cfgPath = `${process.env.HOME || '/tmp'}/.bolloon/config.json`;
1203
+ if (existsSync(cfgPath)) {
1204
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
1205
+ if (cfg.userName) myName = cfg.userName;
1206
+ }
1207
+ } catch {}
1208
+ let sent = 0;
1209
+ for (const peer of peers) {
1210
+ if (peer.publicKey === myPk) continue;
1211
+ const sharedForPeer = channels
1212
+ .map(ch => sanitizeChannelForPeer(ch, peer.publicKey))
1213
+ .filter((x): x is Record<string, unknown> => x !== null);
1214
+ if (sharedForPeer.length > 0) {
1215
+ const msg = JSON.stringify({
1216
+ v: 3, op: 'agent.meta.list.reply',
1217
+ payload: { channels: sharedForPeer, name: myName, fromPublicKey: myPk }
1218
+ });
1219
+ const ok = v3P2PRef.sendTo(peer.publicKey, msg);
1220
+ if (ok) {
1221
+ sent++;
1222
+ console.log(`[v3] broadcast: ${peer.name || peer.publicKey.substring(0,8)} → ${sharedForPeer.length} 个 channel`);
1223
+ }
1224
+ }
1225
+ }
1226
+ console.log(`[v3] broadcast 完成: sent=${sent}/${peers.length} 个 peer`);
1227
+ return { sent, total: peers.length };
1228
+ };
1229
+
1119
1230
  try {
1120
1231
  console.log('开始生成 P2P 身份...');
1121
1232
 
@@ -1218,6 +1329,83 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1218
1329
  return Promise.resolve();
1219
1330
  }
1220
1331
  };
1332
+ // v3 新增: 好友申请 RPC — 任何对端可以发, 推到前端 UI 让用户接受
1333
+ if (parsed.op === 'agent.friend.request') {
1334
+ console.log(`[v3-friend] 收到 ${evt.fromPublicKey.substring(0,12)}... 的好友申请: ${parsed.payload?.name || '(无名字)'}`);
1335
+ broadcast({
1336
+ type: 'friend-request',
1337
+ fromPublicKey: evt.fromPublicKey,
1338
+ fromName: parsed.payload?.name || ('peer-' + evt.fromPublicKey.substring(0, 8)),
1339
+ message: parsed.payload?.message || '想加你为 P2P 好友',
1340
+ requestId: parsed.payload?.requestId, // 2026-06-10: 透传 requestId 给前端
1341
+ timestamp: Date.now()
1342
+ }, 'p2p-global');
1343
+ // 2026-06-10 新增: 立刻发 ack 回给发送方, 让发送方 UI 知道"对方收到了"
1344
+ try {
1345
+ const ackRpc = JSON.stringify({
1346
+ v: 3,
1347
+ op: 'agent.friend.request.ack',
1348
+ payload: {
1349
+ requestId: parsed.payload?.requestId,
1350
+ receivedBy: v3P2PRef?.getPublicKey(),
1351
+ timestamp: Date.now()
1352
+ }
1353
+ });
1354
+ v3P2PRef?.sendTo(evt.fromPublicKey, ackRpc);
1355
+ } catch (err) {
1356
+ console.warn('[v3-friend] 发 ack 失败 (不阻塞):', (err as Error).message);
1357
+ }
1358
+ return;
1359
+ }
1360
+ // 2026-06-10 新增: 发送方收到对方 ack → SSE 推前端, 显示"对方已收到"
1361
+ if (parsed.op === 'agent.friend.request.ack') {
1362
+ console.log(`[v3-friend] 收到 ack: requestId=${(parsed.payload?.requestId || '').substring(0,8)} 来自 ${evt.fromPublicKey.substring(0,12)}...`);
1363
+ broadcast({
1364
+ type: 'friend-request-ack',
1365
+ requestId: parsed.payload?.requestId,
1366
+ receivedBy: parsed.payload?.receivedBy,
1367
+ timestamp: Date.now()
1368
+ }, 'p2p-global');
1369
+ return;
1370
+ }
1371
+ // v3 修复: agent.meta.list.reply 也走 v3P2PRef.on('data') (因为 handleV3P2PMessage 只走老通道)
1372
+ if (parsed.op === 'agent.meta.list.reply') {
1373
+ const list = parsed.payload?.channels || [];
1374
+ remoteChannelCache.set(evt.fromPublicKey, list);
1375
+ // 2026-06-10: 持久化到 ~/.bolloon/remote-channels-cache.json, 重启后不丢
1376
+ persistRemoteChannelCache();
1377
+ // 2026-06-10: 接收侧记录对方名字 (来自 list.reply payload.name), 落 known_peers
1378
+ const senderName = parsed.payload?.name;
1379
+ if (senderName && typeof senderName === 'string') {
1380
+ import('../network/known-peers.js').then(({ addOrUpdatePeer }) =>
1381
+ addOrUpdatePeer(senderName, evt.fromPublicKey)
1382
+ ).catch(err => console.warn('[v3] 记录对端名字失败:', (err as Error).message));
1383
+ }
1384
+ console.log(`[v3] 收到 ${evt.fromPublicKey.substring(0,12)}... 的 ${list.length} 个 channel, 已缓存 (sender=${senderName || '?'})`);
1385
+ broadcast({
1386
+ type: 'remote-channel-update',
1387
+ peerId: evt.fromPublicKey,
1388
+ peerName: senderName, // 2026-06-10: 一并带名字到 UI
1389
+ channels: list
1390
+ }, 'p2p-global');
1391
+ return;
1392
+ }
1393
+ // 2026-06-10: 收到对方请求本机的 channel 列表 (启动时主动发请求, 加速 cache 填充)
1394
+ if (parsed.op === 'agent.meta.list.request') {
1395
+ console.log(`[v3-meta] 收到 ${evt.fromPublicKey.substring(0,12)}... 的 channel 列表请求 → 立刻回包`);
1396
+ // 不能 await (在 on('data') sync 回调里), 改用 .then 异步处理
1397
+ loadChannels().then(channels => {
1398
+ const sharedForPeer = channels
1399
+ .map(ch => sanitizeChannelForPeer(ch, evt.fromPublicKey))
1400
+ .filter((x): x is Record<string, unknown> => x !== null);
1401
+ const msg = JSON.stringify({
1402
+ v: 3, op: 'agent.meta.list.reply',
1403
+ payload: { channels: sharedForPeer }
1404
+ });
1405
+ v3P2PRef!.sendTo(evt.fromPublicKey, msg);
1406
+ }).catch(err => console.warn('[v3-meta] 回应 channel 列表失败:', (err as Error).message));
1407
+ return;
1408
+ }
1221
1409
  handleV3P2PMessage(parsed, { id: evt.fromPublicKey, publicKey: evt.fromPublicKey } as any, commShim as any);
1222
1410
  }
1223
1411
  } catch (err) {
@@ -1227,6 +1415,8 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1227
1415
 
1228
1416
  // 新连接进来 → 主动发我分享给 ta 的 channel 列表
1229
1417
  v3P2PRef.on('connection', (evt: any) => {
1418
+ // 2026-06-10: 喂 watchdog —— 新连接到来是真实业务活动
1419
+ watchdogRef?.recordActivity?.();
1230
1420
  setTimeout(async () => {
1231
1421
  try {
1232
1422
  const channels = await loadChannels();
@@ -1266,38 +1456,46 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1266
1456
  }
1267
1457
  // 触发一次 broadcast 推送给所有重连的 peer
1268
1458
  setTimeout(() => v3BroadcastOwn(), 2000);
1459
+ // 2026-06-10: 同时主动请求每个 known peer 把 ta 的 channel 列表推过来
1460
+ // 避免对面 publicKey 没变但 cache 丢了(本机重启) → 一直空
1461
+ setTimeout(() => requestChannelsFromAllPeers(), 3500);
1269
1462
  } catch (err) {
1270
1463
  console.error('[v3] 自动重连失败:', (err as Error).message);
1271
1464
  }
1272
1465
  }, 5000); // 5s 后再重连, 让 swarm 充分 bootstrap
1466
+
1467
+ // 2026-06-10 新增: 主动向所有 known peer 发起 channel 列表请求
1468
+ async function requestChannelsFromAllPeers() {
1469
+ if (!v3P2PRef) return;
1470
+ try {
1471
+ const { listPeers } = await import('../network/known-peers.js');
1472
+ const peers = await listPeers();
1473
+ const myPk = v3P2PRef.getPublicKey();
1474
+ const req = JSON.stringify({ v: 3, op: 'agent.meta.list.request', payload: { fromPublicKey: myPk } });
1475
+ let sent = 0;
1476
+ for (const peer of peers) {
1477
+ if (peer.publicKey === myPk) continue;
1478
+ // 用 sendToWithWait, 等 conn 就绪再发 (同 Step 5 sendToWithWait 修复)
1479
+ const r = await v3P2PRef.sendToWithWait(peer.publicKey, req, 3000);
1480
+ if (r === 'SENT') sent++;
1481
+ }
1482
+ console.log(`[v3-meta] requestChannelsFromAllPeers → sent=${sent}/${peers.length - 1}`);
1483
+ } catch (err) {
1484
+ console.warn('[v3-meta] requestChannelsFromAllPeers failed:', (err as Error).message);
1485
+ }
1486
+ }
1487
+ // 立即跑一次 + 每 30s 兜底 (跟 v3BroadcastOwn 一样的节奏)
1488
+ setTimeout(requestChannelsFromAllPeers, 4000);
1489
+ setInterval(requestChannelsFromAllPeers, 30000);
1273
1490
  } catch (err) {
1274
1491
  console.error('[v3] P2PDirect 启动失败:', (err as Error).message);
1275
1492
  v3P2PRef = null;
1276
1493
  }
1277
1494
 
1278
- // v3: 定期 broadcast 每个 peer 只收到分享给他的 channel (按 peer 个性化)
1279
- const v3BroadcastOwn = () => {
1280
- if (!v3P2PRef) return;
1281
- loadChannels().then(channels => {
1282
- const conns = (v3P2PRef as any).conns as Map<string, any>;
1283
- if (!conns) return;
1284
- for (const [peerPk, conn] of conns.entries()) {
1285
- if (conn?.destroyed) continue;
1286
- const sharedForPeer = channels
1287
- .map(ch => sanitizeChannelForPeer(ch, peerPk))
1288
- .filter((x): x is Record<string, unknown> => x !== null);
1289
- if (sharedForPeer.length > 0) {
1290
- const msg = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: sharedForPeer } });
1291
- try { conn.write(Buffer.from(msg)); } catch {}
1292
- }
1293
- }
1294
- console.log(`[v3] broadcast 个性化: ${conns.size} 个 peer, 各自收到分享的 channel`);
1295
- }).catch(err => console.error('[v3] broadcast 失败:', (err as Error).message));
1296
- };
1495
+ // 首次广播: swarm bootstrap 完成后推一次
1297
1496
  setTimeout(v3BroadcastOwn, 3000);
1298
- setTimeout(v3BroadcastOwn, 10000);
1299
- setTimeout(v3BroadcastOwn, 20000);
1300
- setTimeout(v3BroadcastOwn, 40000);
1497
+ // v3 修复: 用 setInterval 替代一次性 setTimeout, 确保分享变更后能持续推送给 peer
1498
+ setInterval(v3BroadcastOwn, 30000);
1301
1499
 
1302
1500
  // 保留 @diap/sdk 的旧实例 (它的 Hyperswarm 实例能帮 P2PDirect 做 DHT bootstrap)
1303
1501
  try {
@@ -1378,7 +1576,10 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1378
1576
  const channelId = req.query.channelId as string;
1379
1577
  res.setHeader('Content-Type', 'text/event-stream');
1380
1578
  res.setHeader('Cache-Control', 'no-cache');
1381
- res.setHeader('Connection', 'keep-alive');
1579
+ // 2026-06-11: 改 keep-alive → close
1580
+ // 原因: SSE 长连接占着 keep-alive 槽 (HTTP/1.1 + 浏览器 max 6 并发), 后续同源 fetch 排队 30s+
1581
+ // 设 close 让浏览器把 SSE 当长期流, 不抢占普通请求的 keep-alive 槽
1582
+ res.setHeader('Connection', 'close');
1382
1583
  // 反向代理 (nginx/cloudflair) 需要: 禁用缓冲 + 立即 flush
1383
1584
  res.setHeader('X-Accel-Buffering', 'no');
1384
1585
  res.flushHeaders();
@@ -1414,6 +1615,14 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1414
1615
 
1415
1616
  broadcast({ type: 'user', content: text }, channelId);
1416
1617
 
1618
+ // 2026-06-11: /message 端点立即返回 202, LLM 后续处理挪到 setImmediate 后台跑
1619
+ // 之前 res.json 在 try 块末尾 (line 1815), 需要等 LLM (5-15s) + 落盘 + suggestRename (5-8s) = 13s+
1620
+ // 客户端 fetch 占用 13s, 视觉像"卡死", 切其他 channel 也感觉"无法加载"
1621
+ // 修法: 立即 res.json(202), try 块主体仍跑 (LLM 流 + 落盘) 但不阻塞 HTTP 响应
1622
+ // 关键: res.json 之后不能再调用 res.json (会抛 ERR_HTTP_HEADERS_SENT), 所以 try 块末尾的 res.json 必须用 res.headersSent 守卫
1623
+ res.status(202).json({ ok: true, async: true, channelId, sessionId: currentSessionId });
1624
+ console.log(`[v3-async] /message 立即返回 202, channel=${channelId}, text length=${text.length}`);
1625
+
1417
1626
  // 提前捕获 wallet/autoTools 到本地变量, 避免下面 try 块内的 inner const channel
1418
1627
  // (line ~638) 与这里外层的 const channel 形成 shadowing 让 TS 误报"使用前未声明"
1419
1628
  const boundWalletAddress = channel?.walletAddress;
@@ -1463,6 +1672,101 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1463
1672
  const judgmentHint = await buildJudgmentHint(channelForJudgment, channelId);
1464
1673
  if (judgmentHint) contextHint += judgmentHint;
1465
1674
 
1675
+ // 2026-06-10: 注入 skills 列表 (本机 ~/.bolloon/skills/ 下所有 skills)
1676
+ // 让 LLM 知道有哪些 skill 可用, 在回复中提示用户
1677
+ try {
1678
+ const { loadSkillsFromPaths, defaultSkillPaths, describeSkill } = await import('../agents/skill-loader.js');
1679
+ const paths = defaultSkillPaths();
1680
+ const skills = await loadSkillsFromPaths(paths);
1681
+ if (skills.length > 0) {
1682
+ contextHint += `[系统上下文] 本机已加载的 skills (${skills.length} 个, 你可以提示用户主动调用):\n`;
1683
+ for (const s of skills.slice(0, 20)) { // 上限 20 避免 prompt 过长
1684
+ const desc = (s.description || '').slice(0, 80);
1685
+ contextHint += ` - /${s.name}${desc ? ' — ' + desc : ''}\n`;
1686
+ }
1687
+ contextHint += '调用语法: 用户说 "/技能名 ..." 或 你回复时建议 "/技能名 ..." 让用户主动触发.\n\n';
1688
+ }
1689
+ } catch (err) {
1690
+ // 静默失败 — skills 不是核心, 加载失败不阻塞
1691
+ }
1692
+
1693
+ // 2026-06-10: 注入 human values 摘要 (最常用的 judgment / 价值偏好)
1694
+ // 与 judgment 不同: values 是更宏观的"用户偏好", judgment 是针对具体决策的约束
1695
+ try {
1696
+ const { loadAllJudgments } = await import('../pi-ecosystem-judgment/human-value-store.js');
1697
+ const allJudgments = await loadAllJudgments().catch(() => []);
1698
+ // 把所有 judgment 视作软参考 (跟 buildJudgmentHint 的 candidates 同理)
1699
+ if (Array.isArray(allJudgments) && allJudgments.length > 0) {
1700
+ contextHint += `[系统上下文] 用户的核心价值倾向 (来自 ${allJudgments.length} 条历史 judgment, 软参考, 体现而非复述):\n`;
1701
+ for (const j of allJudgments.slice(0, 8)) {
1702
+ const decision = (j.decision || '').slice(0, 80);
1703
+ contextHint += ` - ${decision}\n`;
1704
+ }
1705
+ contextHint += '\n';
1706
+ }
1707
+ } catch (err) {
1708
+ // 静默失败
1709
+ }
1710
+
1711
+ // 2026-06-10: 注入 documents 列表 (本机 documents/ 目录的文档元数据)
1712
+ // 让 LLM 知道有文档存在, 用户可主动要求读
1713
+ try {
1714
+ const { documentStore } = await import('../documents/store.js');
1715
+ const docs = await documentStore.getReceivedDocuments(50).catch(() => []);
1716
+ if (Array.isArray(docs) && docs.length > 0) {
1717
+ contextHint += `[系统上下文] 本机 documents (${docs.length} 篇, 用户可让你读):\n`;
1718
+ for (const d of docs.slice(0, 10)) {
1719
+ const name = d.fileName || d.id || '(未命名)';
1720
+ const size = d.fileSize ? ` (${Math.round(d.fileSize / 1024)}KB)` : '';
1721
+ const sender = d.fromNodeId ? ` [来自 ${d.fromNodeIdShort || d.fromNodeId.substring(0,8)}…]` : '';
1722
+ contextHint += ` - ${name}${size}${sender}\n`;
1723
+ }
1724
+ contextHint += '用户提到某文档时, 你可以调用读文档工具读取并总结.\n\n';
1725
+ }
1726
+ } catch (err) {
1727
+ // 静默失败
1728
+ }
1729
+
1730
+ // 2026-06-11: 注入此 channel 专属的 persona + 关联文档 (从 channel 字段读, LLM 长期记忆)
1731
+ const chPersona = channelForJudgment?.persona;
1732
+ if (chPersona && typeof chPersona === 'object') {
1733
+ contextHint += '[系统上下文] 此 channel 的人设 (你是这个角色):\n';
1734
+ if (chPersona.name) contextHint += ` 名字: ${chPersona.name}\n`;
1735
+ if (chPersona.description) contextHint += ` 描述: ${chPersona.description}\n`;
1736
+ if (chPersona.personality) contextHint += ` 性格: ${chPersona.personality}\n`;
1737
+ if (chPersona.greeting) contextHint += ` 问候: ${chPersona.greeting}\n`;
1738
+ if (Array.isArray(chPersona.capabilities) && chPersona.capabilities.length > 0) {
1739
+ contextHint += ` 能力: ${chPersona.capabilities.join('、')}\n`;
1740
+ }
1741
+ if (Array.isArray(chPersona.interests) && chPersona.interests.length > 0) {
1742
+ contextHint += ` 兴趣: ${chPersona.interests.join('、')}\n`;
1743
+ }
1744
+ contextHint += '回复时应自然体现这个角色 (不要硬搬原文, 像这个角色说话即可).\n\n';
1745
+ }
1746
+ const linkedIds = channelForJudgment?.linkedDocumentIds;
1747
+ if (Array.isArray(linkedIds) && linkedIds.length > 0) {
1748
+ try {
1749
+ const { documentStore } = await import('../documents/store.js');
1750
+ contextHint += `[系统上下文] 此 channel 关联了 ${linkedIds.length} 篇文档 (已自动加载内容, 你应基于它们回答):\n`;
1751
+ let loaded = 0;
1752
+ for (const docId of linkedIds.slice(0, 10)) {
1753
+ const doc = await documentStore.readDocument(docId).catch(() => null);
1754
+ if (!doc) continue;
1755
+ const name = doc.metadata?.fileName || docId;
1756
+ const content = (doc.content || '').slice(0, 1500); // 单篇 1.5KB 上限, 总 prompt 防爆
1757
+ contextHint += `\n--- 文档: ${name} ---\n${content}\n--- 文档结束 ---\n`;
1758
+ loaded++;
1759
+ }
1760
+ if (loaded === 0) {
1761
+ contextHint += `(但加载失败, 文档可能已被删除)\n\n`;
1762
+ } else {
1763
+ contextHint += '\n';
1764
+ }
1765
+ } catch (err) {
1766
+ console.warn('[v3-persona] 加载关联文档失败 (非致命):', (err as Error).message);
1767
+ }
1768
+ }
1769
+
1466
1770
  // v3 新增: 注入"可用渠道"目录, 让 LLM 知道可以 @-mention 哪些 channel
1467
1771
  // - 本地 channels (除了自己)
1468
1772
  // - 远端 channels (remoteChannelCache 缓存的)
@@ -1481,7 +1785,14 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1481
1785
  for (const c of remoteChannels) {
1482
1786
  contextHint += ` - [远端, owner=${(c._ownerPublicKey || '').substring(0,8)}…] @${c.name} (id=${c.id})\n`;
1483
1787
  }
1484
- contextHint += '语法: 当你想给其他渠道发消息, 在回复中写 "@渠道名 我要说的话" 即可. 消息会持久化到目标 channel 的 session, 你之后能看到"自己"在那里说的话.\n\n';
1788
+ contextHint += '语法: 当你想给其他渠道发消息, 在回复中写 "@渠道名 我要说的话" 即可. 消息会持久化到目标 channel 的 session, 你之后能看到"自己"在那里说的话.\n';
1789
+ // 2026-06-10 强化: 当用户消息里出现 @渠道名, 默认是请你代为转发, 务必在回复里包含对应的 @ 转发
1790
+ if (remoteChannels.length > 0) {
1791
+ contextHint += '重要: 上面列表里 [远端] 标记的 channel 在另一台机器上, 你可以像 @本地 channel 一样 @ 它们 — 我会通过 P2P 自动把消息送达对方智能体, 对方智能体的回复也会同步回来.\n';
1792
+ contextHint += '当用户在消息里 @ 了某个 (本地或远端) channel, 默认意图是希望你代为转发 — 你应该在回复中写出对应的 "@渠道名 转发内容", 否则用户的请求不会被路由出去.\n\n';
1793
+ } else {
1794
+ contextHint += '\n';
1795
+ }
1485
1796
  }
1486
1797
 
1487
1798
  if (contextHint) contextHint += '\n';
@@ -1503,25 +1814,21 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
1503
1814
 
1504
1815
  const channels = await loadChannels();
1505
1816
  const channel = channels.find(c => c.id === channelId);
1506
- if (channel && channel.name === '智能体') {
1507
- const renameSuggestion = await agent.suggestRename(session.messages);
1508
- if (renameSuggestion) {
1509
- channel.name = renameSuggestion;
1510
- await saveChannels(channels);
1511
- broadcast({ type: 'renamed', channelId, newName: renameSuggestion }, channelId);
1512
- }
1513
- }
1817
+ // 2026-06-11: 移除 suggestRename 的二次 LLM 调用 — 之前每次用户发消息, 智能体 channel 都会再调一次 LLM (5-8s) 自动改名
1818
+ // 影响: (1) /message 端点被拖慢 5-8s (2) LLM 客户端排队, 其他 channel 跟着卡
1819
+ // 现在改名逻辑挪到 /api/agent-rename 端点, 用户主动触发才跑
1514
1820
  if (channel) {
1515
1821
  channel.updatedAt = new Date().toISOString();
1516
1822
  await saveChannels(channels);
1517
1823
  }
1518
1824
 
1519
1825
  broadcast({ type: 'done' }, channelId);
1520
- res.json({ ok: true });
1826
+ // 2026-06-11: 202 已发的话, 不要重复 res.json (会抛 ERR_HTTP_HEADERS_SENT)
1827
+ if (!res.headersSent) res.json({ ok: true });
1521
1828
  } catch (err: any) {
1522
1829
  broadcast({ type: 'error', content: err.message }, channelId);
1523
1830
  broadcast({ type: 'done' }, channelId);
1524
- res.status(500).json({ error: err.message });
1831
+ if (!res.headersSent) res.status(500).json({ error: err.message });
1525
1832
  }
1526
1833
  });
1527
1834
 
@@ -1649,9 +1956,21 @@ app.get('/channels', async (_req, res) => {
1649
1956
  // v3: 列出本节点缓存的远端 channel (按 peerId 分组)
1650
1957
  app.get('/api/remote-channels', async (_req, res) => {
1651
1958
  try {
1652
- const out: Array<{ peerId: string; channels: Array<Record<string, unknown>> }> = [];
1959
+ const out: Array<{ peerId: string; channels: Array<Record<string, unknown>>; peerName?: string }> = [];
1960
+ // 2026-06-11: 合并 known_peers + cache, 避免 cache 空时 UI 一个 peer 都看不到
1961
+ // (cache 是纯内存, 重启即丢; known_peers 持久化, 至少能让 UI 显示"这些 peer 我认识")
1962
+ const { listPeers } = await import('../network/known-peers.js');
1963
+ const knownPeers = await listPeers();
1964
+ const knownByPk = new Map<string, { name?: string }>();
1965
+ for (const p of knownPeers) knownByPk.set(p.publicKey, { name: p.name });
1653
1966
  for (const [peerId, list] of remoteChannelCache.entries()) {
1654
- out.push({ peerId, channels: list });
1967
+ out.push({ peerId, channels: list, peerName: knownByPk.get(peerId)?.name });
1968
+ }
1969
+ // known_peers 里但 cache 没的, 占位推进 out (channels=[]) 让 UI 能渲染 peer header
1970
+ for (const [peerId, info] of knownByPk.entries()) {
1971
+ if (!remoteChannelCache.has(peerId)) {
1972
+ out.push({ peerId, channels: [], peerName: info.name });
1973
+ }
1655
1974
  }
1656
1975
  res.json({ count: out.length, peers: out });
1657
1976
  } catch (err: any) {
@@ -1659,6 +1978,27 @@ app.get('/channels', async (_req, res) => {
1659
1978
  }
1660
1979
  });
1661
1980
 
1981
+ // v3 测试专用: 直接注入远端频道缓存 (绕过 P2P)
1982
+ // 仅当 NODE_ENV=test 时可用
1983
+ app.post('/api/test/inject-remote-channel', async (req, res) => {
1984
+ if (process.env.NODE_ENV !== 'test') {
1985
+ return res.status(403).json({ error: 'only available in test mode' });
1986
+ }
1987
+ try {
1988
+ const { peerPublicKey, channel } = req.body || {};
1989
+ if (!peerPublicKey || !channel) {
1990
+ return res.status(400).json({ error: 'peerPublicKey and channel required' });
1991
+ }
1992
+ const list = remoteChannelCache.get(peerPublicKey) || [];
1993
+ list.push(channel);
1994
+ remoteChannelCache.set(peerPublicKey, list);
1995
+ broadcast({ type: 'remote-channel-update', peerId: peerPublicKey, channels: list }, 'p2p-global');
1996
+ res.json({ ok: true, count: list.length });
1997
+ } catch (err: any) {
1998
+ res.status(500).json({ error: err.message });
1999
+ }
2000
+ });
2001
+
1662
2002
  // v3: 主动向所有已连接 P2P peer 拉 channel 列表
1663
2003
  // 用法: B 端用户点 "刷新远端智能体" → 触发本 endpoint
1664
2004
  app.post('/api/remote-channels/refresh', async (_req, res) => {
@@ -1738,7 +2078,7 @@ app.get('/channels', async (_req, res) => {
1738
2078
 
1739
2079
  app.post('/channels', async (req, res) => {
1740
2080
  try {
1741
- const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
2081
+ const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids, personaOverride, linkedDocumentIds } = req.body;
1742
2082
  console.log(`[创建频道] 收到请求: name=${name}, agentId=${agentId}, wallet=${walletAddress ? 'yes' : 'no'}, boundJudgments=${Array.isArray(bound_judgment_ids) ? bound_judgment_ids.length : 0}`);
1743
2083
  if (!name || !agentId) {
1744
2084
  return res.status(400).json({ error: 'name and agentId required' });
@@ -1754,6 +2094,42 @@ app.get('/channels', async (_req, res) => {
1754
2094
  ? bound_judgment_ids.filter((x: unknown) => typeof x === 'string' && (x as string).length > 0)
1755
2095
  : [];
1756
2096
 
2097
+ // 2026-06-11: persona 加载 — 优先用 personaOverride, 否则从 ~/.bolloon/persona.json 读全局默认
2098
+ let channelPersona: Channel['persona'];
2099
+ if (personaOverride && typeof personaOverride === 'object') {
2100
+ channelPersona = {
2101
+ name: personaOverride.name,
2102
+ description: personaOverride.description,
2103
+ personality: personaOverride.personality,
2104
+ greeting: personaOverride.greeting,
2105
+ capabilities: Array.isArray(personaOverride.capabilities) ? personaOverride.capabilities.slice(0, 20) : undefined,
2106
+ interests: Array.isArray(personaOverride.interests) ? personaOverride.interests.slice(0, 20) : undefined,
2107
+ };
2108
+ } else {
2109
+ try {
2110
+ const { readFileSync, existsSync } = await import('fs');
2111
+ const personaPath = `${process.env.HOME || '/tmp'}/.bolloon/persona.json`;
2112
+ if (existsSync(personaPath)) {
2113
+ const p = JSON.parse(readFileSync(personaPath, 'utf-8'));
2114
+ channelPersona = {
2115
+ name: p.name,
2116
+ description: p.description,
2117
+ personality: p.personality,
2118
+ greeting: p.greeting,
2119
+ capabilities: Array.isArray(p.capabilities) ? p.capabilities.slice(0, 20) : undefined,
2120
+ interests: Array.isArray(p.interests) ? p.interests.slice(0, 20) : undefined,
2121
+ };
2122
+ }
2123
+ } catch (err) {
2124
+ console.warn('[创建频道] 加载 persona.json 失败 (非致命):', (err as Error).message);
2125
+ }
2126
+ }
2127
+
2128
+ // 过滤 linkedDocumentIds: 只保留 string
2129
+ const safeLinkedDocIds = Array.isArray(linkedDocumentIds)
2130
+ ? linkedDocumentIds.filter((x: unknown) => typeof x === 'string' && (x as string).length > 0).slice(0, 50)
2131
+ : [];
2132
+
1757
2133
  // 先创建频道(不阻塞等待 DID 生成)
1758
2134
  const channel: Channel = {
1759
2135
  id,
@@ -1766,6 +2142,8 @@ app.get('/channels', async (_req, res) => {
1766
2142
  walletRegisteredAt: validWallet ? new Date().toISOString() : undefined,
1767
2143
  autoInvokeTools: autoInvokeTools !== false, // 默认 true
1768
2144
  bound_judgment_ids: safeBoundIds,
2145
+ persona: channelPersona,
2146
+ linkedDocumentIds: safeLinkedDocIds,
1769
2147
  sessions: [{
1770
2148
  id: `sess_${Date.now()}`,
1771
2149
  createdAt: new Date().toISOString(),
@@ -1944,7 +2322,7 @@ app.get('/channels', async (_req, res) => {
1944
2322
  app.patch('/channels/:channelId', async (req, res) => {
1945
2323
  try {
1946
2324
  const { channelId } = req.params;
1947
- const { name, walletAddress, autoInvokeTools, bound_judgment_ids, shared_with_peers } = req.body;
2325
+ const { name, walletAddress, autoInvokeTools, bound_judgment_ids, shared_with_peers, persona, linkedDocumentIds } = req.body;
1948
2326
  const channels = await loadChannels();
1949
2327
  const channel = channels.find(c => c.id === channelId);
1950
2328
  if (!channel) {
@@ -1953,6 +2331,25 @@ app.get('/channels', async (_req, res) => {
1953
2331
  if (typeof name === 'string' && name.trim()) {
1954
2332
  channel.name = name.trim();
1955
2333
  }
2334
+ // 2026-06-11: 改 persona (允许 null 重置回全局默认)
2335
+ if (persona !== undefined) {
2336
+ if (persona === null) {
2337
+ channel.persona = undefined;
2338
+ } else if (typeof persona === 'object') {
2339
+ channel.persona = {
2340
+ name: persona.name,
2341
+ description: persona.description,
2342
+ personality: persona.personality,
2343
+ greeting: persona.greeting,
2344
+ capabilities: Array.isArray(persona.capabilities) ? persona.capabilities.slice(0, 20) : channel.persona?.capabilities,
2345
+ interests: Array.isArray(persona.interests) ? persona.interests.slice(0, 20) : channel.persona?.interests,
2346
+ };
2347
+ }
2348
+ }
2349
+ // 2026-06-11: 改关联文档列表 (数组整体替换, 空数组 = 解绑所有)
2350
+ if (Array.isArray(linkedDocumentIds)) {
2351
+ channel.linkedDocumentIds = linkedDocumentIds.filter((x: unknown) => typeof x === 'string' && (x as string).length > 0).slice(0, 50);
2352
+ }
1956
2353
  // walletAddress 允许 null/'' 来解绑
1957
2354
  if (walletAddress !== undefined) {
1958
2355
  if (walletAddress === null || walletAddress === '') {
@@ -2003,6 +2400,10 @@ app.get('/channels', async (_req, res) => {
2003
2400
  }
2004
2401
  channel.updatedAt = new Date().toISOString();
2005
2402
  await saveChannels(channels);
2403
+ // v3 修复: 分享变更后立即广播给所有 peer, 不用等对方手动刷新
2404
+ if (shared_with_peers !== undefined) {
2405
+ v3BroadcastOwn().catch(err => console.error('[v3] broadcast after share update failed:', err));
2406
+ }
2006
2407
  res.json(channel);
2007
2408
  } catch (err: any) {
2008
2409
  res.status(500).json({ error: err.message });
@@ -2728,13 +3129,24 @@ app.get('/channels', async (_req, res) => {
2728
3129
  }
2729
3130
  });
2730
3131
 
2731
- // v3: 暴露 P2PDirect 自己的 publicKey, 对方可用它主动 connect
3132
+ // v3: 暴露 P2PDirect 自己的 publicKey + 本机名字, 对方可用它主动 connect 并自动取名
2732
3133
  app.get('/api/p2p-publickey', async (_req, res) => {
2733
3134
  try {
2734
3135
  if (!v3P2PRef) {
2735
3136
  return res.status(503).json({ error: 'P2PDirect not started' });
2736
3137
  }
2737
- res.json({ publicKey: v3P2PRef.getPublicKey() });
3138
+ const publicKey = v3P2PRef.getPublicKey();
3139
+ // 2026-06-10: 把本机 user/agent name 一起返回, 对方拿到后能直接用
3140
+ let name = process.env.BOLLOON_USER_NAME || process.env.USER || 'node';
3141
+ try {
3142
+ const { readFileSync, existsSync } = await import('fs');
3143
+ const cfgPath = `${process.env.HOME || '/tmp'}/.bolloon/config.json`;
3144
+ if (existsSync(cfgPath)) {
3145
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
3146
+ if (cfg.userName) name = cfg.userName;
3147
+ }
3148
+ } catch {}
3149
+ res.json({ publicKey, name, role: v3P2PRef.getRole() });
2738
3150
  } catch (err: any) {
2739
3151
  res.status(500).json({ error: err.message });
2740
3152
  }
@@ -2774,6 +3186,37 @@ app.get('/channels', async (_req, res) => {
2774
3186
  res.status(500).json({ error: err.message });
2775
3187
  }
2776
3188
  });
3189
+ // 2026-06-10: PATCH 重命名 / 改备注 / 同时影响 publicKey
3190
+ // 用法: PATCH /api/p2p-peers/:name { name?, notes?, publicKey? }
3191
+ app.patch('/api/p2p-peers/:name', async (req, res) => {
3192
+ try {
3193
+ const { addOrUpdatePeer, removePeer } = await import('../network/known-peers.js');
3194
+ const { readFile, writeFile } = await import('fs/promises');
3195
+ const { existsSync } = await import('fs');
3196
+ const filePath = `${process.env.HOME || '/tmp'}/.bolloon/known_peers.json`;
3197
+ if (!existsSync(filePath)) return res.status(404).json({ error: 'no known_peers.json' });
3198
+ const data = JSON.parse(await readFile(filePath, 'utf-8'));
3199
+ const oldName = req.params.name;
3200
+ const oldEntry = data.peers[oldName];
3201
+ if (!oldEntry) return res.status(404).json({ error: `peer "${oldName}" not found` });
3202
+ const { name: newName, notes, publicKey: newPk } = req.body || {};
3203
+ const finalName = newName || oldName;
3204
+ const finalPk = newPk || oldEntry.publicKey;
3205
+ if (finalName !== oldName) {
3206
+ delete data.peers[oldName];
3207
+ }
3208
+ data.peers[finalName] = {
3209
+ ...oldEntry,
3210
+ publicKey: finalPk,
3211
+ name: finalName,
3212
+ notes: notes !== undefined ? notes : oldEntry.notes
3213
+ };
3214
+ await writeFile(filePath, JSON.stringify(data, null, 2), 'utf-8');
3215
+ res.json({ ok: true, peer: data.peers[finalName] });
3216
+ } catch (err: any) {
3217
+ res.status(500).json({ error: err.message });
3218
+ }
3219
+ });
2777
3220
 
2778
3221
  // v3: 主动 connect 到对端的 P2PDirect publicKey
2779
3222
  // 用法: POST /api/remote-channels/p2p-connect { targetPublicKey: "<hex>" }
@@ -2812,6 +3255,93 @@ app.get('/channels', async (_req, res) => {
2812
3255
  }
2813
3256
  });
2814
3257
 
3258
+ // v3: 主动给对端发好友申请 — 推到对端 UI 让对方接受
3259
+ // 用法: POST /api/friend-request { targetPublicKey, name, message }
3260
+ // 2026-06-10 改: 用 sendToWithWait 等握手完成, 不再 fire-and-forget; 返回结构化 code 让前端知道失败
3261
+ app.post('/api/friend-request', async (req, res) => {
3262
+ try {
3263
+ if (!v3P2PRef) {
3264
+ return res.status(503).json({ ok: false, code: 'P2P_NOT_STARTED', error: 'P2PDirect not started' });
3265
+ }
3266
+ const { targetPublicKey, name, message } = req.body || {};
3267
+ if (!targetPublicKey || typeof targetPublicKey !== 'string' || targetPublicKey.length !== 64) {
3268
+ return res.status(400).json({ ok: false, code: 'BAD_REQUEST', error: 'targetPublicKey (64 hex) required' });
3269
+ }
3270
+ // 先 joinPeer 触发握手 (注意: joinPeer 不阻塞到 conn 就绪)
3271
+ const swarm = (v3P2PRef as any).swarm;
3272
+ if (swarm) {
3273
+ try { await swarm.joinPeer(Buffer.from(targetPublicKey, 'hex')); } catch {}
3274
+ }
3275
+ // 主动把对方加为本机 known_peers (本地视角认为对方是朋友)
3276
+ const { addOrUpdatePeer, findNameByPublicKey } = await import('../network/known-peers.js');
3277
+ const existing = await findNameByPublicKey(targetPublicKey);
3278
+ const peerName = name || existing || `peer-${targetPublicKey.substring(0, 8)}`;
3279
+ await addOrUpdatePeer(peerName, targetPublicKey);
3280
+ // 构造 RPC, 推到对端 — 对端会 SSE 推 friend-request 到前端
3281
+ const myPk = v3P2PRef.getPublicKey();
3282
+ const requestId = crypto.randomUUID();
3283
+ const rpc = JSON.stringify({
3284
+ v: 3,
3285
+ op: 'agent.friend.request',
3286
+ payload: {
3287
+ requestId, // 2026-06-10: 加 requestId, ack 时回带
3288
+ fromPublicKey: myPk,
3289
+ name: peerName,
3290
+ message: message || '想加你为 P2P 好友, 共享 channel 协作'
3291
+ }
3292
+ });
3293
+ // 2026-06-10: 用 sendToWithWait, 等 conn 真就绪后再发, 默认 5s 超时
3294
+ const result = await v3P2PRef.sendToWithWait(targetPublicKey, rpc, 5000);
3295
+ console.log(`[v3-friend] ${myPk.substring(0,12)}... 发送好友申请给 ${targetPublicKey.substring(0,12)}... (result=${result}, requestId=${requestId.substring(0,8)})`);
3296
+ if (result !== 'SENT') {
3297
+ return res.status(502).json({
3298
+ ok: false,
3299
+ code: result, // NO_CONN / WRITE_FAIL
3300
+ error: result === 'NO_CONN'
3301
+ ? '对方未在线, 请确认对方已启动 bolloon 并互联'
3302
+ : '写入 P2P 通道失败, 请重试',
3303
+ persistedAs: peerName // 本地仍持久化, 等对方上线再 retry 即可
3304
+ });
3305
+ }
3306
+ res.json({ ok: true, sent: true, code: 'SENT', persistedAs: peerName, requestId });
3307
+ } catch (err: any) {
3308
+ console.error('[v3-friend] friend-request 失败:', err);
3309
+ res.status(500).json({ ok: false, code: 'EXCEPTION', error: err.message });
3310
+ }
3311
+ });
3312
+
3313
+ // v3: 接受对方的好友申请 — 把对方加为 known_peers, 立即推我的 channel 列表给 ta
3314
+ // 用法: POST /api/friend-accept { fromPublicKey, name }
3315
+ app.post('/api/friend-accept', async (req, res) => {
3316
+ try {
3317
+ if (!v3P2PRef) {
3318
+ return res.status(503).json({ error: 'P2PDirect not started' });
3319
+ }
3320
+ const { fromPublicKey, name } = req.body || {};
3321
+ if (!fromPublicKey || typeof fromPublicKey !== 'string' || fromPublicKey.length !== 64) {
3322
+ return res.status(400).json({ error: 'fromPublicKey (64 hex) required' });
3323
+ }
3324
+ // 持久化
3325
+ const { addOrUpdatePeer, findNameByPublicKey } = await import('../network/known-peers.js');
3326
+ const existing = await findNameByPublicKey(fromPublicKey);
3327
+ const peerName = name || existing || `peer-${fromPublicKey.substring(0, 8)}`;
3328
+ await addOrUpdatePeer(peerName, fromPublicKey);
3329
+ // joinPeer 确保连接存在 (连接可能已在 friend-request 时建立, 这里可能是 no-op)
3330
+ const swarm = (v3P2PRef as any).swarm;
3331
+ if (swarm) {
3332
+ try { await swarm.joinPeer(Buffer.from(fromPublicKey, 'hex')); } catch {}
3333
+ }
3334
+ // v3 修复: 主动广播自己的 channel 列表给新好友,
3335
+ // 不能依赖 connection handler, 因为连接在 friend-request 阶段已建立, 不会触发新 connection 事件
3336
+ v3BroadcastOwn().catch(err => console.error('[v3] broadcast after friend-accept failed:', err));
3337
+ console.log(`[v3-friend] 接受好友申请: ${fromPublicKey.substring(0,12)}... → ${peerName}`);
3338
+ res.json({ ok: true, persistedAs: peerName });
3339
+ } catch (err: any) {
3340
+ console.error('[v3-friend] friend-accept 失败:', err);
3341
+ res.status(500).json({ error: err.message });
3342
+ }
3343
+ });
3344
+
2815
3345
  // v3: 给远端 channel 发消息 (B 节点) - 通过 P2PDirect 转发到 A, A 跑 LLM, 回 B
2816
3346
  // 用法: POST /api/remote-channels/chat-send
2817
3347
  // { targetPublicKey, channelId, text }
@@ -2839,6 +3369,8 @@ app.get('/channels', async (_req, res) => {
2839
3369
  error: 'peer not connected. POST /api/remote-channels/p2p-connect first.'
2840
3370
  });
2841
3371
  }
3372
+ // 2026-06-10: 喂 watchdog — chat-send 成功是真实业务活动
3373
+ watchdogRef?.recordActivity?.();
2842
3374
  console.log(`[v3] chat-send 转发到 ${targetPublicKey.substring(0, 12)}... (channelId=${channelId})`);
2843
3375
  res.json({ ok: true, sent: true });
2844
3376
  } catch (err: any) {
@@ -3785,6 +4317,8 @@ app.get('/channels', async (_req, res) => {
3785
4317
  healthMonitor = createHealthMonitor();
3786
4318
  // 把 watchdog 静默阈值拉到 30 分钟, 避免开发期 / 用户空闲时被误杀
3787
4319
  watchdog = createWatchdog({ silentThresholdMs: 30 * 60 * 1000 });
4320
+ // 2026-06-10: 同步到 module-level, 让 broadcast() / P2P handler / chat-send 都能喂活动
4321
+ watchdogRef = watchdog;
3788
4322
 
3789
4323
  console.log('[24h] Heartbeat modules loaded');
3790
4324
  } catch (err) {
@@ -4138,8 +4672,12 @@ app.get('/channels', async (_req, res) => {
4138
4672
  // level 1 (内存爆) → 进程自杀, 依赖外层 supervisor / 用户重启 (Windows 任务计划/手动)
4139
4673
  // 否则 Node.js 高 GC 压力下 HTTP 响应丢失, 客户端 fetch 永远 pending
4140
4674
  watchdog.registerRestartStrategy(1, () => {
4141
- console.error('[Watchdog] memory critical, 进程退出 (期望外层重启)');
4142
- setTimeout(() => process.exit(1), 100);
4675
+ // 2026-06-10: 改为不退出, 因为我们直接后台 tsx 启动没有外层 supervisor.
4676
+ // 误判主要因 recordActivity 仅在显式调用时刷新, 而 broadcast/SSE/连接均不触发.
4677
+ // 退出策略原文保留在注释里:
4678
+ // console.error('[Watchdog] memory critical, 进程退出 (期望外层重启)');
4679
+ // setTimeout(() => process.exit(1), 100);
4680
+ console.warn('[Watchdog] silentThreshold 触发, 但跳过 process.exit (无 supervisor)');
4143
4681
  });
4144
4682
  watchdog.start();
4145
4683
  console.log('[24h] Watchdog started');
@@ -4299,6 +4837,8 @@ app.get('/channels', async (_req, res) => {
4299
4837
  }
4300
4838
 
4301
4839
  function broadcast(data: { type: string; [key: string]: unknown }, channelId?: string) {
4840
+ // 2026-06-10: 喂 watchdog, 避免 30min 空闲被误判 (recordActivity 内有 5s 去抖)
4841
+ watchdogRef?.recordActivity?.();
4302
4842
  const envelope = { ...data, channelId };
4303
4843
  const message = `data: ${JSON.stringify(envelope)}\n\n`;
4304
4844
  console.log(`[broadcast] type=${data.type}, channelId=${channelId}, clients=${sseClients.size}`);