@bolloon/bolloon-agent 0.1.27 → 0.1.29

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
@@ -74,6 +74,10 @@ interface Channel {
74
74
  sessions?: SessionSummary[];
75
75
  /** 用户在盾牌里手动绑定的判断力 (LLM 跑 channel 时会注入). 默认 []. */
76
76
  bound_judgment_ids?: string[];
77
+ /** v3: 显式共享给哪些 P2P 好友 (peerPublicKey 列表). 只有这些 peer 能看到这个 channel. */
78
+ shared_with_peers?: string[];
79
+ /** v3: 自动生成的 share ID (短字符串), 方便分享给 P2P 好友. */
80
+ share_id?: string;
77
81
  }
78
82
 
79
83
  interface SessionSummary {
@@ -385,6 +389,10 @@ let sseClients: Set<SSEClient> = new Set();
385
389
  // v3: 远端 channel UI 元数据缓存 — key: peerId, value: sanitize 过的 channel 列表
386
390
  // in-memory only, 进程重启清空 (judgment 内容永远不在这里)
387
391
  let remoteChannelCache: Map<string, Array<Record<string, unknown>>> = new Map();
392
+ // v3: P2PDirect 引用 (Hyperswarm 薄包装) - 模块级, 因为 web server 闭包里不可用
393
+ let v3P2PRef: import('../network/p2p-direct.js').P2PDirect | null = null;
394
+ // v3: 等待中的 history RPC (B 端 chat-history endpoint 用) — rpcId → { resolve, reject }
395
+ const v3PendingHistoryGets: Map<string, { resolve: (data: any) => void; reject: (err: Error) => void }> = new Map();
388
396
  let channelSessions: Map<string, AgentSession> = new Map(); // key: channelId
389
397
  let sessionMessages: Map<string, any[]> = new Map(); // key: channelId + sessionId
390
398
 
@@ -400,8 +408,21 @@ let sessionMessages: Map<string, any[]> = new Map(); // key: channelId + session
400
408
  * v3: 过滤 channel 元数据, 只返回对远端 peer 安全的字段.
401
409
  * 关键: bound_judgment_ids / walletBinding / autoInvokeTools 内部状态不外传.
402
410
  * judgment 内容永远不会出现在 RPC 响应里 (judgment 始终在 A 节点内存, 由 A 跑 LLM).
411
+ *
412
+ * Phase 3 分享模式: 加 peerPublicKey 参数 — 只有 shared_with_peers 包含此 peer 的 channel 才返回.
413
+ * peerPublicKey 不传 = admin 路径, 返回所有 channel (老行为).
403
414
  */
404
- function sanitizeChannelForPeer(ch: Channel): Record<string, unknown> {
415
+ function sanitizeChannelForPeer(
416
+ ch: Channel,
417
+ peerPublicKey?: string
418
+ ): Record<string, unknown> | null {
419
+ // Phase 3 核心: 分享过滤
420
+ if (peerPublicKey) {
421
+ const shared = Array.isArray(ch.shared_with_peers) ? ch.shared_with_peers : [];
422
+ if (!shared.includes(peerPublicKey)) {
423
+ return null; // 没分享给这个 peer, 不返回
424
+ }
425
+ }
405
426
  return {
406
427
  id: ch.id,
407
428
  name: ch.name,
@@ -409,12 +430,284 @@ function sanitizeChannelForPeer(ch: Channel): Record<string, unknown> {
409
430
  publicKey: ch.publicKey,
410
431
  createdAt: ch.createdAt,
411
432
  updatedAt: ch.updatedAt,
412
- hasWallet: !!ch.walletAddress, // 只告诉 B "有没有钱包", 不传地址
433
+ hasWallet: !!ch.walletAddress,
413
434
  boundJudgmentCount: Array.isArray(ch.bound_judgment_ids) ? ch.bound_judgment_ids.length : 0,
414
- // 🔒 不返回: bound_judgment_ids, walletAddress, walletBinding, autoInvokeTools, sessions
435
+ share_id: ch.share_id,
436
+ // 🔒 不返回: bound_judgment_ids, walletAddress, walletBinding, autoInvokeTools, sessions, shared_with_peers
415
437
  };
416
438
  }
417
439
 
440
+ /** v3 新增: 判断 channel 是否分享给 peerPublicKey */
441
+ function isSharedWith(ch: Channel, peerPublicKey: string): boolean {
442
+ const shared = Array.isArray(ch.shared_with_peers) ? ch.shared_with_peers : [];
443
+ return shared.includes(peerPublicKey);
444
+ }
445
+
446
+ /**
447
+ * v3: 处理 Hyperswarm 通道收到的 v3 RPC 消息
448
+ * 设计: 用 HyperswarmCommunicator (DHT topic 自动发现) 取代 iroh 直接 connect
449
+ * - A 启动 → broadcast(agent.meta.list.reply) → 所有已连接 peer 缓存 A 的 channel
450
+ * - B 启动 → 同样 broadcast
451
+ * - 任何节点收到 list 请求 → 回 list.reply
452
+ */
453
+ async function handleV3P2PMessage(parsed: any, conn: P2PConnection, comm: HyperswarmCommunicator): Promise<void> {
454
+ const op = parsed.op;
455
+ const peerKey = conn.publicKey;
456
+
457
+ if (op === 'agent.meta.list') {
458
+ // 对方问我的 channel 列表 — 只返回分享给他的
459
+ try {
460
+ const channels = await loadChannels();
461
+ const publicMeta = channels
462
+ .map(ch => sanitizeChannelForPeer(ch, peerKey))
463
+ .filter((x): x is Record<string, unknown> => x !== null);
464
+ const reply = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: publicMeta } });
465
+ await comm.sendToConnection(conn.id, reply);
466
+ console.log(`[v3] 回 ${peerKey.substring(0,12)}... list.reply (${publicMeta.length} 个分享给 ta)`);
467
+ } catch (err) {
468
+ console.error('[v3] 处理 agent.meta.list 失败:', (err as Error).message);
469
+ }
470
+ return;
471
+ }
472
+
473
+ if (op === 'agent.meta.list.reply') {
474
+ // 对方把他自己的 channel 列表推给我 — 缓存
475
+ const list = parsed.payload?.channels || [];
476
+ remoteChannelCache.set(peerKey, list);
477
+ console.log(`[v3] 收到 ${peerKey.substring(0,12)}... 的 ${list.length} 个 channel, 已缓存`);
478
+ broadcast({
479
+ type: 'remote-channel-update',
480
+ peerId: peerKey,
481
+ channels: list
482
+ }, 'p2p-global');
483
+ return;
484
+ }
485
+
486
+ if (op === 'agent.meta.get') {
487
+ // 对方问单条 channel — 回
488
+ const channelId = parsed.payload?.channelId;
489
+ if (channelId) {
490
+ const channels = await loadChannels();
491
+ const ch = channels.find(c => c.id === channelId);
492
+ if (ch) {
493
+ // Phase 3: 分享过滤 — 必须分享给该 peer
494
+ const sanitized = sanitizeChannelForPeer(ch, peerKey);
495
+ if (sanitized) {
496
+ const reply = JSON.stringify({ v: 3, op: 'agent.meta.get.reply', payload: { channel: sanitized } });
497
+ await comm.sendToConnection(conn.id, reply);
498
+ } else {
499
+ const reply = JSON.stringify({ v: 3, op: 'agent.meta.get.reply', payload: { error: 'not shared with you' } });
500
+ await comm.sendToConnection(conn.id, reply);
501
+ }
502
+ }
503
+ }
504
+ return;
505
+ }
506
+
507
+ if (op === 'agent.meta.get.reply') {
508
+ const ch = parsed.payload?.channel;
509
+ if (ch && ch.id) {
510
+ const list = remoteChannelCache.get(peerKey) || [];
511
+ const idx = list.findIndex((c: any) => c.id === ch.id);
512
+ if (idx >= 0) list[idx] = ch;
513
+ else list.push(ch);
514
+ remoteChannelCache.set(peerKey, list);
515
+ broadcast({
516
+ type: 'remote-channel-update',
517
+ peerId: peerKey,
518
+ channels: list
519
+ }, 'p2p-global');
520
+ }
521
+ return;
522
+ }
523
+
524
+ if (op === 'agent.chat.send') {
525
+ // B 端发来: 在 A 节点上对 channelId 跑 LLM, 结果回 B
526
+ // judgment 永远在 A 节点 (buildJudgmentHint 已经用 bound_judgment_ids)
527
+ const { channelId, text, fromPublicKey } = parsed.payload || {};
528
+ if (!channelId || !text) {
529
+ console.warn(`[v3] agent.chat.send 缺少 channelId/text`);
530
+ return;
531
+ }
532
+ const senderKey = fromPublicKey || peerKey;
533
+ console.log(`[v3] 收到 ${senderKey.substring(0,12)}... 对 channel ${channelId} 的 chat: "${text.substring(0, 40)}..."`);
534
+ try {
535
+ // 1. 找到 channel
536
+ const channels = await loadChannels();
537
+ const ch = channels.find(c => c.id === channelId);
538
+ if (!ch) {
539
+ const reply = JSON.stringify({
540
+ v: 3, op: 'agent.chat.reply',
541
+ payload: { channelId, fromPublicKey: v3P2PRef?.getPublicKey() || '', error: 'channel not found', text: '' }
542
+ });
543
+ await comm.sendToConnection(conn.id, reply);
544
+ return;
545
+ }
546
+ // v3 新增: 持久化 B 的 user 消息到 A 的 session — 让历史可拉
547
+ try {
548
+ const existing = await loadSession(channelId, 'default');
549
+ const session: Session = existing || {
550
+ channelId, sessionId: 'default', messages: [], lastUpdated: new Date().toISOString()
551
+ };
552
+ session.messages.push({
553
+ id: `msg-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
554
+ type: 'user',
555
+ content: text,
556
+ timestamp: new Date().toISOString()
557
+ });
558
+ session.lastUpdated = new Date().toISOString();
559
+ await saveSession(session);
560
+ console.log(`[v3] (${channelId}) 存 user 消息 (${text.length} chars) 到 A 的 session`);
561
+ } catch (saveErr) {
562
+ console.warn(`[v3] 存 user 消息失败 (不影响 chat):`, (saveErr as Error).message);
563
+ }
564
+
565
+ // v3 新增: 告诉 B "我开始想了, 用了哪些 judgment" — 让 B 看到决策依据
566
+ const judgmentHint = await buildJudgmentHint(ch, channelId);
567
+ const usedJudgments = await extractJudgmentsFromHint(ch);
568
+ try {
569
+ const thinkingStart = JSON.stringify({
570
+ v: 3, op: 'agent.chat.thinking',
571
+ payload: {
572
+ channelId,
573
+ phase: 'start',
574
+ fromPublicKey: v3P2PRef?.getPublicKey() || '',
575
+ hint: judgmentHint,
576
+ usedJudgments,
577
+ userText: text
578
+ }
579
+ });
580
+ await comm.sendToConnection(conn.id, thinkingStart);
581
+ } catch {}
582
+
583
+ // 2. 跑 LLM (复用 Phase 1 的 buildJudgmentHint — 注入 channel 的 judgment)
584
+ const { getMinimax } = await import('../constraints/index.js');
585
+ const llm = getMinimax();
586
+ const fullPrompt = `${judgmentHint}${text}`;
587
+ let fullResponse = '';
588
+ // v3 新增: 流式 token 节流推给 B — 让 B 看到过程
589
+ let lastFlushAt = 0;
590
+ const streamCallback: any = (event: any) => {
591
+ if (event.type === 'token') {
592
+ fullResponse += event.content;
593
+ if (fullResponse.length - lastFlushAt >= 20) {
594
+ lastFlushAt = fullResponse.length;
595
+ const msg = JSON.stringify({
596
+ v: 3, op: 'agent.chat.thinking',
597
+ payload: { channelId, phase: 'token', partial: fullResponse, fromPublicKey: v3P2PRef?.getPublicKey() || '' }
598
+ });
599
+ comm.sendToConnection(conn.id, msg).catch(() => {});
600
+ }
601
+ }
602
+ };
603
+ const agent = await getAgentForChannel(channelId, ch.did || '', ch.name, ch.didDocRef);
604
+ fullResponse = await agent.promptStream(fullPrompt, streamCallback);
605
+
606
+ // v3 新增: 存 A 的 assistant 消息到 session — B 拉历史时能看到完整对话
607
+ try {
608
+ const existing = await loadSession(channelId, 'default');
609
+ const session: Session = existing || {
610
+ channelId, sessionId: 'default', messages: [], lastUpdated: new Date().toISOString()
611
+ };
612
+ session.messages.push({
613
+ id: `msg-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
614
+ type: 'ai',
615
+ content: fullResponse,
616
+ timestamp: new Date().toISOString()
617
+ });
618
+ session.lastUpdated = new Date().toISOString();
619
+ await saveSession(session);
620
+ console.log(`[v3] (${channelId}) 存 assistant 回复 (${fullResponse.length} chars) 到 A 的 session`);
621
+ } catch (saveErr) {
622
+ console.warn(`[v3] 存 assistant 消息失败 (不影响):`, (saveErr as Error).message);
623
+ }
624
+
625
+ // 3. 把完整回复发给 B
626
+ const reply = JSON.stringify({
627
+ v: 3, op: 'agent.chat.reply',
628
+ payload: {
629
+ channelId,
630
+ fromPublicKey: v3P2PRef?.getPublicKey() || '',
631
+ text: fullResponse
632
+ }
633
+ });
634
+ await comm.sendToConnection(conn.id, reply);
635
+ console.log(`[v3] 回 chat.reply 给 ${senderKey.substring(0,12)}... (${fullResponse.length} chars)`);
636
+ } catch (err) {
637
+ console.error(`[v3] agent.chat.send 处理失败:`, (err as Error).message);
638
+ try {
639
+ const reply = JSON.stringify({
640
+ v: 3, op: 'agent.chat.reply',
641
+ payload: { channelId, fromPublicKey: v3P2PRef?.getPublicKey() || '', error: (err as Error).message, text: '' }
642
+ });
643
+ await comm.sendToConnection(conn.id, reply);
644
+ } catch {}
645
+ }
646
+ return;
647
+ }
648
+
649
+ if (op === 'agent.history.get') {
650
+ // v3 新增: B 拉 A 的 channel 历史 (含所有 message + judgment hint)
651
+ // 共享过滤: 只返回 B 可见的 channel + 包含的 judgment
652
+ const { channelId, rpcId, fromPublicKey } = parsed.payload || {};
653
+ if (!channelId || !rpcId) {
654
+ console.warn(`[v3] agent.history.get 缺少 channelId/rpcId`);
655
+ return;
656
+ }
657
+ try {
658
+ const channels = await loadChannels();
659
+ const ch = channels.find(c => c.id === channelId);
660
+ if (!ch) {
661
+ const err = JSON.stringify({
662
+ v: 3, op: 'agent.history.get.reply',
663
+ payload: { rpcId, error: 'channel not found', messages: [], judgments: { bound: [], candidates: [] } }
664
+ });
665
+ await comm.sendToConnection(conn.id, err);
666
+ return;
667
+ }
668
+ // 共享过滤: 必须 peerKey 在 shared_with_peers 里 (避免泄露未分享的 channel)
669
+ const peerKey = fromPublicKey;
670
+ if (!peerKey || !isSharedWith(ch, peerKey)) {
671
+ const err = JSON.stringify({
672
+ v: 3, op: 'agent.history.get.reply',
673
+ payload: { rpcId, error: 'channel not shared with you', messages: [], judgments: { bound: [], candidates: [] } }
674
+ });
675
+ await comm.sendToConnection(conn.id, err);
676
+ return;
677
+ }
678
+ // 加载 A 端 session
679
+ const session = await loadSession(channelId, 'default');
680
+ // 加载 channel 用到的 judgment
681
+ const judgments = await extractJudgmentsFromHint(ch);
682
+ const reply = JSON.stringify({
683
+ v: 3, op: 'agent.history.get.reply',
684
+ payload: {
685
+ rpcId,
686
+ channelId,
687
+ messages: session?.messages || [],
688
+ lastUpdated: session?.lastUpdated,
689
+ judgments,
690
+ channelName: ch.name
691
+ }
692
+ });
693
+ await comm.sendToConnection(conn.id, reply);
694
+ console.log(`[v3] 回 history.reply 给 ${peerKey.substring(0,12)}... (channelId=${channelId}, ${session?.messages?.length || 0} messages)`);
695
+ } catch (err) {
696
+ console.error(`[v3] agent.history.get 处理失败:`, (err as Error).message);
697
+ try {
698
+ const errMsg = JSON.stringify({
699
+ v: 3, op: 'agent.history.get.reply',
700
+ payload: { rpcId, error: (err as Error).message, messages: [], judgments: { bound: [], candidates: [] } }
701
+ });
702
+ await comm.sendToConnection(conn.id, errMsg);
703
+ } catch {}
704
+ }
705
+ return;
706
+ }
707
+
708
+ console.log(`[v3] 收到未知 op: ${op}`);
709
+ }
710
+
418
711
  async function buildJudgmentHint(
419
712
  channel: Channel | undefined | null,
420
713
  channelIdForLog: string
@@ -469,6 +762,47 @@ async function buildJudgmentHint(
469
762
  }
470
763
  }
471
764
 
765
+ /**
766
+ * v3 新增: 把 channel 当前用到的 judgment 提取成结构化数据, 给 B 端 UI 显示.
767
+ * 返回 { bound: [...], candidates: [...] } — bound 是硬绑定, candidates 是参考池.
768
+ */
769
+ async function extractJudgmentsFromHint(
770
+ channel: Channel | undefined | null
771
+ ): Promise<{ bound: any[]; candidates: any[] }> {
772
+ try {
773
+ const { loadAllJudgments, initializeValueStore } = await import(
774
+ '../pi-ecosystem-judgment/human-value-store.js'
775
+ );
776
+ await initializeValueStore();
777
+ const allJudgments = await loadAllJudgments();
778
+ if (allJudgments.length === 0) return { bound: [], candidates: [] };
779
+
780
+ const boundIds = new Set(
781
+ channel && Array.isArray(channel.bound_judgment_ids) ? channel.bound_judgment_ids : []
782
+ );
783
+
784
+ const summarize = (j: any) => ({
785
+ id: j.id,
786
+ decision: (j.decision || '').toString().slice(0, 200),
787
+ reasons: Array.isArray(j.reasons) ? j.reasons : [],
788
+ domain: j.domain,
789
+ stakes: j.stakes
790
+ });
791
+
792
+ const bound = allJudgments
793
+ .filter((j: any) => j.id !== undefined && boundIds.has(j.id))
794
+ .map(summarize);
795
+ const candidates = allJudgments
796
+ .filter((j: any) => j.id !== undefined && !boundIds.has(j.id))
797
+ .map(summarize);
798
+
799
+ return { bound, candidates };
800
+ } catch (err) {
801
+ console.warn(`[v3] extractJudgmentsFromHint 失败:`, (err as Error).message);
802
+ return { bound: [], candidates: [] };
803
+ }
804
+ }
805
+
472
806
  async function getAgentForChannel(
473
807
  channelId: string,
474
808
  channelDid?: string,
@@ -602,7 +936,157 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
602
936
  console.log('P2P DID 本地模式运行');
603
937
  }
604
938
 
605
- // 初始化 P2P 通信器
939
+ // v3: 完全用 P2PDirect 取代 @diap/sdk 的 HyperswarmCommunicator
940
+ // 原因: @diap/sdk 的 sendToConnection 是 stub, 不真发数据
941
+ // 这里故意不启动 p2pCommunicator (保持 null), 让 P2PDirect 独占 hyperswarm 通道
942
+ try {
943
+ const { P2PDirect } = await import('../network/p2p-direct.js');
944
+ v3P2PRef = new P2PDirect({ name: 'v3' });
945
+ await v3P2PRef.start();
946
+ await v3P2PRef.joinTopic(Buffer.from('bolloon-agent-harness'));
947
+
948
+ v3P2PRef.on('data', (evt: any) => {
949
+ try {
950
+ const parsed = JSON.parse(evt.data.toString('utf-8'));
951
+ if (parsed && parsed.v === 3 && parsed.op) {
952
+ // v3 跨用户 chat: B 端收到 A 的 chat.reply, 直接 SSE 推给前端
953
+ if (parsed.op === 'agent.chat.reply') {
954
+ console.log(`[v3] 收到来自 ${evt.fromPublicKey.substring(0,12)}... 的 chat.reply (${(parsed.payload?.text || '').length} chars)`);
955
+ broadcast({
956
+ type: 'remote-chat-reply',
957
+ fromPublicKey: evt.fromPublicKey,
958
+ channelId: parsed.payload?.channelId,
959
+ text: parsed.payload?.text || '',
960
+ error: parsed.payload?.error
961
+ }, 'p2p-global');
962
+ return;
963
+ }
964
+ // v3 新增: B 端收到 A 的 thinking (开始 + 流式 token)
965
+ if (parsed.op === 'agent.chat.thinking') {
966
+ const phase = parsed.payload?.phase;
967
+ if (phase === 'start') {
968
+ console.log(`[v3] 收到来自 ${evt.fromPublicKey.substring(0,12)}... 的 thinking start (judgments: bound=${(parsed.payload?.usedJudgments?.bound || []).length}, candidates=${(parsed.payload?.usedJudgments?.candidates || []).length})`);
969
+ }
970
+ broadcast({
971
+ type: 'remote-chat-thinking',
972
+ fromPublicKey: evt.fromPublicKey,
973
+ channelId: parsed.payload?.channelId,
974
+ phase: parsed.payload?.phase,
975
+ partial: parsed.payload?.partial,
976
+ hint: parsed.payload?.hint,
977
+ usedJudgments: parsed.payload?.usedJudgments,
978
+ userText: parsed.payload?.userText
979
+ }, 'p2p-global');
980
+ return;
981
+ }
982
+ // v3 新增: B 端收到 A 的 history reply → resolve pending promise
983
+ if (parsed.op === 'agent.history.get.reply') {
984
+ const rpcId = parsed.payload?.rpcId;
985
+ if (rpcId && v3PendingHistoryGets.has(rpcId)) {
986
+ const pending = v3PendingHistoryGets.get(rpcId)!;
987
+ v3PendingHistoryGets.delete(rpcId);
988
+ if (parsed.payload?.error) {
989
+ pending.reject(new Error(parsed.payload.error));
990
+ } else {
991
+ pending.resolve({
992
+ channelId: parsed.payload.channelId,
993
+ messages: parsed.payload.messages || [],
994
+ lastUpdated: parsed.payload.lastUpdated,
995
+ judgments: parsed.payload.judgments || { bound: [], candidates: [] },
996
+ channelName: parsed.payload.channelName
997
+ });
998
+ }
999
+ }
1000
+ return;
1001
+ }
1002
+ const commShim = {
1003
+ sendToConnection: (_id: string, data: string) => {
1004
+ v3P2PRef!.sendTo(evt.fromPublicKey, data);
1005
+ return Promise.resolve();
1006
+ }
1007
+ };
1008
+ handleV3P2PMessage(parsed, { id: evt.fromPublicKey, publicKey: evt.fromPublicKey } as any, commShim as any);
1009
+ }
1010
+ } catch (err) {
1011
+ console.error('[v3-P2PDirect] 解析/处理消息失败:', (err as Error).message);
1012
+ }
1013
+ });
1014
+
1015
+ // 新连接进来 → 主动发我分享给 ta 的 channel 列表
1016
+ v3P2PRef.on('connection', (evt: any) => {
1017
+ setTimeout(async () => {
1018
+ try {
1019
+ const channels = await loadChannels();
1020
+ const publicMeta = channels
1021
+ .map(ch => sanitizeChannelForPeer(ch, evt.remotePublicKey))
1022
+ .filter((x): x is Record<string, unknown> => x !== null);
1023
+ const msg = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: publicMeta } });
1024
+ v3P2PRef!.sendTo(evt.remotePublicKey, msg);
1025
+ console.log(`[v3] 新连接 ${evt.remotePublicKey.substring(0,12)}... → 发 ${publicMeta.length} 个分享给 ta`);
1026
+ } catch (err) {
1027
+ console.error('[v3] 新连接发 list.reply 失败:', (err as Error).message);
1028
+ }
1029
+ }, 500);
1030
+ });
1031
+
1032
+ console.log(`[v3] P2PDirect 已启动, role=${v3P2PRef.getRole()}, publicKey=${v3P2PRef.getPublicKey().substring(0,12)}...`);
1033
+
1034
+ // v3: 启动后自动重连 known peers — 让"启动就互联"成为现实
1035
+ setTimeout(async () => {
1036
+ try {
1037
+ const { listPeers, markConnected } = await import('../network/known-peers.js');
1038
+ const peers = await listPeers();
1039
+ if (peers.length === 0) {
1040
+ console.log(`[v3] 没有 known peers, 跳过自动重连`);
1041
+ return;
1042
+ }
1043
+ const swarm = (v3P2PRef as any).swarm;
1044
+ if (!swarm) return;
1045
+ for (const peer of peers) {
1046
+ try {
1047
+ await swarm.joinPeer(Buffer.from(peer.publicKey, 'hex'));
1048
+ await markConnected(peer.name || '');
1049
+ console.log(`[v3] 自动重连 ${peer.name} (${peer.publicKey.substring(0, 12)}...) ✓`);
1050
+ } catch (err) {
1051
+ console.warn(`[v3] 自动重连 ${peer.name} 失败:`, (err as Error).message);
1052
+ }
1053
+ }
1054
+ // 触发一次 broadcast 推送给所有重连的 peer
1055
+ setTimeout(() => v3BroadcastOwn(), 2000);
1056
+ } catch (err) {
1057
+ console.error('[v3] 自动重连失败:', (err as Error).message);
1058
+ }
1059
+ }, 5000); // 5s 后再重连, 让 swarm 充分 bootstrap
1060
+ } catch (err) {
1061
+ console.error('[v3] P2PDirect 启动失败:', (err as Error).message);
1062
+ v3P2PRef = null;
1063
+ }
1064
+
1065
+ // v3: 定期 broadcast — 每个 peer 只收到分享给他的 channel (按 peer 个性化)
1066
+ const v3BroadcastOwn = () => {
1067
+ if (!v3P2PRef) return;
1068
+ loadChannels().then(channels => {
1069
+ const conns = (v3P2PRef as any).conns as Map<string, any>;
1070
+ if (!conns) return;
1071
+ for (const [peerPk, conn] of conns.entries()) {
1072
+ if (conn?.destroyed) continue;
1073
+ const sharedForPeer = channels
1074
+ .map(ch => sanitizeChannelForPeer(ch, peerPk))
1075
+ .filter((x): x is Record<string, unknown> => x !== null);
1076
+ if (sharedForPeer.length > 0) {
1077
+ const msg = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: sharedForPeer } });
1078
+ try { conn.write(Buffer.from(msg)); } catch {}
1079
+ }
1080
+ }
1081
+ console.log(`[v3] broadcast 个性化: ${conns.size} 个 peer, 各自收到分享的 channel`);
1082
+ }).catch(err => console.error('[v3] broadcast 失败:', (err as Error).message));
1083
+ };
1084
+ setTimeout(v3BroadcastOwn, 3000);
1085
+ setTimeout(v3BroadcastOwn, 10000);
1086
+ setTimeout(v3BroadcastOwn, 20000);
1087
+ setTimeout(v3BroadcastOwn, 40000);
1088
+
1089
+ // 保留 @diap/sdk 的旧实例 (它的 Hyperswarm 实例能帮 P2PDirect 做 DHT bootstrap)
606
1090
  try {
607
1091
  const rawSeed = crypto.getRandomValues(new Uint8Array(32));
608
1092
  p2pCommunicator = createHyperswarmCommunicator({
@@ -612,24 +1096,19 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
612
1096
  maxConnections: 50,
613
1097
  seed: rawSeed
614
1098
  } as any);
615
-
616
- p2pCommunicator.on('connection', (conn: P2PConnection) => {
617
- console.log(`P2P 连接: ${conn.publicKey.substring(0, 8)}...`);
618
- });
619
-
620
1099
  p2pCommunicator.on('message', async (msg: any, conn: P2PConnection) => {
1100
+ // 旧 p2p_message 路径 (非 v3)
621
1101
  const content = new TextDecoder().decode(msg.content);
622
- console.log(`P2P 收到消息: ${content.substring(0, 50)}...`);
623
- // 可以在这里处理接收到的消息
624
1102
  broadcast({ type: 'p2p_message', from: conn.publicKey.substring(0, 8), content }, undefined);
625
1103
  });
626
-
627
1104
  await p2pCommunicator.start();
628
- const topic = createTopic('bolloon-agent-harness') as Buffer;
629
- await p2pCommunicator.joinTopic(topic);
630
- console.log(`P2P 网络已就绪`);
1105
+ // @diap/sdk 也 join topic 它的 Hyperswarm 实例帮 P2PDirect 做 DHT 引导
1106
+ // @diap/sdk 收到的数据是 mock (不真发), 但 DHT 发现 + 节点连接是 OK 的
1107
+ const oldTopic = createTopic('bolloon-agent-harness') as Buffer;
1108
+ await p2pCommunicator.joinTopic(oldTopic);
1109
+ console.log(`P2P 老通道已就绪 (DHT bootstrap 帮 P2PDirect, 实际数据走 P2PDirect)`);
631
1110
  } catch (e: any) {
632
- console.log(`P2P 网络初始化失败: ${e.message}`);
1111
+ console.log(`P2P 老通道初始化失败: ${e.message}`);
633
1112
  }
634
1113
  } catch (e: any) {
635
1114
  console.log(`P2P 身份初始化失败: ${e.message}`);
@@ -944,6 +1423,25 @@ app.get('/channels', async (_req, res) => {
944
1423
  // 用法: B 端用户点 "刷新远端智能体" → 触发本 endpoint
945
1424
  app.post('/api/remote-channels/refresh', async (_req, res) => {
946
1425
  try {
1426
+ // Phase 3: 优先用 P2PDirect conns (Phase 2/3 的真实通道)
1427
+ if (v3P2PRef) {
1428
+ const conns = (v3P2PRef as any).conns as Map<string, any>;
1429
+ const peerIds = Array.from(conns.keys()).filter(pk => {
1430
+ const c = conns.get(pk);
1431
+ return c && !c.destroyed;
1432
+ });
1433
+ if (peerIds.length === 0) {
1434
+ return res.json({ ok: true, sent: 0, note: 'no connected peers (P2PDirect)' });
1435
+ }
1436
+ // 让每个 peer 拉 list — Phase 3 个性化分享过滤
1437
+ let sent = 0;
1438
+ for (const peerPk of peerIds) {
1439
+ const ok = await (v3P2PRef as any).sendTo(peerPk, JSON.stringify({ v: 3, op: 'agent.meta.list', payload: {} }));
1440
+ if (ok) sent++;
1441
+ }
1442
+ return res.json({ ok: true, sent, total: peerIds.length });
1443
+ }
1444
+ // Fallback: 老 iroh 路径
947
1445
  const peers = irohTransport.getPeers ? irohTransport.getPeers() : [];
948
1446
  const peerIds = Array.isArray(peers) ? peers.map((p: any) => p.nodeId || p) : [];
949
1447
  if (peerIds.length === 0) {
@@ -964,6 +1462,40 @@ app.get('/channels', async (_req, res) => {
964
1462
  }
965
1463
  });
966
1464
 
1465
+ // ===== v3: 主动 connect 到对端, 再发 agent.meta.list =====
1466
+ // 用法: POST /api/remote-channels/connect { targetAddr: "<完整 EndpointAddr 含 relay URL>" }
1467
+ // targetAddr 应来自对端 GET /api/iroh-addr (完整字符串, 不只是 nodeId)
1468
+ // 兼容旧用法: 也接受 targetNodeId, 但只有 nodeId 不一定能 connect 成功
1469
+ app.post('/api/remote-channels/connect', async (req, res) => {
1470
+ try {
1471
+ const { targetAddr, targetNodeId } = req.body || {};
1472
+ const target = targetAddr || targetNodeId;
1473
+ if (!target || typeof target !== 'string') {
1474
+ return res.status(400).json({ error: 'targetAddr (or targetNodeId) required' });
1475
+ }
1476
+ console.log(`[v3] 主动 connect 到 ${target.substring(0, 32)}...`);
1477
+ // iroh connect 接受 nodeId 或完整 addr 字符串 — 用完整 addr 才会成功
1478
+ const ok = await irohTransport.connect(target);
1479
+ if (!ok) {
1480
+ return res.status(502).json({
1481
+ error: 'connect failed',
1482
+ hint: '传 targetAddr (完整 EndpointAddr 字符串, 含 relay URL) 而非仅 nodeId'
1483
+ });
1484
+ }
1485
+ // 立即发 agent.meta.list 请求对端返回元数据
1486
+ const sent = await irohTransport.sendMessage(
1487
+ target,
1488
+ 'agent.meta.list',
1489
+ new TextEncoder().encode('{}')
1490
+ );
1491
+ console.log(`[v3] connect+list 发送结果: connect=ok, list=${sent}`);
1492
+ res.json({ ok: true, connected: true, sent, target });
1493
+ } catch (err: any) {
1494
+ console.error('[v3] /api/remote-channels/connect 失败:', err);
1495
+ res.status(500).json({ error: err.message });
1496
+ }
1497
+ });
1498
+
967
1499
  app.post('/channels', async (req, res) => {
968
1500
  try {
969
1501
  const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
@@ -1172,7 +1704,7 @@ app.get('/channels', async (_req, res) => {
1172
1704
  app.patch('/channels/:channelId', async (req, res) => {
1173
1705
  try {
1174
1706
  const { channelId } = req.params;
1175
- const { name, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
1707
+ const { name, walletAddress, autoInvokeTools, bound_judgment_ids, shared_with_peers } = req.body;
1176
1708
  const channels = await loadChannels();
1177
1709
  const channel = channels.find(c => c.id === channelId);
1178
1710
  if (!channel) {
@@ -1211,6 +1743,24 @@ app.get('/channels', async (_req, res) => {
1211
1743
  }
1212
1744
  console.log(`[Channel ${channelId}] 绑定判断力: ${channel.bound_judgment_ids.length} 条`);
1213
1745
  }
1746
+ // Phase 3: shared_with_peers (显式分享给指定 peerPublicKey 列表)
1747
+ if (shared_with_peers !== undefined) {
1748
+ if (shared_with_peers === null) {
1749
+ channel.shared_with_peers = [];
1750
+ } else if (Array.isArray(shared_with_peers)) {
1751
+ channel.shared_with_peers = shared_with_peers.filter(
1752
+ (x: unknown) => typeof x === 'string' && (x as string).length === 64 // iroh/hyperswarm pubkey 32 字节 = 64 hex
1753
+ );
1754
+ } else {
1755
+ return res.status(400).json({ error: 'shared_with_peers must be array of publicKey hex' });
1756
+ }
1757
+ console.log(`[Channel ${channelId}] 分享给 ${channel.shared_with_peers.length} 个 peer`);
1758
+ }
1759
+ // 首次保存时自动生成 share_id (短字符串, 方便粘贴)
1760
+ if (!channel.share_id) {
1761
+ channel.share_id = `shr_${channelId.slice(3, 12)}_${Math.random().toString(36).substring(2, 8)}`;
1762
+ console.log(`[Channel ${channelId}] 自动生成 share_id: ${channel.share_id}`);
1763
+ }
1214
1764
  channel.updatedAt = new Date().toISOString();
1215
1765
  await saveChannels(channels);
1216
1766
  res.json(channel);
@@ -1796,6 +2346,184 @@ app.get('/channels', async (_req, res) => {
1796
2346
  }
1797
2347
  });
1798
2348
 
2349
+ // v3 测试: 返回 iroh endpoint 完整地址 (含 relay URL), 这才是 connect() 真正需要的
2350
+ app.get('/api/iroh-addr', async (_req, res) => {
2351
+ try {
2352
+ const addr = irohTransport.getEndpointAddr
2353
+ ? irohTransport.getEndpointAddr()
2354
+ : irohTransport.getNodeId();
2355
+ res.json({ addr });
2356
+ } catch (err: any) {
2357
+ res.status(500).json({ error: err.message });
2358
+ }
2359
+ });
2360
+
2361
+ // v3: 暴露 P2PDirect 自己的 publicKey, 对方可用它主动 connect
2362
+ app.get('/api/p2p-publickey', async (_req, res) => {
2363
+ try {
2364
+ if (!v3P2PRef) {
2365
+ return res.status(503).json({ error: 'P2PDirect not started' });
2366
+ }
2367
+ res.json({ publicKey: v3P2PRef.getPublicKey() });
2368
+ } catch (err: any) {
2369
+ res.status(500).json({ error: err.message });
2370
+ }
2371
+ });
2372
+
2373
+ // v3: known peers CRUD (持久化到 ~/.bolloon/known_peers.json)
2374
+ // GET 列表, POST 加/更新, DELETE 删, PATCH 重命名
2375
+ app.get('/api/p2p-peers', async (_req, res) => {
2376
+ try {
2377
+ const { listPeers } = await import('../network/known-peers.js');
2378
+ const peers = await listPeers();
2379
+ res.json({ count: peers.length, peers });
2380
+ } catch (err: any) {
2381
+ res.status(500).json({ error: err.message });
2382
+ }
2383
+ });
2384
+ app.post('/api/p2p-peers', async (req, res) => {
2385
+ try {
2386
+ const { name, publicKey, notes } = req.body || {};
2387
+ if (!name || !publicKey) return res.status(400).json({ error: 'name and publicKey required' });
2388
+ if (typeof publicKey !== 'string' || publicKey.length !== 64) {
2389
+ return res.status(400).json({ error: 'publicKey must be 64-char hex (32 bytes)' });
2390
+ }
2391
+ const { addOrUpdatePeer } = await import('../network/known-peers.js');
2392
+ await addOrUpdatePeer(name, publicKey, notes);
2393
+ res.json({ ok: true });
2394
+ } catch (err: any) {
2395
+ res.status(500).json({ error: err.message });
2396
+ }
2397
+ });
2398
+ app.delete('/api/p2p-peers/:name', async (req, res) => {
2399
+ try {
2400
+ const { removePeer } = await import('../network/known-peers.js');
2401
+ await removePeer(req.params.name);
2402
+ res.json({ ok: true });
2403
+ } catch (err: any) {
2404
+ res.status(500).json({ error: err.message });
2405
+ }
2406
+ });
2407
+
2408
+ // v3: 主动 connect 到对端的 P2PDirect publicKey
2409
+ // 用法: POST /api/remote-channels/p2p-connect { targetPublicKey: "<hex>" }
2410
+ app.post('/api/remote-channels/p2p-connect', async (req, res) => {
2411
+ try {
2412
+ if (!v3P2PRef) {
2413
+ return res.status(503).json({ error: 'P2PDirect not started' });
2414
+ }
2415
+ const { targetPublicKey, name, persist } = req.body || {};
2416
+ if (!targetPublicKey || typeof targetPublicKey !== 'string') {
2417
+ return res.status(400).json({ error: 'targetPublicKey required (hex)' });
2418
+ }
2419
+ // v3P2PRef 直接连到目标 publicKey (用 hyperswarm 的 joinPeer API)
2420
+ const swarm = (v3P2PRef as any).swarm;
2421
+ if (!swarm) return res.status(503).json({ error: 'swarm not available' });
2422
+ const conn = await swarm.joinPeer(Buffer.from(targetPublicKey, 'hex'));
2423
+ console.log(`[v3] 已主动 joinPeer ${targetPublicKey.substring(0, 12)}...`);
2424
+
2425
+ // 自动持久化 (默认开启) — 之后启动自动重连
2426
+ let persistedAs: string | null = null;
2427
+ if (persist !== false) {
2428
+ const { addOrUpdatePeer, findNameByPublicKey } = await import('../network/known-peers.js');
2429
+ // 优先用客户端传的 name, 否则用 publicKey 前 8 位
2430
+ const peerName = name || `peer-${targetPublicKey.substring(0, 8)}`;
2431
+ // 如果 publicKey 已被别的 name 占用, 用现有 name
2432
+ const existingName = await findNameByPublicKey(targetPublicKey);
2433
+ persistedAs = existingName ?? peerName ?? `peer-${targetPublicKey.substring(0, 8)}`;
2434
+ await addOrUpdatePeer(persistedAs, targetPublicKey);
2435
+ console.log(`[v3] 自动持久化 peer: ${persistedAs}`);
2436
+ }
2437
+
2438
+ res.json({ ok: true, target: targetPublicKey, persistedAs });
2439
+ } catch (err: any) {
2440
+ console.error('[v3] p2p-connect 失败:', err);
2441
+ res.status(500).json({ error: err.message });
2442
+ }
2443
+ });
2444
+
2445
+ // v3: 给远端 channel 发消息 (B 节点) - 通过 P2PDirect 转发到 A, A 跑 LLM, 回 B
2446
+ // 用法: POST /api/remote-channels/chat-send
2447
+ // { targetPublicKey, channelId, text }
2448
+ app.post('/api/remote-channels/chat-send', async (req, res) => {
2449
+ try {
2450
+ if (!v3P2PRef) {
2451
+ return res.status(503).json({ error: 'P2PDirect not started' });
2452
+ }
2453
+ const { targetPublicKey, channelId, text } = req.body || {};
2454
+ if (!targetPublicKey || !channelId || !text) {
2455
+ return res.status(400).json({ error: 'targetPublicKey, channelId, text required' });
2456
+ }
2457
+ if (typeof text !== 'string' || text.length === 0 || text.length > 8000) {
2458
+ return res.status(400).json({ error: 'text length must be 1-8000' });
2459
+ }
2460
+ const fromPk = v3P2PRef.getPublicKey();
2461
+ const msg = JSON.stringify({
2462
+ v: 3,
2463
+ op: 'agent.chat.send',
2464
+ payload: { channelId, text, fromPublicKey: fromPk }
2465
+ });
2466
+ const ok = v3P2PRef.sendTo(targetPublicKey, msg);
2467
+ if (!ok) {
2468
+ return res.status(502).json({
2469
+ error: 'peer not connected. POST /api/remote-channels/p2p-connect first.'
2470
+ });
2471
+ }
2472
+ console.log(`[v3] chat-send 转发到 ${targetPublicKey.substring(0, 12)}... (channelId=${channelId})`);
2473
+ res.json({ ok: true, sent: true });
2474
+ } catch (err: any) {
2475
+ console.error('[v3] chat-send 失败:', err);
2476
+ res.status(500).json({ error: err.message });
2477
+ }
2478
+ });
2479
+
2480
+ // v3 新增: B 拉 A 的 channel 历史 + 用了哪些 judgment
2481
+ // GET /api/remote-channels/chat-history?targetPublicKey=...&channelId=...
2482
+ // 实现: B → POST 给 A 一个 agent.history.get RPC → A 把 session 返回 → B 渲染
2483
+ app.get('/api/remote-channels/chat-history', async (req, res) => {
2484
+ try {
2485
+ if (!v3P2PRef) {
2486
+ return res.status(503).json({ error: 'P2PDirect not started' });
2487
+ }
2488
+ const targetPublicKey = String(req.query.targetPublicKey || '');
2489
+ const channelId = String(req.query.channelId || '');
2490
+ if (!targetPublicKey || !channelId) {
2491
+ return res.status(400).json({ error: 'targetPublicKey, channelId required' });
2492
+ }
2493
+
2494
+ // 通过 RPC 拉 A 的 session — A 端收到后异步回复
2495
+ const fromPk = v3P2PRef.getPublicKey();
2496
+ const rpcId = `hist-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2497
+ const msg = JSON.stringify({
2498
+ v: 3,
2499
+ op: 'agent.history.get',
2500
+ payload: { rpcId, channelId, fromPublicKey: fromPk }
2501
+ });
2502
+ const ok = v3P2PRef.sendTo(targetPublicKey, msg);
2503
+ if (!ok) {
2504
+ return res.status(502).json({ error: 'peer not connected' });
2505
+ }
2506
+
2507
+ // 等待 A 异步回复 (15s timeout) — 用一个 Promise 等
2508
+ const result = await new Promise<any>((resolve, reject) => {
2509
+ const timer = setTimeout(() => {
2510
+ v3PendingHistoryGets.delete(rpcId);
2511
+ reject(new Error('A 端 15s 内未回复, 可能未分享该 channel'));
2512
+ }, 15000);
2513
+ v3PendingHistoryGets.set(rpcId, {
2514
+ resolve: (data) => { clearTimeout(timer); resolve(data); },
2515
+ reject: (err) => { clearTimeout(timer); reject(err); }
2516
+ });
2517
+ });
2518
+
2519
+ console.log(`[v3] chat-history 从 ${targetPublicKey.substring(0,12)}... 拉到 ${(result.messages || []).length} 条`);
2520
+ res.json(result);
2521
+ } catch (err: any) {
2522
+ console.error('[v3] chat-history 失败:', err.message);
2523
+ res.status(504).json({ error: err.message });
2524
+ }
2525
+ });
2526
+
1799
2527
  // 获取已连接的节点
1800
2528
  app.get('/api/peers', async (_req, res) => {
1801
2529
  try {
@@ -1969,7 +2697,8 @@ app.get('/channels', async (_req, res) => {
1969
2697
  console.log(`[v3] 收到 agent.meta.list from ${msg.from.substring(0, 12)}...`);
1970
2698
  try {
1971
2699
  const channels = await loadChannels();
1972
- const publicMeta = channels.map(sanitizeChannelForPeer);
2700
+ // iroh 路径保留 (admin / debug 用, 不走分享过滤)
2701
+ const publicMeta = channels.map((ch) => sanitizeChannelForPeer(ch));
1973
2702
  const response = JSON.stringify({ ok: true, channels: publicMeta });
1974
2703
  const encoded = new TextEncoder().encode(response);
1975
2704
  // 沿用 msg.from 路由回去