@bolloon/bolloon-agent 0.1.23 → 0.1.25

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.
@@ -11,6 +11,8 @@ import { initMinimax, getMinimax } from '../constraints/index.js';
11
11
  import { createAgentSession } from '../agents/pi-sdk.js';
12
12
  import { llmConfigStore } from '../llm/config-store.js';
13
13
  import { irohTransport } from '../network/iroh-transport.js';
14
+ import { createAgentDelegateApp } from './agent-delegate-server.js';
15
+ import { createIrohDelegateTransport } from './iroh-delegate-transport.js';
14
16
  import { verifyMessage, isAddress, getAddress } from 'viem';
15
17
  // 前端资源路径:在打包后会通过 CommonJS require 加载,使用 import.meta.url
16
18
  const __filename = fileURLToPath(import.meta.url);
@@ -254,6 +256,54 @@ async function executeTask(task, channelId) {
254
256
  let sseClients = new Set();
255
257
  let channelSessions = new Map(); // key: channelId
256
258
  let sessionMessages = new Map(); // key: channelId + sessionId
259
+ /**
260
+ * v3 重做: 构造 channel 的两路 judgment prompt 片段
261
+ * 路 1: 用户在盾牌里手动绑定的 judgment (channel.bound_judgment_ids)
262
+ * 路 2: 全局 judgment 列表 (供 LLM 在主调用中按需挑选, 写入回复)
263
+ * 返回 "" 表示完全没数据; 否则返回完整 "[系统上下文] ..." 块 (含尾部换行)
264
+ * 失败非致命 — 任何异常都返回空串, 保证 LLM 调用不被阻塞
265
+ */
266
+ async function buildJudgmentHint(channel, channelIdForLog) {
267
+ try {
268
+ const { loadAllJudgments, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
269
+ await initializeValueStore();
270
+ const allJudgments = await loadAllJudgments();
271
+ if (allJudgments.length === 0)
272
+ return '';
273
+ const boundIds = new Set(channel && Array.isArray(channel.bound_judgment_ids) ? channel.bound_judgment_ids : []);
274
+ const bound = allJudgments.filter(j => j.id !== undefined && boundIds.has(j.id));
275
+ const others = allJudgments.filter(j => j.id !== undefined && !boundIds.has(j.id));
276
+ let hint = '';
277
+ // 路 1: 用户手动绑定的 judgment — 硬约束, 必须遵循
278
+ if (bound.length > 0) {
279
+ hint += `[系统上下文] 此 channel 用户绑定了 ${bound.length} 条判断力, 必须严格遵循:\n`;
280
+ for (const j of bound) {
281
+ const decision = (j.decision || '').toString().slice(0, 200);
282
+ const reasonList = Array.isArray(j.reasons) ? j.reasons : [];
283
+ const reasonText = reasonList.length > 0
284
+ ? ` (理由: ${reasonList.join('; ').slice(0, 100)})`
285
+ : '';
286
+ hint += `- ${decision}${reasonText}\n`;
287
+ }
288
+ hint += '\n';
289
+ }
290
+ // 路 2: 全局 judgment 候选池 — 软参考, LLM 自己挑
291
+ if (others.length > 0) {
292
+ hint += `[系统上下文] 候选判断力 (用户未明确绑定, 你可以按相关性自主选择参考):\n`;
293
+ for (const j of others) {
294
+ const decision = (j.decision || '').toString().slice(0, 120);
295
+ hint += `- [id=${j.id}] ${decision}\n`;
296
+ }
297
+ hint += `\n[系统上下文] 如果你的回复参考了某条候选判断力, 请在回复中自然提及 "我参考了你的判断: <decision 简述>" 即可, 无需复述 id.\n\n`;
298
+ }
299
+ console.log(`[v3] channel ${channelIdForLog} 注入: 绑定 ${bound.length} 条, 候选 ${others.length} 条`);
300
+ return hint;
301
+ }
302
+ catch (err) {
303
+ console.error(`[v3] 加载判断力失败 (非致命):`, err.message);
304
+ return '';
305
+ }
306
+ }
257
307
  async function getAgentForChannel(channelId, channelDid, channelName, channelDidDoc) {
258
308
  // 获取当前 channel 的 currentSessionId
259
309
  const channels = await loadChannels();
@@ -310,7 +360,9 @@ async function getAgentForChannel(channelId, channelDid, channelName, channelDid
310
360
  }
311
361
  return session;
312
362
  }
313
- export async function createWebServer(port = 3000) {
363
+ let selfImproveEnabled = false;
364
+ export async function createWebServer(port = 3000, options = {}) {
365
+ selfImproveEnabled = options.selfImprove ?? false;
314
366
  // 防止 P2P DHT 超时等错误导致进程崩溃
315
367
  process.on('unhandledRejection', (reason, promise) => {
316
368
  console.error('[警告] 未处理的 Promise 拒绝:', reason);
@@ -464,6 +516,8 @@ export async function createWebServer(port = 3000) {
464
516
  // (line ~638) 与这里外层的 const channel 形成 shadowing 让 TS 误报"使用前未声明"
465
517
  const boundWalletAddress = channel?.walletAddress;
466
518
  const autoToolsEnabled = channel?.autoInvokeTools !== false; // 默认开启
519
+ // 捕获外层 channel 到独立变量, 避免被 try 块内 (line 740+) 的 const channel 遮蔽
520
+ const channelForJudgment = channel;
467
521
  try {
468
522
  const agent = await getAgentForChannel(channelId, realChannelDid, realChannelName, realChannelDidDoc);
469
523
  let fullResponse = '';
@@ -499,6 +553,11 @@ export async function createWebServer(port = 3000) {
499
553
  else {
500
554
  contextHint += `[系统上下文] 自动工具调用已关闭: 每次执行工具前必须先与用户确认。\n`;
501
555
  }
556
+ // v3: 注入 channel 绑定的判断力 (judgment_ids)
557
+ // 这是 v3 的核心 — channel 跑 LLM 时, 它的判断力 = 绑定的 judgment 列表
558
+ const judgmentHint = await buildJudgmentHint(channelForJudgment, channelId);
559
+ if (judgmentHint)
560
+ contextHint += judgmentHint;
502
561
  if (contextHint)
503
562
  contextHint += '\n';
504
563
  fullResponse = await agent.promptStream(contextHint + text, streamCallback);
@@ -657,8 +716,8 @@ export async function createWebServer(port = 3000) {
657
716
  });
658
717
  app.post('/channels', async (req, res) => {
659
718
  try {
660
- const { name, agentId, walletAddress, autoInvokeTools } = req.body;
661
- console.log(`[创建频道] 收到请求: name=${name}, agentId=${agentId}, wallet=${walletAddress ? 'yes' : 'no'}`);
719
+ const { name, agentId, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
720
+ console.log(`[创建频道] 收到请求: name=${name}, agentId=${agentId}, wallet=${walletAddress ? 'yes' : 'no'}, boundJudgments=${Array.isArray(bound_judgment_ids) ? bound_judgment_ids.length : 0}`);
662
721
  if (!name || !agentId) {
663
722
  return res.status(400).json({ error: 'name and agentId required' });
664
723
  }
@@ -666,6 +725,10 @@ export async function createWebServer(port = 3000) {
666
725
  const id = `ch_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
667
726
  // 校验钱包地址格式 (粗校验: 0x + 40 hex / Solana base58 / Sui 0x+64)
668
727
  const validWallet = isValidWalletAddress(walletAddress);
728
+ // 过滤 bound_judgment_ids: 只保留 string
729
+ const safeBoundIds = Array.isArray(bound_judgment_ids)
730
+ ? bound_judgment_ids.filter((x) => typeof x === 'string' && x.length > 0)
731
+ : [];
669
732
  // 先创建频道(不阻塞等待 DID 生成)
670
733
  const channel = {
671
734
  id,
@@ -677,6 +740,7 @@ export async function createWebServer(port = 3000) {
677
740
  walletAddress: validWallet || undefined,
678
741
  walletRegisteredAt: validWallet ? new Date().toISOString() : undefined,
679
742
  autoInvokeTools: autoInvokeTools !== false, // 默认 true
743
+ bound_judgment_ids: safeBoundIds,
680
744
  sessions: [{
681
745
  id: `sess_${Date.now()}`,
682
746
  createdAt: new Date().toISOString(),
@@ -835,7 +899,7 @@ export async function createWebServer(port = 3000) {
835
899
  app.patch('/channels/:channelId', async (req, res) => {
836
900
  try {
837
901
  const { channelId } = req.params;
838
- const { name, walletAddress, autoInvokeTools } = req.body;
902
+ const { name, walletAddress, autoInvokeTools, bound_judgment_ids } = req.body;
839
903
  const channels = await loadChannels();
840
904
  const channel = channels.find(c => c.id === channelId);
841
905
  if (!channel) {
@@ -862,6 +926,19 @@ export async function createWebServer(port = 3000) {
862
926
  if (typeof autoInvokeTools === 'boolean') {
863
927
  channel.autoInvokeTools = autoInvokeTools;
864
928
  }
929
+ // bound_judgment_ids: 允许数组(替换)/null(清空)/undefined(不改)
930
+ if (bound_judgment_ids !== undefined) {
931
+ if (bound_judgment_ids === null) {
932
+ channel.bound_judgment_ids = [];
933
+ }
934
+ else if (Array.isArray(bound_judgment_ids)) {
935
+ channel.bound_judgment_ids = bound_judgment_ids.filter((x) => typeof x === 'string' && x.length > 0);
936
+ }
937
+ else {
938
+ return res.status(400).json({ error: 'bound_judgment_ids must be array or null' });
939
+ }
940
+ console.log(`[Channel ${channelId}] 绑定判断力: ${channel.bound_judgment_ids.length} 条`);
941
+ }
865
942
  channel.updatedAt = new Date().toISOString();
866
943
  await saveChannels(channels);
867
944
  res.json(channel);
@@ -1023,8 +1100,9 @@ export async function createWebServer(port = 3000) {
1023
1100
  broadcast({ type: 'error', content: event.content }, channelId);
1024
1101
  }
1025
1102
  };
1026
- // 重新生成时只发送用户消息
1027
- fullResponse = await agent.promptStream(userMessage, streamCallback);
1103
+ // 重新生成时只发送用户消息 (v3: 同时注入 channel 绑定的判断力)
1104
+ const regenHint = await buildJudgmentHint(channel, channelId);
1105
+ fullResponse = await agent.promptStream(regenHint + userMessage, streamCallback);
1028
1106
  broadcast({ type: 'ai', content: fullResponse }, channelId);
1029
1107
  // 更新 session
1030
1108
  const existingSession = await loadSession(channelId, currentSessionId);
@@ -1489,6 +1567,17 @@ export async function createWebServer(port = 3000) {
1489
1567
  initialized: true
1490
1568
  };
1491
1569
  irohInitialized = true;
1570
+ // 挂载 agent-delegate app (manifest 协议 + agent_delegate)
1571
+ // 必须在 irohInitialized 之后挂, 因为适配器要监听 irohTransport.onMessage
1572
+ try {
1573
+ const delegateTransport = createIrohDelegateTransport({ verbose: true });
1574
+ const delegateApp = createAgentDelegateApp(delegateTransport);
1575
+ app.use('/api/agent', delegateApp);
1576
+ console.log('[iroh API] agent-delegate app 已挂载到 /api/agent');
1577
+ }
1578
+ catch (e) {
1579
+ console.error('[iroh API] 挂载 agent-delegate app 失败:', e);
1580
+ }
1492
1581
  // 设置消息处理
1493
1582
  irohTransport.onMessage('chat', (msg) => {
1494
1583
  const content = new TextDecoder().decode(msg.payload);
@@ -2125,7 +2214,8 @@ export async function createWebServer(port = 3000) {
2125
2214
  try {
2126
2215
  const { createHealthMonitor, createWatchdog } = await import('../heartbeat/index.js');
2127
2216
  healthMonitor = createHealthMonitor();
2128
- watchdog = createWatchdog();
2217
+ // 把 watchdog 静默阈值拉到 30 分钟, 避免开发期 / 用户空闲时被误杀
2218
+ watchdog = createWatchdog({ silentThresholdMs: 30 * 60 * 1000 });
2129
2219
  console.log('[24h] Heartbeat modules loaded');
2130
2220
  }
2131
2221
  catch (err) {
@@ -2177,6 +2267,294 @@ export async function createWebServer(port = 3000) {
2177
2267
  res.status(500).json({ error: err.message });
2178
2268
  }
2179
2269
  });
2270
+ // ==================== Judgments (v1 核心: 让我能记录判断) ====================
2271
+ // POST /api/judgments — 记录一个判断
2272
+ // GET /api/judgments — 列出所有判断 (新→旧)
2273
+ // 存储: ~/.bolloon/human-values/judgments.json (human-value-store)
2274
+ // 极简版: 只记录 decision + reason; 其它字段可选
2275
+ app.post('/api/judgments', async (req, res) => {
2276
+ try {
2277
+ const { decision, reason, context } = req.body;
2278
+ if (!decision || typeof decision !== 'string' || !decision.trim()) {
2279
+ return res.status(400).json({ error: 'decision required' });
2280
+ }
2281
+ const { storeHumanJudgment, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
2282
+ await initializeValueStore();
2283
+ const j = await storeHumanJudgment({
2284
+ decision: decision.trim(),
2285
+ decision_type: 'approve',
2286
+ reasons: reason ? [reason.trim()] : [],
2287
+ values_derived: [],
2288
+ context: {
2289
+ domain: context?.domain || 'general',
2290
+ complexity: 'moderate',
2291
+ stakes: context?.stakes || 'medium',
2292
+ time_pressure: 'low',
2293
+ },
2294
+ metadata: {
2295
+ source: 'explicit',
2296
+ confidence: 0.8,
2297
+ revisable: true,
2298
+ },
2299
+ });
2300
+ res.json({ ok: true, judgment: j });
2301
+ }
2302
+ catch (err) {
2303
+ console.error('[judgments] POST failed:', err);
2304
+ res.status(500).json({ error: err.message });
2305
+ }
2306
+ });
2307
+ app.get('/api/judgments', async (_req, res) => {
2308
+ try {
2309
+ const { loadAllJudgments, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
2310
+ await initializeValueStore();
2311
+ const all = await loadAllJudgments();
2312
+ // 新的在前
2313
+ all.sort((a, b) => (b.timestamp || '').localeCompare(a.timestamp || ''));
2314
+ res.json({ count: all.length, judgments: all });
2315
+ }
2316
+ catch (err) {
2317
+ console.error('[judgments] GET failed:', err);
2318
+ res.status(500).json({ error: err.message });
2319
+ }
2320
+ });
2321
+ // 导入判断: 接受 { filename, content (base64), context }.
2322
+ // 支持 .json / .yaml / .yml / .md / .txt / .html. 完全离线解析, 不调 LLM.
2323
+ // 解析规则:
2324
+ // - .json: 顶层数组 [{decision, reason?, context?}, ...] 或 {judgments: [...]} 或 {items: [...]}
2325
+ // - .yaml/.yml: 期望顶层数组 (用 js-yaml); 不支持复杂结构
2326
+ // - .md/.txt/.html: 每一段 (按空行分隔) 算一条判断, 首行非空 = decision, 整段 = content
2327
+ // 如果首行是 markdown 标题 (# ...) 则去掉 #, 整段去掉首行后作 reason
2328
+ app.post('/api/judgments/import', async (req, res) => {
2329
+ try {
2330
+ const { filename, content, context } = req.body;
2331
+ if (!filename || !content) {
2332
+ return res.status(400).json({ error: 'filename and content (base64) required' });
2333
+ }
2334
+ let raw;
2335
+ try {
2336
+ raw = Buffer.from(content, 'base64').toString('utf-8');
2337
+ }
2338
+ catch {
2339
+ return res.status(400).json({ error: 'content is not valid base64' });
2340
+ }
2341
+ const lower = filename.toLowerCase();
2342
+ let items = [];
2343
+ if (lower.endsWith('.json')) {
2344
+ try {
2345
+ const parsed = JSON.parse(raw);
2346
+ const arr = Array.isArray(parsed) ? parsed
2347
+ : Array.isArray(parsed?.judgments) ? parsed.judgments
2348
+ : Array.isArray(parsed?.items) ? parsed.items
2349
+ : null;
2350
+ if (!arr)
2351
+ return res.status(400).json({ error: 'JSON must be an array, or {judgments:[]}/{items:[]}' });
2352
+ for (const it of arr) {
2353
+ if (it && typeof it.decision === 'string' && it.decision.trim()) {
2354
+ items.push({ decision: it.decision.trim(), reason: it.reason, context: it.context });
2355
+ }
2356
+ }
2357
+ }
2358
+ catch (e) {
2359
+ return res.status(400).json({ error: 'JSON parse failed: ' + e.message });
2360
+ }
2361
+ }
2362
+ else if (lower.endsWith('.yaml') || lower.endsWith('.yml')) {
2363
+ try {
2364
+ const yaml = (await import('js-yaml')).default;
2365
+ const parsed = yaml.load(raw);
2366
+ if (!Array.isArray(parsed))
2367
+ return res.status(400).json({ error: 'YAML must be a top-level array' });
2368
+ for (const it of parsed) {
2369
+ if (it && typeof it.decision === 'string' && it.decision.trim()) {
2370
+ items.push({ decision: it.decision.trim(), reason: it.reason, context: it.context });
2371
+ }
2372
+ }
2373
+ }
2374
+ catch (e) {
2375
+ return res.status(400).json({ error: 'YAML parse failed: ' + e.message });
2376
+ }
2377
+ }
2378
+ else if (lower.endsWith('.md') || lower.endsWith('.txt') || lower.endsWith('.html') || lower.endsWith('.htm')) {
2379
+ // 通用纯文本: 按空行分段, 每段是一条判断
2380
+ // 对 .html 先剥掉标签, 但保留段落分隔
2381
+ let text = raw;
2382
+ if (lower.endsWith('.html') || lower.endsWith('.htm')) {
2383
+ text = text.replace(/<script[\s\S]*?<\/script>/gi, '')
2384
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
2385
+ // 块级标签 -> 双换行 (保留段落分隔)
2386
+ .replace(/<\/?(p|div|h[1-6]|li|tr|br)[^>]*>/gi, '\n\n')
2387
+ .replace(/<[^>]+>/g, ' ')
2388
+ .replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
2389
+ }
2390
+ const blocks = text.split(/\n\s*\n/).map(b => b.trim()).filter(b => b.length > 0);
2391
+ for (const block of blocks) {
2392
+ const lines = block.split('\n').map(l => l.trim()).filter(l => l.length > 0);
2393
+ if (lines.length === 0)
2394
+ continue;
2395
+ let decision = lines[0];
2396
+ // 如果首行是 markdown 标题, 去掉 # 前缀
2397
+ decision = decision.replace(/^#+\s*/, '');
2398
+ // 如果整段就是一个短句 (没有换行), 直接当 decision
2399
+ const reason = lines.length > 1 ? lines.slice(1).join(' ').trim() || undefined : undefined;
2400
+ if (decision)
2401
+ items.push({ decision, reason });
2402
+ }
2403
+ }
2404
+ else {
2405
+ return res.status(400).json({ error: 'unsupported file type (use .json .yaml .yml .md .txt .html)' });
2406
+ }
2407
+ if (items.length === 0) {
2408
+ return res.status(400).json({ error: 'no parseable judgments found in file' });
2409
+ }
2410
+ const { storeHumanJudgment, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
2411
+ await initializeValueStore();
2412
+ const imported = [];
2413
+ const errors = [];
2414
+ for (let i = 0; i < items.length; i++) {
2415
+ try {
2416
+ const it = items[i];
2417
+ const j = await storeHumanJudgment({
2418
+ decision: it.decision,
2419
+ decision_type: 'approve',
2420
+ reasons: it.reason ? [String(it.reason)] : [],
2421
+ values_derived: [],
2422
+ context: {
2423
+ domain: it.context?.domain || context?.domain || 'general',
2424
+ complexity: 'moderate',
2425
+ stakes: it.context?.stakes || context?.stakes || 'medium',
2426
+ time_pressure: 'low',
2427
+ },
2428
+ metadata: {
2429
+ source: 'explicit',
2430
+ confidence: 0.8,
2431
+ revisable: true,
2432
+ },
2433
+ });
2434
+ imported.push(j);
2435
+ }
2436
+ catch (e) {
2437
+ errors.push(`#${i + 1} (${items[i].decision.substring(0, 30)}): ${e.message}`);
2438
+ }
2439
+ }
2440
+ res.json({ ok: true, imported: imported.length, failed: errors.length, errors: errors.slice(0, 5), judgments: imported });
2441
+ }
2442
+ catch (err) {
2443
+ console.error('[judgments] import failed:', err);
2444
+ res.status(500).json({ error: err.message });
2445
+ }
2446
+ });
2447
+ // 修改判断 (手动编辑 decision / reasons / context / values_derived)
2448
+ app.patch('/api/judgments/:id', async (req, res) => {
2449
+ try {
2450
+ const { id } = req.params;
2451
+ const { updateJudgment, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
2452
+ await initializeValueStore();
2453
+ const updated = await updateJudgment(id, req.body || {});
2454
+ if (!updated)
2455
+ return res.status(404).json({ error: 'judgment not found' });
2456
+ res.json({ ok: true, judgment: updated });
2457
+ }
2458
+ catch (err) {
2459
+ console.error('[judgments] PATCH failed:', err);
2460
+ res.status(500).json({ error: err.message });
2461
+ }
2462
+ });
2463
+ // 删除判断
2464
+ app.delete('/api/judgments/:id', async (req, res) => {
2465
+ try {
2466
+ const { id } = req.params;
2467
+ const { deleteJudgment, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
2468
+ await initializeValueStore();
2469
+ const ok = await deleteJudgment(id);
2470
+ if (!ok)
2471
+ return res.status(404).json({ error: 'judgment not found' });
2472
+ res.json({ ok: true });
2473
+ }
2474
+ catch (err) {
2475
+ console.error('[judgments] DELETE failed:', err);
2476
+ res.status(500).json({ error: err.message });
2477
+ }
2478
+ });
2479
+ // 批量删除: { ids: ['hv-xxx', ...] } → { ok, deleted, notFound }
2480
+ app.post('/api/judgments/batch-delete', async (req, res) => {
2481
+ try {
2482
+ const ids = (req.body && Array.isArray(req.body.ids)) ? req.body.ids : null;
2483
+ if (!ids)
2484
+ return res.status(400).json({ error: 'ids array required' });
2485
+ const { deleteJudgment, initializeValueStore } = await import('../pi-ecosystem-judgment/human-value-store.js');
2486
+ await initializeValueStore();
2487
+ const idStrs = ids.filter((x) => typeof x === 'string' && x.length > 0);
2488
+ let deleted = 0;
2489
+ const notFound = [];
2490
+ for (const id of idStrs) {
2491
+ const ok = await deleteJudgment(id);
2492
+ if (ok)
2493
+ deleted++;
2494
+ else
2495
+ notFound.push(id);
2496
+ }
2497
+ res.json({ ok: true, deleted, notFound });
2498
+ }
2499
+ catch (err) {
2500
+ console.error('[judgments] batch-delete failed:', err);
2501
+ res.status(500).json({ error: err.message });
2502
+ }
2503
+ });
2504
+ // AI 自动委派: 根据新判断的 capability / context 找最匹配的远端 agent, 委派任务
2505
+ // 由前端在 POST /api/judgments 成功后调用 (fire-and-forget)
2506
+ // 出参: { matched, targetAgent, response | skipped, reason }
2507
+ app.post('/api/judgments/auto-delegate', async (req, res) => {
2508
+ try {
2509
+ const { judgmentId, capability, instruction } = req.body;
2510
+ if (!judgmentId && !capability) {
2511
+ return res.status(400).json({ error: 'judgmentId or capability required' });
2512
+ }
2513
+ const cap = capability || 'general';
2514
+ // 用 agent-manifest-protocol 里的 pickAgent (内存) — 走本节点已经缓存的远端 manifest
2515
+ const manifestMod = await import('../agents/agent-manifest-protocol.js');
2516
+ const picked = manifestMod.pickAgent(cap);
2517
+ if (!picked) {
2518
+ return res.json({ ok: true, matched: false, reason: 'no remote agent matches capability' });
2519
+ }
2520
+ // 命中后, 用 iroh delegate transport 真正发过去
2521
+ // 注: irohDelegateTransport.sendToNode 走的是 sendToNode(publicKey, frame, timeoutMs)
2522
+ // irohTransport 的 sendMessage 不等回包, 所以委托是 fire-and-forget
2523
+ // 想等回包需要新接口. 这里先把 "找得到目标 + 发送成功" 作为成功.
2524
+ // TODO: 接入 requestResponse 等待远端 agent_response
2525
+ try {
2526
+ const idMod = await import('../network/iroh-integration.js');
2527
+ const integ = idMod.getIrohIntegration();
2528
+ if (!integ || !integ.getNodeId()) {
2529
+ return res.json({ ok: true, matched: true, targetAgent: picked.agent, sent: false, reason: 'iroh not initialized' });
2530
+ }
2531
+ // 用 pickAgent 选出来的 agent 关联的 irohNodeId (有的话), 没有就跳到本地自处理
2532
+ const targetIrohNodeId = picked.agent.irohNodeId;
2533
+ if (!targetIrohNodeId) {
2534
+ return res.json({ ok: true, matched: true, targetAgent: picked.agent, sent: false, reason: 'target agent has no irohNodeId (peer identity not bound)' });
2535
+ }
2536
+ const ok = await integ.sendTo(targetIrohNodeId, 'agent_delegate', new TextEncoder().encode(JSON.stringify({
2537
+ type: 'agent_delegate',
2538
+ payload: {
2539
+ capability: cap,
2540
+ instruction: instruction || `请执行我的判断: ${judgmentId}`,
2541
+ fromAgentId: 'local-judgment',
2542
+ },
2543
+ ts: Date.now(),
2544
+ fromDid: '',
2545
+ })));
2546
+ res.json({ ok: true, matched: true, targetAgent: picked.agent, sent: ok });
2547
+ }
2548
+ catch (e) {
2549
+ res.json({ ok: true, matched: true, targetAgent: picked.agent, sent: false, error: e.message });
2550
+ }
2551
+ }
2552
+ catch (err) {
2553
+ console.error('[judgments] auto-delegate failed:', err);
2554
+ res.status(500).json({ error: err.message });
2555
+ }
2556
+ });
2557
+ // (判断的 UI 已合并到主页面 header 的盾牌按钮 + modal, 不再走独立路由)
2180
2558
  // 启动看门狗监控
2181
2559
  if (watchdog) {
2182
2560
  // level 1 (内存爆) → 进程自杀, 依赖外层 supervisor / 用户重启 (Windows 任务计划/手动)
@@ -575,6 +575,13 @@ body {
575
575
  transform: rotate(90deg);
576
576
  }
577
577
 
578
+ /* ⚡ 自动工具徽章 + 当前会话名: 折叠时不显示, 只在展开时可见.
579
+ 配置 (钱包/工具) 按钮保留在行上, 用户随时能进 modal. */
580
+ .agent-group:not(.expanded) .agent-tools-badge,
581
+ .agent-group:not(.expanded) .agent-current-session {
582
+ display: none !important;
583
+ }
584
+
578
585
  .agent-new-session {
579
586
  /* 已废弃: 新建会话按钮迁移到 session 列表顶部, 见 .session-new-item */
580
587
  display: none;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bolloon/bolloon-agent",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
4
  "type": "module",
5
5
  "description": "P2P AI Document Agent - 全局安装后执行 `bolloon` 启动产品",
6
6
  "main": "dist/cli.js",
@@ -0,0 +1,117 @@
1
+ /**
2
+ * agent-manifest-protocol - 节点握手后立刻互换"我有哪些 agent + capabilities"
3
+ *
4
+ * 核心目的:实现 "建联一次,访问对方所有智能体"。
5
+ * - 节点连上 (Hyperswarm 主题 / iroh) 后立刻发 'manifest_request'
6
+ * - 对端回 'manifest_payload',写入本地 agentRegistry
7
+ * - 之后任何指令可以 pickAgent(capability, ownerDid) → 直接委派
8
+ *
9
+ * 协议消息 (Hyperswarm 字符串帧):
10
+ * manifest_request: { }
11
+ * manifest_payload: { ownerName, ownerPublicKey, agents:[{id,name,capabilities,status}], publishedAt }
12
+ *
13
+ * 本文件不绑定 transport — 只提供 build/parse/dispatch 帮助函数。
14
+ * 调用方在自己 transport 上挂 onMessage('manifest_request', ...) 和 onMessage('manifest_payload', ...)。
15
+ */
16
+
17
+ export interface AgentManifestEntry {
18
+ id: string;
19
+ name: string;
20
+ capabilities: string[];
21
+ status: 'active' | 'idle' | 'busy' | 'creating' | 'terminated';
22
+ // 可选 — 若对方把这个 agent 关联到具体子 P2P 端点
23
+ peerId?: string;
24
+ irohNodeId?: string;
25
+ sessionId?: string;
26
+ cid?: string;
27
+ ipnsName?: string;
28
+ }
29
+
30
+ export interface AgentManifest {
31
+ ownerName: string;
32
+ ownerPublicKey: string;
33
+ agents: AgentManifestEntry[];
34
+ publishedAt: number;
35
+ }
36
+
37
+ // ============== 帧构造 ==============
38
+ export function buildManifestRequest(): string {
39
+ return JSON.stringify({ type: 'manifest_request', payload: {}, ts: Date.now(), fromDid: '' });
40
+ }
41
+
42
+ export function buildManifestPayload(manifest: AgentManifest): string {
43
+ return JSON.stringify({ type: 'manifest_payload', payload: manifest, ts: Date.now(), fromDid: '' });
44
+ }
45
+
46
+ export function buildAgentDelegateRequest(opts: {
47
+ capability: string;
48
+ docPath?: string;
49
+ docContent?: string;
50
+ instruction: string;
51
+ fromAgentId: string;
52
+ }): string {
53
+ return JSON.stringify({ type: 'agent_delegate', payload: opts, ts: Date.now(), fromDid: '' });
54
+ }
55
+
56
+ export function buildAgentResponse(opts: {
57
+ ok: boolean;
58
+ delegatedTo: string;
59
+ resultCid?: string;
60
+ summary: string;
61
+ error?: string;
62
+ }): string {
63
+ return JSON.stringify({ type: 'agent_response', payload: opts, ts: Date.now(), fromDid: '' });
64
+ }
65
+
66
+ // ============== 帧解析 ==============
67
+ export function parseFrame(text: string): { type: string; payload: any; ts: number; fromDid: string } | null {
68
+ try { return JSON.parse(text); } catch { return null; }
69
+ }
70
+
71
+ // ============== 本地 manifest registry ==============
72
+ const localManifest: AgentManifest = {
73
+ ownerName: '',
74
+ ownerPublicKey: '',
75
+ agents: [],
76
+ publishedAt: 0,
77
+ };
78
+
79
+ export function setLocalManifest(m: Partial<AgentManifest>) {
80
+ Object.assign(localManifest, m, { publishedAt: Date.now() });
81
+ return localManifest;
82
+ }
83
+
84
+ export function getLocalManifest(): AgentManifest {
85
+ return localManifest;
86
+ }
87
+
88
+ export function addLocalAgent(agent: AgentManifestEntry) {
89
+ const idx = localManifest.agents.findIndex((a) => a.id === agent.id);
90
+ if (idx >= 0) localManifest.agents[idx] = agent;
91
+ else localManifest.agents.push(agent);
92
+ localManifest.publishedAt = Date.now();
93
+ return localManifest;
94
+ }
95
+
96
+ // ============== 远端 manifest 缓存 ==============
97
+ const remoteManifests: Map<string, AgentManifest> = new Map(); // key = ownerPublicKey
98
+
99
+ export function cacheRemoteManifest(m: AgentManifest) {
100
+ if (m.ownerPublicKey) remoteManifests.set(m.ownerPublicKey, m);
101
+ return m;
102
+ }
103
+
104
+ export function getRemoteManifests(): AgentManifest[] {
105
+ return Array.from(remoteManifests.values());
106
+ }
107
+
108
+ export function pickAgent(capability: string, ownerPublicKey?: string): { agent: AgentManifestEntry; owner: AgentManifest } | null {
109
+ const owners = ownerPublicKey
110
+ ? [remoteManifests.get(ownerPublicKey)].filter(Boolean) as AgentManifest[]
111
+ : getRemoteManifests();
112
+ for (const owner of owners) {
113
+ const a = owner.agents.find((x) => x.capabilities.includes(capability) && x.status === 'active');
114
+ if (a) return { agent: a, owner };
115
+ }
116
+ return null;
117
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * iroh-secret - 把 iroh secretKey 落 ~/.bolloon/iroh-secret.json
3
+ *
4
+ * iroh 默认每次启动生成新节点 ID;落盘后可实现"跨重启稳定 nodeId"。
5
+ * 对应 Issue: "建联一次访问所有智能体"需要稳定标识, 不然对方缓存的 nodeId 失效
6
+ */
7
+
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+ import * as os from 'os';
11
+ import * as crypto from 'crypto';
12
+
13
+ const SECRET_DIR = path.join(os.homedir(), '.bolloon');
14
+
15
+ export function loadOrCreateIrohSecret(role: string = 'default'): { secretKey: Uint8Array; createdAt: string; reused: boolean } {
16
+ if (!fs.existsSync(SECRET_DIR)) fs.mkdirSync(SECRET_DIR, { recursive: true });
17
+ const fp = path.join(SECRET_DIR, `iroh-secret-${role}.json`);
18
+ if (fs.existsSync(fp)) {
19
+ const j = JSON.parse(fs.readFileSync(fp, 'utf-8'));
20
+ return { secretKey: Buffer.from(j.secretKey, 'hex'), createdAt: j.createdAt, reused: true };
21
+ }
22
+ const sk = crypto.randomBytes(32);
23
+ const createdAt = new Date().toISOString();
24
+ fs.writeFileSync(fp, JSON.stringify({ secretKey: sk.toString('hex'), createdAt }, null, 2), { mode: 0o600 });
25
+ // chmod in case the file already existed and umask produced looser perms
26
+ try { fs.chmodSync(fp, 0o600); } catch {}
27
+ return { secretKey: sk, createdAt, reused: false };
28
+ }
29
+
30
+ export function irohSecretFilePath(role: string = 'default'): string {
31
+ return path.join(SECRET_DIR, `iroh-secret-${role}.json`);
32
+ }