@bolloon/bolloon-agent 0.3.52 → 0.4.0
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/README.md +135 -135
- package/bin/bolloon-cli.cjs +183 -183
- package/bin/bolloon.cjs +0 -0
- package/bin/bolloon.js +157 -0
- package/dist/agents/constraint-layer.js +19 -19
- package/dist/agents/judgment-protocol.js +14 -14
- package/dist/agents/loop-review.js +21 -0
- package/dist/agents/pi-sdk-tools.js +86 -2
- package/dist/agents/pi-sdk-types.js +12 -12
- package/dist/agents/pi-sdk.js +90 -90
- package/dist/agents/shell-guard.js +22 -1
- package/dist/agents/skill-organizer.js +19 -19
- package/dist/agents/verify-recipe.js +84 -0
- package/dist/agents/workflow-pivot-loop.js +101 -13
- package/dist/bollharness/src/scripts/deploy-guard.js +8 -8
- package/dist/bollharness-integration/context-router-judgment.js +4 -4
- package/dist/bollharness-integration/context-router.js +292 -292
- package/dist/bollharness-integration/gate-state-machine.js +13 -13
- package/dist/bollharness-integration/llm-judgment-engine.js +134 -134
- package/dist/bollharness-integration/skill-adapter.js +21 -21
- package/dist/bootstrap/chat-archiver.js +14 -14
- package/dist/bootstrap/context-os.js +50 -40
- package/dist/bootstrap/memory-compressor.js +13 -13
- package/dist/cli-entry.js +36 -36
- package/dist/context-compaction/auto-compact.js +7 -7
- package/dist/electron/first-run.js +54 -54
- package/dist/electron-build/electron/first-run.js +54 -54
- package/dist/electron-preload.js.map +1 -1
- package/dist/electron.js.map +1 -1
- package/dist/external-engines/delegate-handle.js +70 -0
- package/dist/external-engines/delegate.js +24 -3
- package/dist/index.js +112 -112
- package/dist/llm/error-lessons.js +53 -0
- package/dist/llm/llm-judgment-client.js +102 -102
- package/dist/llm/pi-ai.js +61 -48
- package/dist/llm/system-prompt/layers/channel/human-async.md +41 -41
- package/dist/llm/system-prompt/layers/channel/local.md +14 -14
- package/dist/llm/system-prompt/layers/channel/p2p-agent.md +18 -18
- package/dist/llm/system-prompt/layers/channel/p2p-peer-sync.md +51 -51
- package/dist/llm/system-prompt/layers/channel/p2p-proactive.md +43 -43
- package/dist/llm/system-prompt/layers/channel/p2p-visitor.md +19 -19
- package/dist/llm/system-prompt/layers/channel/session-handoff.md +61 -61
- package/dist/llm/system-prompt/layers/core/artifacts_storage.md +89 -89
- package/dist/llm/system-prompt/layers/core/evenhandedness.md +21 -21
- package/dist/llm/system-prompt/layers/core/external-engagement.md +73 -73
- package/dist/llm/system-prompt/layers/core/hibs_reminders.md +15 -15
- package/dist/llm/system-prompt/layers/core/identity.md +48 -48
- package/dist/llm/system-prompt/layers/core/knowledge.md +17 -17
- package/dist/llm/system-prompt/layers/core/memory_system.md +12 -12
- package/dist/llm/system-prompt/layers/core/network_filesystem.md +28 -28
- package/dist/llm/system-prompt/layers/core/refusal.md +37 -37
- package/dist/llm/system-prompt/layers/core/tone.md +31 -31
- package/dist/llm/system-prompt/layers/core/tools.thin.md +13 -13
- package/dist/llm/system-prompt/layers/core/wellbeing.md +41 -41
- package/dist/llm/system-prompt/layers/role/architect.md +20 -20
- package/dist/llm/system-prompt/layers/role/expert.md +19 -19
- package/dist/llm/system-prompt/layers/role/implementer.md +15 -15
- package/dist/llm/system-prompt/layers/role/security.md +15 -15
- package/dist/llm/system-prompt/layers/tool/artifacts.md +72 -72
- package/dist/llm/system-prompt/layers/tool/bash.md +25 -25
- package/dist/llm/system-prompt/layers/tool/goal_handoff.md +77 -77
- package/dist/llm/system-prompt/layers/tool/hibs_api.md +171 -171
- package/dist/llm/system-prompt/layers/tool/image_search.md +70 -70
- package/dist/llm/system-prompt/layers/tool/manifest.md +89 -89
- package/dist/llm/system-prompt/layers/tool/mcp_apps.md +53 -53
- package/dist/llm/system-prompt/layers/tool/p2p_request.md +61 -61
- package/dist/llm/system-prompt/layers/tool/web_search.md +83 -83
- package/dist/llm/system-prompt/registry.js +9 -1
- package/dist/llm/tool-manifest/ask_user_input.js +1 -1
- package/dist/llm/tool-manifest/bash.js +3 -3
- package/dist/llm/tool-manifest/create_file.js +4 -4
- package/dist/llm/tool-manifest/fetch_sports_data.js +3 -3
- package/dist/llm/tool-manifest/image_search.js +2 -2
- package/dist/llm/tool-manifest/index.js +0 -59
- package/dist/llm/tool-manifest/mcp.js +2 -2
- package/dist/llm/tool-manifest/message_compose.js +3 -3
- package/dist/llm/tool-manifest/places.js +2 -2
- package/dist/llm/tool-manifest/present_files.js +1 -1
- package/dist/llm/tool-manifest/recipe.js +2 -2
- package/dist/llm/tool-manifest/str_replace.js +5 -5
- package/dist/llm/tool-manifest/view.js +3 -3
- package/dist/llm/tool-manifest/weather.js +4 -4
- package/dist/llm/tool-manifest/web.js +4 -4
- package/dist/locales/en.js +28 -0
- package/dist/locales/zh.js +26 -0
- package/dist/pi-ecosystem-colony/index.js +365 -0
- package/dist/pi-ecosystem-judgment/causal-judge.js +51 -51
- package/dist/pi-ecosystem-judgment/distill-prompt.js +42 -42
- package/dist/pi-ecosystem-judgment/distillation.js +14 -14
- package/dist/pi-ecosystem-judgment/monitor-gate.js +28 -28
- package/dist/pi-ecosystem-judgment/value-injection.js +102 -102
- package/dist/security/context-router-tool.js +15 -15
- package/dist/social/ant-colony/AdaptiveHeartbeat.js +101 -0
- package/dist/social/ant-colony/PheromoneEngine.js +227 -0
- package/dist/social/ant-colony/index.js +6 -0
- package/dist/social/ant-colony/types.js +24 -0
- package/dist/storage/trajectory.js +101 -0
- package/dist/test/ai-judgment-test.js +80 -0
- package/dist/test/bollharness-integration.test.js +318 -0
- package/dist/test/channel-agent-multi-dialogue.js +205 -0
- package/dist/test/channel-heartbeat-agent-test.js +201 -0
- package/dist/test/constraint-layer.test.js +164 -0
- package/dist/test/diap-identity-test.js +172 -0
- package/dist/test/diap-quick-test.js +62 -0
- package/dist/test/global-shared-context.test.js +315 -0
- package/dist/test/harness-judgment-injection.test.js +246 -0
- package/dist/test/harness-workflow-integrator-test.js +228 -0
- package/dist/test/human-value-store.test.js +243 -0
- package/dist/test/hybrid-integration-test.js +118 -0
- package/dist/test/hybrid-messenger-verify.js +55 -0
- package/dist/test/iroh-bistream-debug.js +38 -0
- package/dist/test/iroh-communication.test.js +66 -0
- package/dist/test/iroh-debug-test.js +57 -0
- package/dist/test/iroh-diap-test.js +71 -0
- package/dist/test/iroh-direct-connect.js +55 -0
- package/dist/test/iroh-e2e-fixed.js +89 -0
- package/dist/test/iroh-e2e-same-process.js +63 -0
- package/dist/test/iroh-e2e.js +66 -0
- package/dist/test/iroh-final-e2e.js +72 -0
- package/dist/test/iroh-relay-test.js +37 -0
- package/dist/test/iroh-simple-test.js +41 -0
- package/dist/test/iroh-transport-verify.js +54 -0
- package/dist/test/iroh-transport.test.js +37 -0
- package/dist/test/iroh-two-nodes.js +70 -0
- package/dist/test/iroh-verify.js +44 -0
- package/dist/test/judgment-decision.test.js +219 -0
- package/dist/test/llm-judgment-integration.test.js +220 -0
- package/dist/test/p2p-agent-complex-dialogue.js +385 -0
- package/dist/test/p2p-agent-dialogue.js +341 -0
- package/dist/test/p2p-agent-full-bidirectional.js +510 -0
- package/dist/test/p2p-agent-harness-flow.js +437 -0
- package/dist/test/p2p-agent-harness-single.js +143 -0
- package/dist/test/p2p-ai-dialogue-test.js +318 -0
- package/dist/test/p2p-cid-connect-test.js +195 -0
- package/dist/test/p2p-connect-receiver.js +69 -0
- package/dist/test/p2p-doc-transfer.js +110 -0
- package/dist/test/p2p-identity-page-test.js +77 -0
- package/dist/test/p2p-iroh-test.js +171 -0
- package/dist/test/p2p-minimal-test.js +241 -0
- package/dist/test/p2p-node-1.js +148 -0
- package/dist/test/p2p-node-2.js +148 -0
- package/dist/test/p2p-server.js +281 -0
- package/dist/test/p2p-two-nodes-test.js +438 -0
- package/dist/test/pi-sdk.test.js +44 -0
- package/dist/test/set-persona.js +40 -0
- package/dist/test/simple.test.js +9 -0
- package/dist/test/storage-integration.test.js +150 -0
- package/dist/test/subagent-manager.test.js +276 -0
- package/dist/test/test-gate-flow.test.js +81 -0
- package/dist/test/workflow-engine.test.js +87 -0
- package/dist/test/workflow-pivot-loop.test.js +246 -0
- package/dist/web/api-config.html +779 -779
- package/dist/web/client-hearth.js +10 -10
- package/dist/web/components/wallet-viem.mjs +118 -118
- package/dist/web/delivery-ledger.js +103 -0
- package/dist/web/i18n.js +104 -0
- package/dist/web/index.html +472 -472
- package/dist/web/manifest.json +20 -20
- package/dist/web/routes-tasks.js +242 -24
- package/dist/web/server-storage.js +111 -0
- package/dist/web/server.js +55 -26
- package/dist/web/style.css +4946 -4946
- package/dist/web/task-breaker.js +18 -0
- package/dist/web/task-cancel.js +35 -0
- package/dist/web/task-deps.js +36 -0
- package/dist/web/task-review.js +27 -0
- package/dist/web/task-verify.js +60 -0
- package/package.json +196 -196
- package/scripts/build-cli.js +215 -215
- package/scripts/build-web.ts +130 -130
- package/scripts/postinstall.js +152 -152
- package/bin/bolloon-daemon.sh +0 -207
- package/dist/constraint-runtime/reference_data/archive_surface_snapshot.json +0 -63
- package/dist/constraint-runtime/reference_data/commands_snapshot.json +0 -1037
- package/dist/constraint-runtime/reference_data/subsystems/assistant.json +0 -8
- package/dist/constraint-runtime/reference_data/subsystems/bootstrap.json +0 -8
- package/dist/constraint-runtime/reference_data/subsystems/bridge.json +0 -32
- package/dist/constraint-runtime/reference_data/subsystems/buddy.json +0 -13
- package/dist/constraint-runtime/reference_data/subsystems/cli.json +0 -26
- package/dist/constraint-runtime/reference_data/subsystems/components.json +0 -32
- package/dist/constraint-runtime/reference_data/subsystems/constants.json +0 -28
- package/dist/constraint-runtime/reference_data/subsystems/coordinator.json +0 -8
- package/dist/constraint-runtime/reference_data/subsystems/entrypoints.json +0 -15
- package/dist/constraint-runtime/reference_data/subsystems/hooks.json +0 -32
- package/dist/constraint-runtime/reference_data/subsystems/keybindings.json +0 -21
- package/dist/constraint-runtime/reference_data/subsystems/memdir.json +0 -15
- package/dist/constraint-runtime/reference_data/subsystems/migrations.json +0 -18
- package/dist/constraint-runtime/reference_data/subsystems/moreright.json +0 -8
- package/dist/constraint-runtime/reference_data/subsystems/native_ts.json +0 -11
- package/dist/constraint-runtime/reference_data/subsystems/outputStyles.json +0 -8
- package/dist/constraint-runtime/reference_data/subsystems/plugins.json +0 -9
- package/dist/constraint-runtime/reference_data/subsystems/remote.json +0 -11
- package/dist/constraint-runtime/reference_data/subsystems/schemas.json +0 -8
- package/dist/constraint-runtime/reference_data/subsystems/screens.json +0 -10
- package/dist/constraint-runtime/reference_data/subsystems/server.json +0 -10
- package/dist/constraint-runtime/reference_data/subsystems/services.json +0 -32
- package/dist/constraint-runtime/reference_data/subsystems/skills.json +0 -27
- package/dist/constraint-runtime/reference_data/subsystems/state.json +0 -13
- package/dist/constraint-runtime/reference_data/subsystems/types.json +0 -18
- package/dist/constraint-runtime/reference_data/subsystems/upstreamproxy.json +0 -9
- package/dist/constraint-runtime/reference_data/subsystems/utils.json +0 -32
- package/dist/constraint-runtime/reference_data/subsystems/vim.json +0 -12
- package/dist/constraint-runtime/reference_data/subsystems/voice.json +0 -8
- package/dist/constraint-runtime/reference_data/tools_snapshot.json +0 -922
- package/dist/electron/config.js.map +0 -1
- package/dist/electron/dialogs.js.map +0 -1
- package/dist/electron/first-run.js.map +0 -1
- package/dist/electron/ipc.js.map +0 -1
- package/dist/electron/logger.js.map +0 -1
- package/dist/electron/main.js.map +0 -1
- package/dist/electron/menu.js.map +0 -1
- package/dist/electron/paths.js.map +0 -1
- package/dist/electron/server.js.map +0 -1
- package/dist/electron/tray.js.map +0 -1
- package/dist/electron/window.js.map +0 -1
- package/dist/utils/auto-update.js.map +0 -1
- package/dist/web/client.js.map +0 -7
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AdaptiveHeartbeat - 动态心跳策略
|
|
3
|
+
*
|
|
4
|
+
* 基于活跃度、信息素密度等因子动态调整心跳间隔
|
|
5
|
+
*/
|
|
6
|
+
import { DEFAULT_ADAPTIVE_CONFIG, } from './types.js';
|
|
7
|
+
export class AdaptiveHeartbeat {
|
|
8
|
+
config;
|
|
9
|
+
lastActivityTime = Date.now();
|
|
10
|
+
activityHistory = [];
|
|
11
|
+
recentDiscoveries = 0;
|
|
12
|
+
pheromoneDensity = 0;
|
|
13
|
+
discoveryBoost = 0;
|
|
14
|
+
activityTimer = null;
|
|
15
|
+
constructor(config) {
|
|
16
|
+
this.config = { ...DEFAULT_ADAPTIVE_CONFIG, ...config };
|
|
17
|
+
this.startActivityTracking();
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 获取下一次心跳的决策
|
|
21
|
+
*/
|
|
22
|
+
decide() {
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
const timeSinceLastActivity = now - this.lastActivityTime;
|
|
25
|
+
const activityRate = this.calculateActivityRate();
|
|
26
|
+
const pheromoneFactor = this.pheromoneDensity;
|
|
27
|
+
const discoveryFactor = this.calculateDiscoveryFactor();
|
|
28
|
+
const combinedFactor = activityRate * 0.2 +
|
|
29
|
+
pheromoneFactor * this.config.pheromoneBoostFactor +
|
|
30
|
+
discoveryFactor * this.config.discoveryBoostFactor;
|
|
31
|
+
const interval = Math.max(this.config.minInterval, Math.min(this.config.maxInterval, this.config.baseInterval * (1 - combinedFactor * 0.7)));
|
|
32
|
+
let priority = 'normal';
|
|
33
|
+
if (discoveryFactor > 0.5 || this.discoveryBoost > 0.6) {
|
|
34
|
+
priority = 'high';
|
|
35
|
+
}
|
|
36
|
+
else if (this.discoveryBoost > 0.8) {
|
|
37
|
+
priority = 'urgent';
|
|
38
|
+
}
|
|
39
|
+
else if (activityRate < this.config.lowActivityThreshold) {
|
|
40
|
+
priority = 'low';
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
interval: Math.round(interval),
|
|
44
|
+
shouldExplore: discoveryFactor > 0.3 || pheromoneFactor > 0.5,
|
|
45
|
+
shouldBroadcast: priority !== 'low' || timeSinceLastActivity > this.config.baseInterval,
|
|
46
|
+
priorityLevel: priority,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 记录活跃事件
|
|
51
|
+
*/
|
|
52
|
+
recordActivity(type) {
|
|
53
|
+
const now = Date.now();
|
|
54
|
+
this.lastActivityTime = now;
|
|
55
|
+
this.activityHistory.push(now);
|
|
56
|
+
if (type === 'discovery') {
|
|
57
|
+
this.recentDiscoveries++;
|
|
58
|
+
this.discoveryBoost = Math.min(1, this.discoveryBoost + 0.2);
|
|
59
|
+
}
|
|
60
|
+
this.discoveryBoost = Math.max(0, this.discoveryBoost - 0.05);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* 设置信息素密度
|
|
64
|
+
*/
|
|
65
|
+
setPheromoneDensity(density) {
|
|
66
|
+
this.pheromoneDensity = Math.max(0, Math.min(1, density));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 获取当前配置
|
|
70
|
+
*/
|
|
71
|
+
getConfig() {
|
|
72
|
+
return { ...this.config };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* 更新配置
|
|
76
|
+
*/
|
|
77
|
+
updateConfig(updates) {
|
|
78
|
+
this.config = { ...this.config, ...updates };
|
|
79
|
+
}
|
|
80
|
+
calculateActivityRate() {
|
|
81
|
+
const now = Date.now();
|
|
82
|
+
const recentActivity = this.activityHistory.filter((t) => now - t < 60000).length;
|
|
83
|
+
return recentActivity / 60;
|
|
84
|
+
}
|
|
85
|
+
calculateDiscoveryFactor() {
|
|
86
|
+
return Math.min(1, this.recentDiscoveries / 5);
|
|
87
|
+
}
|
|
88
|
+
startActivityTracking() {
|
|
89
|
+
this.activityTimer = setInterval(() => {
|
|
90
|
+
const cutoff = Date.now() - 5 * 60 * 1000;
|
|
91
|
+
this.activityHistory = this.activityHistory.filter((t) => t > cutoff);
|
|
92
|
+
this.recentDiscoveries = Math.max(0, this.recentDiscoveries - 1);
|
|
93
|
+
this.discoveryBoost = Math.max(0, this.discoveryBoost - 0.1);
|
|
94
|
+
}, 60000);
|
|
95
|
+
}
|
|
96
|
+
shutdown() {
|
|
97
|
+
if (this.activityTimer) {
|
|
98
|
+
clearInterval(this.activityTimer);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PheromoneEngine - 信息素管理引擎
|
|
3
|
+
*
|
|
4
|
+
* 模拟蚂蚁的信息素系统,用于引导智能体发现和路由决策
|
|
5
|
+
*/
|
|
6
|
+
import * as fs from 'fs/promises';
|
|
7
|
+
import * as path from 'path';
|
|
8
|
+
import { PheromoneType, DEFAULT_PHEROMONE_CONFIG, } from './types.js';
|
|
9
|
+
export { PheromoneType };
|
|
10
|
+
const PHEROMONE_DB_PATH = path.join(process.env.HOME || '/tmp', '.bolloon', 'ant-colony', 'pheromones.json');
|
|
11
|
+
export class PheromoneEngine {
|
|
12
|
+
trails = new Map();
|
|
13
|
+
fields = new Map();
|
|
14
|
+
evaporationTimer = null;
|
|
15
|
+
saveTimer = null;
|
|
16
|
+
dirty = false;
|
|
17
|
+
async initialize() {
|
|
18
|
+
await fs.mkdir(path.dirname(PHEROMONE_DB_PATH), { recursive: true });
|
|
19
|
+
await this.load();
|
|
20
|
+
this.startEvaporation();
|
|
21
|
+
this.startAutoSave();
|
|
22
|
+
}
|
|
23
|
+
startEvaporation() {
|
|
24
|
+
this.evaporationTimer = setInterval(() => {
|
|
25
|
+
this.evaporate();
|
|
26
|
+
}, DEFAULT_PHEROMONE_CONFIG.evaporationInterval);
|
|
27
|
+
}
|
|
28
|
+
startAutoSave() {
|
|
29
|
+
this.saveTimer = setInterval(() => {
|
|
30
|
+
if (this.dirty) {
|
|
31
|
+
this.save().catch(console.error);
|
|
32
|
+
this.dirty = false;
|
|
33
|
+
}
|
|
34
|
+
}, 30000);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* 放置信息素
|
|
38
|
+
*/
|
|
39
|
+
async deposit(type, sourceDid, targetDid, strength = 0.5, options) {
|
|
40
|
+
const key = this.getTrailKey(type, sourceDid, targetDid);
|
|
41
|
+
const existing = this.trails.get(key);
|
|
42
|
+
const newStrength = existing
|
|
43
|
+
? Math.min(1, existing.strength + strength * 0.3)
|
|
44
|
+
: Math.min(1, strength);
|
|
45
|
+
const trail = {
|
|
46
|
+
id: key,
|
|
47
|
+
type,
|
|
48
|
+
sourceDid,
|
|
49
|
+
targetDid,
|
|
50
|
+
strength: newStrength,
|
|
51
|
+
decayRate: DEFAULT_PHEROMONE_CONFIG.decayRate,
|
|
52
|
+
createdAt: existing?.createdAt || Date.now(),
|
|
53
|
+
lastUpdate: Date.now(),
|
|
54
|
+
capability: options?.capability,
|
|
55
|
+
qualityScore: options?.qualityScore,
|
|
56
|
+
};
|
|
57
|
+
this.trails.set(key, trail);
|
|
58
|
+
this.dirty = true;
|
|
59
|
+
if (options?.capability) {
|
|
60
|
+
this.updateField(type, targetDid, options.capability);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 读取某方向的信息素强度
|
|
65
|
+
*/
|
|
66
|
+
getStrength(type, targetDid) {
|
|
67
|
+
let totalStrength = 0;
|
|
68
|
+
let count = 0;
|
|
69
|
+
for (const trail of this.trails.values()) {
|
|
70
|
+
if (trail.type === type && trail.targetDid === targetDid) {
|
|
71
|
+
totalStrength += trail.strength;
|
|
72
|
+
count++;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return count > 0 ? totalStrength / count : 0;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* 查询特定能力的最佳节点
|
|
79
|
+
*/
|
|
80
|
+
queryByCapability(capability, limit = 5) {
|
|
81
|
+
const field = this.fields.get(capability);
|
|
82
|
+
if (!field)
|
|
83
|
+
return [];
|
|
84
|
+
const candidates = [];
|
|
85
|
+
for (const trail of this.trails.values()) {
|
|
86
|
+
if (trail.type === PheromoneType.CAPABILITY &&
|
|
87
|
+
trail.capability?.includes(capability)) {
|
|
88
|
+
const score = trail.strength * (trail.qualityScore || 0.5);
|
|
89
|
+
candidates.push({ did: trail.targetDid, strength: score });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
candidates.sort((a, b) => b.strength - a.strength);
|
|
93
|
+
return candidates.slice(0, limit).map((c) => c.did);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* 获取到达某节点的最佳下一跳
|
|
97
|
+
*/
|
|
98
|
+
getNextHop(targetDid, excludeDids = []) {
|
|
99
|
+
let bestHop = null;
|
|
100
|
+
let bestStrength = 0;
|
|
101
|
+
for (const trail of this.trails.values()) {
|
|
102
|
+
if (trail.targetDid === targetDid && trail.strength > bestStrength) {
|
|
103
|
+
if (!excludeDids.includes(trail.sourceDid)) {
|
|
104
|
+
bestHop = trail.sourceDid;
|
|
105
|
+
bestStrength = trail.strength;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return bestHop;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* 获取所有已知节点及其信息素强度
|
|
113
|
+
*/
|
|
114
|
+
getAllNodeStrengths() {
|
|
115
|
+
const result = new Map();
|
|
116
|
+
for (const trail of this.trails.values()) {
|
|
117
|
+
const current = result.get(trail.targetDid) || 0;
|
|
118
|
+
result.set(trail.targetDid, Math.max(current, trail.strength));
|
|
119
|
+
}
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* 获取信息素统计
|
|
124
|
+
*/
|
|
125
|
+
getStats() {
|
|
126
|
+
let totalStrength = 0;
|
|
127
|
+
for (const trail of this.trails.values()) {
|
|
128
|
+
totalStrength += trail.strength;
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
totalTrails: this.trails.size,
|
|
132
|
+
avgStrength: this.trails.size > 0 ? totalStrength / this.trails.size : 0,
|
|
133
|
+
capabilityCount: this.fields.size,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
getTrailKey(type, source, target) {
|
|
137
|
+
return `${type}:${source}:${target}`;
|
|
138
|
+
}
|
|
139
|
+
updateField(type, targetDid, capability) {
|
|
140
|
+
if (!capability)
|
|
141
|
+
return;
|
|
142
|
+
for (const cap of capability) {
|
|
143
|
+
let field = this.fields.get(cap);
|
|
144
|
+
if (!field) {
|
|
145
|
+
field = {
|
|
146
|
+
capability: cap,
|
|
147
|
+
avgStrength: 0,
|
|
148
|
+
nodeCount: 0,
|
|
149
|
+
lastUpdate: Date.now(),
|
|
150
|
+
};
|
|
151
|
+
this.fields.set(cap, field);
|
|
152
|
+
}
|
|
153
|
+
const trails = Array.from(this.trails.values()).filter((t) => t.type === type && t.capability?.includes(cap));
|
|
154
|
+
field.avgStrength =
|
|
155
|
+
trails.reduce((sum, t) => sum + t.strength, 0) / (trails.length || 1);
|
|
156
|
+
field.nodeCount = new Set(trails.map((t) => t.targetDid)).size;
|
|
157
|
+
field.lastUpdate = Date.now();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
evaporate() {
|
|
161
|
+
const now = Date.now();
|
|
162
|
+
const toDelete = [];
|
|
163
|
+
for (const [key, trail] of this.trails.entries()) {
|
|
164
|
+
const ageHours = (now - trail.lastUpdate) / (1000 * 60 * 60);
|
|
165
|
+
const decayFactor = Math.pow(1 - trail.decayRate, ageHours);
|
|
166
|
+
trail.strength = trail.strength * decayFactor;
|
|
167
|
+
if (trail.strength < DEFAULT_PHEROMONE_CONFIG.minStrength ||
|
|
168
|
+
now - trail.createdAt > DEFAULT_PHEROMONE_CONFIG.maxTrailAge) {
|
|
169
|
+
toDelete.push(key);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
trail.lastUpdate = now;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
for (const key of toDelete) {
|
|
176
|
+
this.trails.delete(key);
|
|
177
|
+
}
|
|
178
|
+
if (toDelete.length > 0) {
|
|
179
|
+
this.dirty = true;
|
|
180
|
+
this.save().catch(console.error);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async save() {
|
|
184
|
+
try {
|
|
185
|
+
const data = {
|
|
186
|
+
trails: Array.from(this.trails.values()),
|
|
187
|
+
fields: Array.from(this.fields.entries()),
|
|
188
|
+
};
|
|
189
|
+
await fs.writeFile(PHEROMONE_DB_PATH, JSON.stringify(data, null, 2));
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
console.warn('[PheromoneEngine] Save failed:', e);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async load() {
|
|
196
|
+
try {
|
|
197
|
+
const data = await fs.readFile(PHEROMONE_DB_PATH, 'utf-8');
|
|
198
|
+
const parsed = JSON.parse(data);
|
|
199
|
+
this.trails.clear();
|
|
200
|
+
for (const t of parsed.trails || []) {
|
|
201
|
+
this.trails.set(t.id, t);
|
|
202
|
+
}
|
|
203
|
+
this.fields.clear();
|
|
204
|
+
for (const [cap, field] of parsed.fields || []) {
|
|
205
|
+
this.fields.set(cap, field);
|
|
206
|
+
}
|
|
207
|
+
console.log(`[PheromoneEngine] Loaded ${this.trails.size} trails, ${this.fields.size} fields`);
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
console.log('[PheromoneEngine] No existing pheromone data, starting fresh');
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
shutdown() {
|
|
214
|
+
if (this.evaporationTimer) {
|
|
215
|
+
clearInterval(this.evaporationTimer);
|
|
216
|
+
}
|
|
217
|
+
if (this.saveTimer) {
|
|
218
|
+
clearInterval(this.saveTimer);
|
|
219
|
+
}
|
|
220
|
+
if (this.dirty) {
|
|
221
|
+
this.save()
|
|
222
|
+
.then(() => console.log('[PheromoneEngine] Saved on shutdown'))
|
|
223
|
+
.catch(console.error);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
export const pheromoneEngine = new PheromoneEngine();
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ant Colony Module - 蚁群心跳系统核心模块
|
|
3
|
+
*/
|
|
4
|
+
export { PheromoneType, DEFAULT_PHEROMONE_CONFIG, DEFAULT_ADAPTIVE_CONFIG, } from './types.js';
|
|
5
|
+
export { PheromoneEngine, pheromoneEngine } from './PheromoneEngine.js';
|
|
6
|
+
export { AdaptiveHeartbeat } from './AdaptiveHeartbeat.js';
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ant Colony Types - 信息素系统类型定义
|
|
3
|
+
*/
|
|
4
|
+
export var PheromoneType;
|
|
5
|
+
(function (PheromoneType) {
|
|
6
|
+
PheromoneType["DISCOVERY"] = "discovery";
|
|
7
|
+
PheromoneType["CAPABILITY"] = "capability";
|
|
8
|
+
})(PheromoneType || (PheromoneType = {}));
|
|
9
|
+
export const DEFAULT_PHEROMONE_CONFIG = {
|
|
10
|
+
decayRate: 0.05,
|
|
11
|
+
evaporationInterval: 5 * 60 * 1000,
|
|
12
|
+
maxTrailAge: 24 * 60 * 60 * 1000,
|
|
13
|
+
minStrength: 0.05,
|
|
14
|
+
maxStrength: 1.0,
|
|
15
|
+
};
|
|
16
|
+
export const DEFAULT_ADAPTIVE_CONFIG = {
|
|
17
|
+
minInterval: 10 * 1000,
|
|
18
|
+
maxInterval: 120 * 1000,
|
|
19
|
+
baseInterval: 30 * 1000,
|
|
20
|
+
lowActivityThreshold: 0.5,
|
|
21
|
+
highActivityThreshold: 5,
|
|
22
|
+
pheromoneBoostFactor: 0.3,
|
|
23
|
+
discoveryBoostFactor: 0.4,
|
|
24
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* trajectory.ts — agent 运行轨迹录制 (2026-08-08)
|
|
3
|
+
*
|
|
4
|
+
* 把 bolloon agent 一次运行的完整过程 (用户输入 / 工具步骤 / 思考 / 最终回复)
|
|
5
|
+
* 沉淀进 DID 目录 (Postgres 式, 以用户 DID 分区) + 镜像到 OrbitDB CID 存储,
|
|
6
|
+
* 供多设备同步 (DidCatalog WAL 回放) 与去中心化 CID 拉取 (cid_load) 双通道消费。
|
|
7
|
+
*
|
|
8
|
+
* 设计:
|
|
9
|
+
* - capture: 收集运行事件 (step_start/done/error/thinking/done) 到一个 Trajectory
|
|
10
|
+
* - flush: 把轨迹写入 DidCatalog context_os 表 (key = runId, DID 分区),
|
|
11
|
+
* 并 (可选) 通过 getCIDDatabase() 保存为 type='state' 记录 + share 上链
|
|
12
|
+
* - 非致命: OrbitDB 首次拉起较重, 全部 fire-and-forget + 吞错, 不影响 agent 主流程
|
|
13
|
+
*
|
|
14
|
+
* 用法 (server / CLI 的 run-end finally 里):
|
|
15
|
+
* const t = createTrajectory({ runId, did, agentId });
|
|
16
|
+
* t.capture(event); // 事件流中逐条喂
|
|
17
|
+
* await t.flush({ mirrorOrbit: true });
|
|
18
|
+
*/
|
|
19
|
+
import { registryOpen } from './did-catalog.js';
|
|
20
|
+
/** 是否工具步骤事件 */
|
|
21
|
+
function isToolStep(ev) {
|
|
22
|
+
return ev.type === 'step_done' || ev.type === 'step_error' || (ev.type === 'step_start');
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 创建轨迹录制器。
|
|
26
|
+
* @param meta.did 用户 DID — 作为目录分区主键 (跨设备绑定)。
|
|
27
|
+
*/
|
|
28
|
+
export function createTrajectory(meta) {
|
|
29
|
+
const events = [];
|
|
30
|
+
return {
|
|
31
|
+
meta: { ...meta, startedAt: meta.startedAt ?? Date.now() },
|
|
32
|
+
get size() { return events.length; },
|
|
33
|
+
capture(ev) {
|
|
34
|
+
if (ev)
|
|
35
|
+
events.push(ev);
|
|
36
|
+
},
|
|
37
|
+
summary() {
|
|
38
|
+
const m = {};
|
|
39
|
+
for (const e of events)
|
|
40
|
+
m[e.type] = (m[e.type] || 0) + 1;
|
|
41
|
+
return m;
|
|
42
|
+
},
|
|
43
|
+
async flush(opts = {}) {
|
|
44
|
+
const okTools = events.filter((e) => e.type === 'step_done' && e.success !== false && e.tool && e.tool !== 'system');
|
|
45
|
+
const toolNames = Array.from(new Set(okTools.map((e) => e.tool))).slice(0, 12).join(', ');
|
|
46
|
+
const failed = events.filter((e) => e.type === 'step_error' || (e.type === 'step_done' && e.success === false));
|
|
47
|
+
const endedAt = Date.now();
|
|
48
|
+
const start = meta.startedAt ?? endedAt;
|
|
49
|
+
const payload = {
|
|
50
|
+
runId: meta.runId,
|
|
51
|
+
agentId: meta.agentId,
|
|
52
|
+
source: meta.source,
|
|
53
|
+
channelId: meta.channelId,
|
|
54
|
+
startedAt: start,
|
|
55
|
+
endedAt,
|
|
56
|
+
durationMs: endedAt - start,
|
|
57
|
+
toolCount: okTools.length,
|
|
58
|
+
failedCount: failed.length,
|
|
59
|
+
toolNames,
|
|
60
|
+
summary: events.reduce((acc, e) => {
|
|
61
|
+
acc[e.type] = (acc[e.type] || 0) + 1;
|
|
62
|
+
return acc;
|
|
63
|
+
}, {}),
|
|
64
|
+
events: events.slice(-200).map((e) => ({
|
|
65
|
+
type: e.type,
|
|
66
|
+
tool: e.tool,
|
|
67
|
+
success: e.success,
|
|
68
|
+
durationMs: e.durationMs,
|
|
69
|
+
output: e.output ? String(e.output).slice(0, 400) : undefined,
|
|
70
|
+
error: e.error ? String(e.error).slice(0, 400) : undefined,
|
|
71
|
+
})),
|
|
72
|
+
};
|
|
73
|
+
// 1) 写入 DID 目录 (Postgres 式, 以用户 DID 分区)
|
|
74
|
+
const cat = await registryOpen(meta.did, opts.home ? { home: opts.home } : {});
|
|
75
|
+
const key = `run-${meta.runId}`;
|
|
76
|
+
await cat.upsert('context_os', key, payload);
|
|
77
|
+
await cat.persist();
|
|
78
|
+
// 2) 镜像到 OrbitDB (fire-and-forget, 非致命)
|
|
79
|
+
let orbitCid;
|
|
80
|
+
if (opts.mirrorOrbit) {
|
|
81
|
+
try {
|
|
82
|
+
const { getCIDDatabase } = await import('../orbitdb/cid-database.js');
|
|
83
|
+
const db = getCIDDatabase();
|
|
84
|
+
const rec = await db.save({
|
|
85
|
+
agentId: meta.agentId || 'bolloon',
|
|
86
|
+
type: 'state',
|
|
87
|
+
content: payload,
|
|
88
|
+
metadata: { runId: meta.runId, did: meta.did, kind: 'trajectory' },
|
|
89
|
+
});
|
|
90
|
+
orbitCid = rec.id;
|
|
91
|
+
try {
|
|
92
|
+
await db.share(rec.id);
|
|
93
|
+
}
|
|
94
|
+
catch { /* 上链失败不致命 */ }
|
|
95
|
+
}
|
|
96
|
+
catch { /* OrbitDB 不可用则跳过镜像 */ }
|
|
97
|
+
}
|
|
98
|
+
return { catalogKey: key, orbitCid };
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI + 判断力注入 测试
|
|
3
|
+
* 验证 AI 调用和价值观注入功能
|
|
4
|
+
*/
|
|
5
|
+
import { createAgentSession } from '../agents/pi-sdk.js';
|
|
6
|
+
import { generateValueInjection } from '../pi-ecosystem-judgment/value-injection.js';
|
|
7
|
+
import { storeHumanJudgment, initializeValueStore, getValueStats } from '../pi-ecosystem-judgment/human-value-store.js';
|
|
8
|
+
async function main() {
|
|
9
|
+
console.log('╔═══════════════════════════════════════════════════╗');
|
|
10
|
+
console.log('║ AI + 判断力注入测试 ║');
|
|
11
|
+
console.log('╚═══════════════════════════════════════════════════╝');
|
|
12
|
+
// 1. 初始化
|
|
13
|
+
console.log('\n[1] 初始化...');
|
|
14
|
+
await initializeValueStore();
|
|
15
|
+
console.log(' ✅ 判断力存储就绪');
|
|
16
|
+
// 2. 存储一些测试判断
|
|
17
|
+
console.log('\n[2] 存储测试判断...');
|
|
18
|
+
await storeHumanJudgment({
|
|
19
|
+
decision: '代码安全性比性能更重要',
|
|
20
|
+
decision_type: 'approve',
|
|
21
|
+
reasons: ['防止被攻击', '用户数据保护'],
|
|
22
|
+
values_derived: [
|
|
23
|
+
{ category: 'safety', value: 'security-first', weight: 0.9 }
|
|
24
|
+
],
|
|
25
|
+
context: {
|
|
26
|
+
domain: 'code',
|
|
27
|
+
complexity: 'moderate',
|
|
28
|
+
stakes: 'high',
|
|
29
|
+
time_pressure: 'low'
|
|
30
|
+
},
|
|
31
|
+
outcome: { approved: true },
|
|
32
|
+
metadata: {
|
|
33
|
+
source: 'explicit',
|
|
34
|
+
confidence: 0.85,
|
|
35
|
+
revisable: true
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
console.log(' ✅ 判断已存储');
|
|
39
|
+
// 3. 查看统计
|
|
40
|
+
console.log('\n[3] 判断力统计...');
|
|
41
|
+
const stats = await getValueStats();
|
|
42
|
+
console.log(` 总判断数: ${stats.total_judgments}`);
|
|
43
|
+
console.log(` 顶级价值观: ${stats.top_values.slice(0, 3).map(v => v.value).join(', ')}`);
|
|
44
|
+
// 4. 生成价值观注入
|
|
45
|
+
console.log('\n[4] 生成价值观注入...');
|
|
46
|
+
const injection = await generateValueInjection('代码安全问题', {
|
|
47
|
+
mode: 'standard',
|
|
48
|
+
maxTokens: 400,
|
|
49
|
+
includeExamples: true,
|
|
50
|
+
includeRules: true
|
|
51
|
+
});
|
|
52
|
+
console.log(` 注入内容长度: ${injection.length} 字符`);
|
|
53
|
+
if (injection) {
|
|
54
|
+
console.log(' ✅ 价值观注入已生成');
|
|
55
|
+
}
|
|
56
|
+
// 5. 调用 AI
|
|
57
|
+
console.log('\n[5] 调用 AI...');
|
|
58
|
+
const session = await createAgentSession({ cwd: process.cwd() });
|
|
59
|
+
const prompt = injection
|
|
60
|
+
? `${injection}
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
【当前问题】
|
|
64
|
+
用户问:如何确保 API 接口的安全性?
|
|
65
|
+
|
|
66
|
+
请基于上面的价值观回复用户。`
|
|
67
|
+
: '用户问:如何确保 API 接口的安全性?请给出建议。';
|
|
68
|
+
console.log('\n[6] 发送请求到 AI...');
|
|
69
|
+
const response = await session.prompt(prompt);
|
|
70
|
+
console.log('\n═══════════════════════════════════════════════════════');
|
|
71
|
+
console.log(' AI 回复:');
|
|
72
|
+
console.log('═══════════════════════════════════════════════════════');
|
|
73
|
+
console.log(response);
|
|
74
|
+
console.log('═══════════════════════════════════════════════════════\n');
|
|
75
|
+
console.log('✅ 测试完成!');
|
|
76
|
+
}
|
|
77
|
+
main().catch(e => {
|
|
78
|
+
console.error('❌ 测试失败:', e);
|
|
79
|
+
process.exit(1);
|
|
80
|
+
});
|