@bolloon/bolloon-agent 0.1.27 → 0.1.28

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,8 @@ 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;
388
394
  let channelSessions: Map<string, AgentSession> = new Map(); // key: channelId
389
395
  let sessionMessages: Map<string, any[]> = new Map(); // key: channelId + sessionId
390
396
 
@@ -400,8 +406,21 @@ let sessionMessages: Map<string, any[]> = new Map(); // key: channelId + session
400
406
  * v3: 过滤 channel 元数据, 只返回对远端 peer 安全的字段.
401
407
  * 关键: bound_judgment_ids / walletBinding / autoInvokeTools 内部状态不外传.
402
408
  * judgment 内容永远不会出现在 RPC 响应里 (judgment 始终在 A 节点内存, 由 A 跑 LLM).
409
+ *
410
+ * Phase 3 分享模式: 加 peerPublicKey 参数 — 只有 shared_with_peers 包含此 peer 的 channel 才返回.
411
+ * peerPublicKey 不传 = admin 路径, 返回所有 channel (老行为).
403
412
  */
404
- function sanitizeChannelForPeer(ch: Channel): Record<string, unknown> {
413
+ function sanitizeChannelForPeer(
414
+ ch: Channel,
415
+ peerPublicKey?: string
416
+ ): Record<string, unknown> | null {
417
+ // Phase 3 核心: 分享过滤
418
+ if (peerPublicKey) {
419
+ const shared = Array.isArray(ch.shared_with_peers) ? ch.shared_with_peers : [];
420
+ if (!shared.includes(peerPublicKey)) {
421
+ return null; // 没分享给这个 peer, 不返回
422
+ }
423
+ }
405
424
  return {
406
425
  id: ch.id,
407
426
  name: ch.name,
@@ -409,12 +428,153 @@ function sanitizeChannelForPeer(ch: Channel): Record<string, unknown> {
409
428
  publicKey: ch.publicKey,
410
429
  createdAt: ch.createdAt,
411
430
  updatedAt: ch.updatedAt,
412
- hasWallet: !!ch.walletAddress, // 只告诉 B "有没有钱包", 不传地址
431
+ hasWallet: !!ch.walletAddress,
413
432
  boundJudgmentCount: Array.isArray(ch.bound_judgment_ids) ? ch.bound_judgment_ids.length : 0,
414
- // 🔒 不返回: bound_judgment_ids, walletAddress, walletBinding, autoInvokeTools, sessions
433
+ share_id: ch.share_id,
434
+ // 🔒 不返回: bound_judgment_ids, walletAddress, walletBinding, autoInvokeTools, sessions, shared_with_peers
415
435
  };
416
436
  }
417
437
 
438
+ /**
439
+ * v3: 处理 Hyperswarm 通道收到的 v3 RPC 消息
440
+ * 设计: 用 HyperswarmCommunicator (DHT topic 自动发现) 取代 iroh 直接 connect
441
+ * - A 启动 → broadcast(agent.meta.list.reply) → 所有已连接 peer 缓存 A 的 channel
442
+ * - B 启动 → 同样 broadcast
443
+ * - 任何节点收到 list 请求 → 回 list.reply
444
+ */
445
+ async function handleV3P2PMessage(parsed: any, conn: P2PConnection, comm: HyperswarmCommunicator): Promise<void> {
446
+ const op = parsed.op;
447
+ const peerKey = conn.publicKey;
448
+
449
+ if (op === 'agent.meta.list') {
450
+ // 对方问我的 channel 列表 — 只返回分享给他的
451
+ try {
452
+ const channels = await loadChannels();
453
+ const publicMeta = channels
454
+ .map(ch => sanitizeChannelForPeer(ch, peerKey))
455
+ .filter((x): x is Record<string, unknown> => x !== null);
456
+ const reply = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: publicMeta } });
457
+ await comm.sendToConnection(conn.id, reply);
458
+ console.log(`[v3] 回 ${peerKey.substring(0,12)}... list.reply (${publicMeta.length} 个分享给 ta)`);
459
+ } catch (err) {
460
+ console.error('[v3] 处理 agent.meta.list 失败:', (err as Error).message);
461
+ }
462
+ return;
463
+ }
464
+
465
+ if (op === 'agent.meta.list.reply') {
466
+ // 对方把他自己的 channel 列表推给我 — 缓存
467
+ const list = parsed.payload?.channels || [];
468
+ remoteChannelCache.set(peerKey, list);
469
+ console.log(`[v3] 收到 ${peerKey.substring(0,12)}... 的 ${list.length} 个 channel, 已缓存`);
470
+ broadcast({
471
+ type: 'remote-channel-update',
472
+ peerId: peerKey,
473
+ channels: list
474
+ }, 'p2p-global');
475
+ return;
476
+ }
477
+
478
+ if (op === 'agent.meta.get') {
479
+ // 对方问单条 channel — 回
480
+ const channelId = parsed.payload?.channelId;
481
+ if (channelId) {
482
+ const channels = await loadChannels();
483
+ const ch = channels.find(c => c.id === channelId);
484
+ if (ch) {
485
+ // Phase 3: 分享过滤 — 必须分享给该 peer
486
+ const sanitized = sanitizeChannelForPeer(ch, peerKey);
487
+ if (sanitized) {
488
+ const reply = JSON.stringify({ v: 3, op: 'agent.meta.get.reply', payload: { channel: sanitized } });
489
+ await comm.sendToConnection(conn.id, reply);
490
+ } else {
491
+ const reply = JSON.stringify({ v: 3, op: 'agent.meta.get.reply', payload: { error: 'not shared with you' } });
492
+ await comm.sendToConnection(conn.id, reply);
493
+ }
494
+ }
495
+ }
496
+ return;
497
+ }
498
+
499
+ if (op === 'agent.meta.get.reply') {
500
+ const ch = parsed.payload?.channel;
501
+ if (ch && ch.id) {
502
+ const list = remoteChannelCache.get(peerKey) || [];
503
+ const idx = list.findIndex((c: any) => c.id === ch.id);
504
+ if (idx >= 0) list[idx] = ch;
505
+ else list.push(ch);
506
+ remoteChannelCache.set(peerKey, list);
507
+ broadcast({
508
+ type: 'remote-channel-update',
509
+ peerId: peerKey,
510
+ channels: list
511
+ }, 'p2p-global');
512
+ }
513
+ return;
514
+ }
515
+
516
+ if (op === 'agent.chat.send') {
517
+ // B 端发来: 在 A 节点上对 channelId 跑 LLM, 结果回 B
518
+ // judgment 永远在 A 节点 (buildJudgmentHint 已经用 bound_judgment_ids)
519
+ const { channelId, text, fromPublicKey } = parsed.payload || {};
520
+ if (!channelId || !text) {
521
+ console.warn(`[v3] agent.chat.send 缺少 channelId/text`);
522
+ return;
523
+ }
524
+ console.log(`[v3] 收到 ${fromPublicKey?.substring(0,12) || peerKey.substring(0,12)}... 对 channel ${channelId} 的 chat: "${text.substring(0, 40)}..."`);
525
+ try {
526
+ // 1. 找到 channel
527
+ const channels = await loadChannels();
528
+ const ch = channels.find(c => c.id === channelId);
529
+ if (!ch) {
530
+ const reply = JSON.stringify({
531
+ v: 3, op: 'agent.chat.reply',
532
+ payload: { channelId, fromPublicKey: v3P2PRef?.getPublicKey() || '', error: 'channel not found', text: '' }
533
+ });
534
+ await comm.sendToConnection(conn.id, reply);
535
+ return;
536
+ }
537
+ // 2. 跑 LLM (复用 Phase 1 的 buildJudgmentHint — 注入 channel 的 judgment)
538
+ const judgmentHint = await buildJudgmentHint(ch, channelId);
539
+ const { getMinimax } = await import('../constraints/index.js');
540
+ const llm = getMinimax();
541
+ const fullPrompt = `${judgmentHint}${text}`;
542
+ let fullResponse = '';
543
+ const streamCallback: any = (event: any) => {
544
+ // 流式 token, 不广播给 B (避免半成品噪音), 只记 A 自己的日志
545
+ if (event.type === 'token') {
546
+ fullResponse += event.content;
547
+ }
548
+ };
549
+ const agent = await getAgentForChannel(channelId, ch.did || '', ch.name, ch.didDocRef);
550
+ fullResponse = await agent.promptStream(fullPrompt, streamCallback);
551
+ // 3. 把完整回复发给 B
552
+ const reply = JSON.stringify({
553
+ v: 3, op: 'agent.chat.reply',
554
+ payload: {
555
+ channelId,
556
+ fromPublicKey: v3P2PRef?.getPublicKey() || '',
557
+ text: fullResponse
558
+ }
559
+ });
560
+ await comm.sendToConnection(conn.id, reply);
561
+ console.log(`[v3] 回 chat.reply 给 ${fromPublicKey?.substring(0,12) || peerKey.substring(0,12)}... (${fullResponse.length} chars)`);
562
+ } catch (err) {
563
+ console.error(`[v3] agent.chat.send 处理失败:`, (err as Error).message);
564
+ try {
565
+ const reply = JSON.stringify({
566
+ v: 3, op: 'agent.chat.reply',
567
+ payload: { channelId, fromPublicKey: v3P2PRef?.getPublicKey() || '', error: (err as Error).message, text: '' }
568
+ });
569
+ await comm.sendToConnection(conn.id, reply);
570
+ } catch {}
571
+ }
572
+ return;
573
+ }
574
+
575
+ console.log(`[v3] 收到未知 op: ${op}`);
576
+ }
577
+
418
578
  async function buildJudgmentHint(
419
579
  channel: Channel | undefined | null,
420
580
  channelIdForLog: string
@@ -602,7 +762,119 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
602
762
  console.log('P2P DID 本地模式运行');
603
763
  }
604
764
 
605
- // 初始化 P2P 通信器
765
+ // v3: 完全用 P2PDirect 取代 @diap/sdk 的 HyperswarmCommunicator
766
+ // 原因: @diap/sdk 的 sendToConnection 是 stub, 不真发数据
767
+ // 这里故意不启动 p2pCommunicator (保持 null), 让 P2PDirect 独占 hyperswarm 通道
768
+ try {
769
+ const { P2PDirect } = await import('../network/p2p-direct.js');
770
+ v3P2PRef = new P2PDirect({ name: 'v3' });
771
+ await v3P2PRef.start();
772
+ await v3P2PRef.joinTopic(Buffer.from('bolloon-agent-harness'));
773
+
774
+ v3P2PRef.on('data', (evt: any) => {
775
+ try {
776
+ const parsed = JSON.parse(evt.data.toString('utf-8'));
777
+ if (parsed && parsed.v === 3 && parsed.op) {
778
+ // v3 跨用户 chat: B 端收到 A 的 chat.reply, 直接 SSE 推给前端
779
+ if (parsed.op === 'agent.chat.reply') {
780
+ console.log(`[v3] 收到来自 ${evt.fromPublicKey.substring(0,12)}... 的 chat.reply (${(parsed.payload?.text || '').length} chars)`);
781
+ broadcast({
782
+ type: 'remote-chat-reply',
783
+ fromPublicKey: evt.fromPublicKey,
784
+ channelId: parsed.payload?.channelId,
785
+ text: parsed.payload?.text || '',
786
+ error: parsed.payload?.error
787
+ }, 'p2p-global');
788
+ return;
789
+ }
790
+ const commShim = {
791
+ sendToConnection: (_id: string, data: string) => {
792
+ v3P2PRef!.sendTo(evt.fromPublicKey, data);
793
+ return Promise.resolve();
794
+ }
795
+ };
796
+ handleV3P2PMessage(parsed, { id: evt.fromPublicKey, publicKey: evt.fromPublicKey } as any, commShim as any);
797
+ }
798
+ } catch (err) {
799
+ console.error('[v3-P2PDirect] 解析/处理消息失败:', (err as Error).message);
800
+ }
801
+ });
802
+
803
+ // 新连接进来 → 主动发我分享给 ta 的 channel 列表
804
+ v3P2PRef.on('connection', (evt: any) => {
805
+ setTimeout(async () => {
806
+ try {
807
+ const channels = await loadChannels();
808
+ const publicMeta = channels
809
+ .map(ch => sanitizeChannelForPeer(ch, evt.remotePublicKey))
810
+ .filter((x): x is Record<string, unknown> => x !== null);
811
+ const msg = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: publicMeta } });
812
+ v3P2PRef!.sendTo(evt.remotePublicKey, msg);
813
+ console.log(`[v3] 新连接 ${evt.remotePublicKey.substring(0,12)}... → 发 ${publicMeta.length} 个分享给 ta`);
814
+ } catch (err) {
815
+ console.error('[v3] 新连接发 list.reply 失败:', (err as Error).message);
816
+ }
817
+ }, 500);
818
+ });
819
+
820
+ console.log(`[v3] P2PDirect 已启动, role=${v3P2PRef.getRole()}, publicKey=${v3P2PRef.getPublicKey().substring(0,12)}...`);
821
+
822
+ // v3: 启动后自动重连 known peers — 让"启动就互联"成为现实
823
+ setTimeout(async () => {
824
+ try {
825
+ const { listPeers, markConnected } = await import('../network/known-peers.js');
826
+ const peers = await listPeers();
827
+ if (peers.length === 0) {
828
+ console.log(`[v3] 没有 known peers, 跳过自动重连`);
829
+ return;
830
+ }
831
+ const swarm = (v3P2PRef as any).swarm;
832
+ if (!swarm) return;
833
+ for (const peer of peers) {
834
+ try {
835
+ await swarm.joinPeer(Buffer.from(peer.publicKey, 'hex'));
836
+ await markConnected(peer.name || '');
837
+ console.log(`[v3] 自动重连 ${peer.name} (${peer.publicKey.substring(0, 12)}...) ✓`);
838
+ } catch (err) {
839
+ console.warn(`[v3] 自动重连 ${peer.name} 失败:`, (err as Error).message);
840
+ }
841
+ }
842
+ // 触发一次 broadcast 推送给所有重连的 peer
843
+ setTimeout(() => v3BroadcastOwn(), 2000);
844
+ } catch (err) {
845
+ console.error('[v3] 自动重连失败:', (err as Error).message);
846
+ }
847
+ }, 5000); // 5s 后再重连, 让 swarm 充分 bootstrap
848
+ } catch (err) {
849
+ console.error('[v3] P2PDirect 启动失败:', (err as Error).message);
850
+ v3P2PRef = null;
851
+ }
852
+
853
+ // v3: 定期 broadcast — 每个 peer 只收到分享给他的 channel (按 peer 个性化)
854
+ const v3BroadcastOwn = () => {
855
+ if (!v3P2PRef) return;
856
+ loadChannels().then(channels => {
857
+ const conns = (v3P2PRef as any).conns as Map<string, any>;
858
+ if (!conns) return;
859
+ for (const [peerPk, conn] of conns.entries()) {
860
+ if (conn?.destroyed) continue;
861
+ const sharedForPeer = channels
862
+ .map(ch => sanitizeChannelForPeer(ch, peerPk))
863
+ .filter((x): x is Record<string, unknown> => x !== null);
864
+ if (sharedForPeer.length > 0) {
865
+ const msg = JSON.stringify({ v: 3, op: 'agent.meta.list.reply', payload: { channels: sharedForPeer } });
866
+ try { conn.write(Buffer.from(msg)); } catch {}
867
+ }
868
+ }
869
+ console.log(`[v3] broadcast 个性化: ${conns.size} 个 peer, 各自收到分享的 channel`);
870
+ }).catch(err => console.error('[v3] broadcast 失败:', (err as Error).message));
871
+ };
872
+ setTimeout(v3BroadcastOwn, 3000);
873
+ setTimeout(v3BroadcastOwn, 10000);
874
+ setTimeout(v3BroadcastOwn, 20000);
875
+ setTimeout(v3BroadcastOwn, 40000);
876
+
877
+ // 保留 @diap/sdk 的旧实例 (它的 Hyperswarm 实例能帮 P2PDirect 做 DHT bootstrap)
606
878
  try {
607
879
  const rawSeed = crypto.getRandomValues(new Uint8Array(32));
608
880
  p2pCommunicator = createHyperswarmCommunicator({
@@ -612,24 +884,19 @@ export async function createWebServer(port: number = 3000, options: CreateWebSer
612
884
  maxConnections: 50,
613
885
  seed: rawSeed
614
886
  } as any);
615
-
616
- p2pCommunicator.on('connection', (conn: P2PConnection) => {
617
- console.log(`P2P 连接: ${conn.publicKey.substring(0, 8)}...`);
618
- });
619
-
620
887
  p2pCommunicator.on('message', async (msg: any, conn: P2PConnection) => {
888
+ // 旧 p2p_message 路径 (非 v3)
621
889
  const content = new TextDecoder().decode(msg.content);
622
- console.log(`P2P 收到消息: ${content.substring(0, 50)}...`);
623
- // 可以在这里处理接收到的消息
624
890
  broadcast({ type: 'p2p_message', from: conn.publicKey.substring(0, 8), content }, undefined);
625
891
  });
626
-
627
892
  await p2pCommunicator.start();
628
- const topic = createTopic('bolloon-agent-harness') as Buffer;
629
- await p2pCommunicator.joinTopic(topic);
630
- console.log(`P2P 网络已就绪`);
893
+ // @diap/sdk 也 join topic 它的 Hyperswarm 实例帮 P2PDirect 做 DHT 引导
894
+ // @diap/sdk 收到的数据是 mock (不真发), 但 DHT 发现 + 节点连接是 OK 的
895
+ const oldTopic = createTopic('bolloon-agent-harness') as Buffer;
896
+ await p2pCommunicator.joinTopic(oldTopic);
897
+ console.log(`P2P 老通道已就绪 (DHT bootstrap 帮 P2PDirect, 实际数据走 P2PDirect)`);
631
898
  } catch (e: any) {
632
- console.log(`P2P 网络初始化失败: ${e.message}`);
899
+ console.log(`P2P 老通道初始化失败: ${e.message}`);
633
900
  }
634
901
  } catch (e: any) {
635
902
  console.log(`P2P 身份初始化失败: ${e.message}`);
@@ -944,6 +1211,25 @@ app.get('/channels', async (_req, res) => {
944
1211
  // 用法: B 端用户点 "刷新远端智能体" → 触发本 endpoint
945
1212
  app.post('/api/remote-channels/refresh', async (_req, res) => {
946
1213
  try {
1214
+ // Phase 3: 优先用 P2PDirect conns (Phase 2/3 的真实通道)
1215
+ if (v3P2PRef) {
1216
+ const conns = (v3P2PRef as any).conns as Map<string, any>;
1217
+ const peerIds = Array.from(conns.keys()).filter(pk => {
1218
+ const c = conns.get(pk);
1219
+ return c && !c.destroyed;
1220
+ });
1221
+ if (peerIds.length === 0) {
1222
+ return res.json({ ok: true, sent: 0, note: 'no connected peers (P2PDirect)' });
1223
+ }
1224
+ // 让每个 peer 拉 list — Phase 3 个性化分享过滤
1225
+ let sent = 0;
1226
+ for (const peerPk of peerIds) {
1227
+ const ok = await (v3P2PRef as any).sendTo(peerPk, JSON.stringify({ v: 3, op: 'agent.meta.list', payload: {} }));
1228
+ if (ok) sent++;
1229
+ }
1230
+ return res.json({ ok: true, sent, total: peerIds.length });
1231
+ }
1232
+ // Fallback: 老 iroh 路径
947
1233
  const peers = irohTransport.getPeers ? irohTransport.getPeers() : [];
948
1234
  const peerIds = Array.isArray(peers) ? peers.map((p: any) => p.nodeId || p) : [];
949
1235
  if (peerIds.length === 0) {
@@ -964,6 +1250,40 @@ app.get('/channels', async (_req, res) => {
964
1250
  }
965
1251
  });
966
1252
 
1253
+ // ===== v3: 主动 connect 到对端, 再发 agent.meta.list =====
1254
+ // 用法: POST /api/remote-channels/connect { targetAddr: "<完整 EndpointAddr 含 relay URL>" }
1255
+ // targetAddr 应来自对端 GET /api/iroh-addr (完整字符串, 不只是 nodeId)
1256
+ // 兼容旧用法: 也接受 targetNodeId, 但只有 nodeId 不一定能 connect 成功
1257
+ app.post('/api/remote-channels/connect', async (req, res) => {
1258
+ try {
1259
+ const { targetAddr, targetNodeId } = req.body || {};
1260
+ const target = targetAddr || targetNodeId;
1261
+ if (!target || typeof target !== 'string') {
1262
+ return res.status(400).json({ error: 'targetAddr (or targetNodeId) required' });
1263
+ }
1264
+ console.log(`[v3] 主动 connect 到 ${target.substring(0, 32)}...`);
1265
+ // iroh connect 接受 nodeId 或完整 addr 字符串 — 用完整 addr 才会成功
1266
+ const ok = await irohTransport.connect(target);
1267
+ if (!ok) {
1268
+ return res.status(502).json({
1269
+ error: 'connect failed',
1270
+ hint: '传 targetAddr (完整 EndpointAddr 字符串, 含 relay URL) 而非仅 nodeId'
1271
+ });
1272
+ }
1273
+ // 立即发 agent.meta.list 请求对端返回元数据
1274
+ const sent = await irohTransport.sendMessage(
1275
+ target,
1276
+ 'agent.meta.list',
1277
+ new TextEncoder().encode('{}')
1278
+ );
1279
+ console.log(`[v3] connect+list 发送结果: connect=ok, list=${sent}`);
1280
+ res.json({ ok: true, connected: true, sent, target });
1281
+ } catch (err: any) {
1282
+ console.error('[v3] /api/remote-channels/connect 失败:', err);
1283
+ res.status(500).json({ error: err.message });
1284
+ }
1285
+ });
1286
+
967
1287
  app.post('/channels', async (req, res) => {
968
1288
  try {
969
1289
  const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
@@ -1172,7 +1492,7 @@ app.get('/channels', async (_req, res) => {
1172
1492
  app.patch('/channels/:channelId', async (req, res) => {
1173
1493
  try {
1174
1494
  const { channelId } = req.params;
1175
- const { name, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
1495
+ const { name, walletAddress, autoInvokeTools, bound_judgment_ids, shared_with_peers } = req.body;
1176
1496
  const channels = await loadChannels();
1177
1497
  const channel = channels.find(c => c.id === channelId);
1178
1498
  if (!channel) {
@@ -1211,6 +1531,24 @@ app.get('/channels', async (_req, res) => {
1211
1531
  }
1212
1532
  console.log(`[Channel ${channelId}] 绑定判断力: ${channel.bound_judgment_ids.length} 条`);
1213
1533
  }
1534
+ // Phase 3: shared_with_peers (显式分享给指定 peerPublicKey 列表)
1535
+ if (shared_with_peers !== undefined) {
1536
+ if (shared_with_peers === null) {
1537
+ channel.shared_with_peers = [];
1538
+ } else if (Array.isArray(shared_with_peers)) {
1539
+ channel.shared_with_peers = shared_with_peers.filter(
1540
+ (x: unknown) => typeof x === 'string' && (x as string).length === 64 // iroh/hyperswarm pubkey 32 字节 = 64 hex
1541
+ );
1542
+ } else {
1543
+ return res.status(400).json({ error: 'shared_with_peers must be array of publicKey hex' });
1544
+ }
1545
+ console.log(`[Channel ${channelId}] 分享给 ${channel.shared_with_peers.length} 个 peer`);
1546
+ }
1547
+ // 首次保存时自动生成 share_id (短字符串, 方便粘贴)
1548
+ if (!channel.share_id) {
1549
+ channel.share_id = `shr_${channelId.slice(3, 12)}_${Math.random().toString(36).substring(2, 8)}`;
1550
+ console.log(`[Channel ${channelId}] 自动生成 share_id: ${channel.share_id}`);
1551
+ }
1214
1552
  channel.updatedAt = new Date().toISOString();
1215
1553
  await saveChannels(channels);
1216
1554
  res.json(channel);
@@ -1796,6 +2134,137 @@ app.get('/channels', async (_req, res) => {
1796
2134
  }
1797
2135
  });
1798
2136
 
2137
+ // v3 测试: 返回 iroh endpoint 完整地址 (含 relay URL), 这才是 connect() 真正需要的
2138
+ app.get('/api/iroh-addr', async (_req, res) => {
2139
+ try {
2140
+ const addr = irohTransport.getEndpointAddr
2141
+ ? irohTransport.getEndpointAddr()
2142
+ : irohTransport.getNodeId();
2143
+ res.json({ addr });
2144
+ } catch (err: any) {
2145
+ res.status(500).json({ error: err.message });
2146
+ }
2147
+ });
2148
+
2149
+ // v3: 暴露 P2PDirect 自己的 publicKey, 对方可用它主动 connect
2150
+ app.get('/api/p2p-publickey', async (_req, res) => {
2151
+ try {
2152
+ if (!v3P2PRef) {
2153
+ return res.status(503).json({ error: 'P2PDirect not started' });
2154
+ }
2155
+ res.json({ publicKey: v3P2PRef.getPublicKey() });
2156
+ } catch (err: any) {
2157
+ res.status(500).json({ error: err.message });
2158
+ }
2159
+ });
2160
+
2161
+ // v3: known peers CRUD (持久化到 ~/.bolloon/known_peers.json)
2162
+ // GET 列表, POST 加/更新, DELETE 删, PATCH 重命名
2163
+ app.get('/api/p2p-peers', async (_req, res) => {
2164
+ try {
2165
+ const { listPeers } = await import('../network/known-peers.js');
2166
+ const peers = await listPeers();
2167
+ res.json({ count: peers.length, peers });
2168
+ } catch (err: any) {
2169
+ res.status(500).json({ error: err.message });
2170
+ }
2171
+ });
2172
+ app.post('/api/p2p-peers', async (req, res) => {
2173
+ try {
2174
+ const { name, publicKey, notes } = req.body || {};
2175
+ if (!name || !publicKey) return res.status(400).json({ error: 'name and publicKey required' });
2176
+ if (typeof publicKey !== 'string' || publicKey.length !== 64) {
2177
+ return res.status(400).json({ error: 'publicKey must be 64-char hex (32 bytes)' });
2178
+ }
2179
+ const { addOrUpdatePeer } = await import('../network/known-peers.js');
2180
+ await addOrUpdatePeer(name, publicKey, notes);
2181
+ res.json({ ok: true });
2182
+ } catch (err: any) {
2183
+ res.status(500).json({ error: err.message });
2184
+ }
2185
+ });
2186
+ app.delete('/api/p2p-peers/:name', async (req, res) => {
2187
+ try {
2188
+ const { removePeer } = await import('../network/known-peers.js');
2189
+ await removePeer(req.params.name);
2190
+ res.json({ ok: true });
2191
+ } catch (err: any) {
2192
+ res.status(500).json({ error: err.message });
2193
+ }
2194
+ });
2195
+
2196
+ // v3: 主动 connect 到对端的 P2PDirect publicKey
2197
+ // 用法: POST /api/remote-channels/p2p-connect { targetPublicKey: "<hex>" }
2198
+ app.post('/api/remote-channels/p2p-connect', async (req, res) => {
2199
+ try {
2200
+ if (!v3P2PRef) {
2201
+ return res.status(503).json({ error: 'P2PDirect not started' });
2202
+ }
2203
+ const { targetPublicKey, name, persist } = req.body || {};
2204
+ if (!targetPublicKey || typeof targetPublicKey !== 'string') {
2205
+ return res.status(400).json({ error: 'targetPublicKey required (hex)' });
2206
+ }
2207
+ // v3P2PRef 直接连到目标 publicKey (用 hyperswarm 的 joinPeer API)
2208
+ const swarm = (v3P2PRef as any).swarm;
2209
+ if (!swarm) return res.status(503).json({ error: 'swarm not available' });
2210
+ const conn = await swarm.joinPeer(Buffer.from(targetPublicKey, 'hex'));
2211
+ console.log(`[v3] 已主动 joinPeer ${targetPublicKey.substring(0, 12)}...`);
2212
+
2213
+ // 自动持久化 (默认开启) — 之后启动自动重连
2214
+ let persistedAs: string | null = null;
2215
+ if (persist !== false) {
2216
+ const { addOrUpdatePeer, findNameByPublicKey } = await import('../network/known-peers.js');
2217
+ // 优先用客户端传的 name, 否则用 publicKey 前 8 位
2218
+ const peerName = name || `peer-${targetPublicKey.substring(0, 8)}`;
2219
+ // 如果 publicKey 已被别的 name 占用, 用现有 name
2220
+ const existingName = await findNameByPublicKey(targetPublicKey);
2221
+ persistedAs = existingName ?? peerName ?? `peer-${targetPublicKey.substring(0, 8)}`;
2222
+ await addOrUpdatePeer(persistedAs, targetPublicKey);
2223
+ console.log(`[v3] 自动持久化 peer: ${persistedAs}`);
2224
+ }
2225
+
2226
+ res.json({ ok: true, target: targetPublicKey, persistedAs });
2227
+ } catch (err: any) {
2228
+ console.error('[v3] p2p-connect 失败:', err);
2229
+ res.status(500).json({ error: err.message });
2230
+ }
2231
+ });
2232
+
2233
+ // v3: 给远端 channel 发消息 (B 节点) - 通过 P2PDirect 转发到 A, A 跑 LLM, 回 B
2234
+ // 用法: POST /api/remote-channels/chat-send
2235
+ // { targetPublicKey, channelId, text }
2236
+ app.post('/api/remote-channels/chat-send', async (req, res) => {
2237
+ try {
2238
+ if (!v3P2PRef) {
2239
+ return res.status(503).json({ error: 'P2PDirect not started' });
2240
+ }
2241
+ const { targetPublicKey, channelId, text } = req.body || {};
2242
+ if (!targetPublicKey || !channelId || !text) {
2243
+ return res.status(400).json({ error: 'targetPublicKey, channelId, text required' });
2244
+ }
2245
+ if (typeof text !== 'string' || text.length === 0 || text.length > 8000) {
2246
+ return res.status(400).json({ error: 'text length must be 1-8000' });
2247
+ }
2248
+ const fromPk = v3P2PRef.getPublicKey();
2249
+ const msg = JSON.stringify({
2250
+ v: 3,
2251
+ op: 'agent.chat.send',
2252
+ payload: { channelId, text, fromPublicKey: fromPk }
2253
+ });
2254
+ const ok = v3P2PRef.sendTo(targetPublicKey, msg);
2255
+ if (!ok) {
2256
+ return res.status(502).json({
2257
+ error: 'peer not connected. POST /api/remote-channels/p2p-connect first.'
2258
+ });
2259
+ }
2260
+ console.log(`[v3] chat-send 转发到 ${targetPublicKey.substring(0, 12)}... (channelId=${channelId})`);
2261
+ res.json({ ok: true, sent: true });
2262
+ } catch (err: any) {
2263
+ console.error('[v3] chat-send 失败:', err);
2264
+ res.status(500).json({ error: err.message });
2265
+ }
2266
+ });
2267
+
1799
2268
  // 获取已连接的节点
1800
2269
  app.get('/api/peers', async (_req, res) => {
1801
2270
  try {
@@ -1969,7 +2438,8 @@ app.get('/channels', async (_req, res) => {
1969
2438
  console.log(`[v3] 收到 agent.meta.list from ${msg.from.substring(0, 12)}...`);
1970
2439
  try {
1971
2440
  const channels = await loadChannels();
1972
- const publicMeta = channels.map(sanitizeChannelForPeer);
2441
+ // iroh 路径保留 (admin / debug 用, 不走分享过滤)
2442
+ const publicMeta = channels.map((ch) => sanitizeChannelForPeer(ch));
1973
2443
  const response = JSON.stringify({ ok: true, channels: publicMeta });
1974
2444
  const encoded = new TextEncoder().encode(response);
1975
2445
  // 沿用 msg.from 路由回去