@bolloon/bolloon-agent 0.4.3 → 0.4.5

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.
Files changed (212) hide show
  1. package/README.md +135 -135
  2. package/bin/bolloon-cli.cjs +183 -183
  3. package/bin/bolloon-daemon.sh +207 -0
  4. package/bin/bolloon.cjs +0 -0
  5. package/dist/agents/constraint-layer.js +19 -19
  6. package/dist/agents/judgment-protocol.js +14 -14
  7. package/dist/agents/pi-sdk-types.js +12 -12
  8. package/dist/agents/pi-sdk.js +90 -90
  9. package/dist/agents/skill-organizer.js +19 -19
  10. package/dist/agents/workflow-pivot-loop.js +2 -2
  11. package/dist/bollharness/src/scripts/deploy-guard.js +8 -8
  12. package/dist/bollharness-integration/context-router-judgment.js +4 -4
  13. package/dist/bollharness-integration/context-router.js +292 -292
  14. package/dist/bollharness-integration/gate-state-machine.js +13 -13
  15. package/dist/bollharness-integration/llm-judgment-engine.js +134 -134
  16. package/dist/bollharness-integration/skill-adapter.js +21 -21
  17. package/dist/bootstrap/chat-archiver.js +14 -14
  18. package/dist/bootstrap/context-os.js +24 -24
  19. package/dist/bootstrap/memory-compressor.js +13 -13
  20. package/dist/cli-entry.js +36 -36
  21. package/dist/constraint-runtime/reference_data/archive_surface_snapshot.json +63 -0
  22. package/dist/constraint-runtime/reference_data/commands_snapshot.json +1037 -0
  23. package/dist/constraint-runtime/reference_data/subsystems/assistant.json +8 -0
  24. package/dist/constraint-runtime/reference_data/subsystems/bootstrap.json +8 -0
  25. package/dist/constraint-runtime/reference_data/subsystems/bridge.json +32 -0
  26. package/dist/constraint-runtime/reference_data/subsystems/buddy.json +13 -0
  27. package/dist/constraint-runtime/reference_data/subsystems/cli.json +26 -0
  28. package/dist/constraint-runtime/reference_data/subsystems/components.json +32 -0
  29. package/dist/constraint-runtime/reference_data/subsystems/constants.json +28 -0
  30. package/dist/constraint-runtime/reference_data/subsystems/coordinator.json +8 -0
  31. package/dist/constraint-runtime/reference_data/subsystems/entrypoints.json +15 -0
  32. package/dist/constraint-runtime/reference_data/subsystems/hooks.json +32 -0
  33. package/dist/constraint-runtime/reference_data/subsystems/keybindings.json +21 -0
  34. package/dist/constraint-runtime/reference_data/subsystems/memdir.json +15 -0
  35. package/dist/constraint-runtime/reference_data/subsystems/migrations.json +18 -0
  36. package/dist/constraint-runtime/reference_data/subsystems/moreright.json +8 -0
  37. package/dist/constraint-runtime/reference_data/subsystems/native_ts.json +11 -0
  38. package/dist/constraint-runtime/reference_data/subsystems/outputStyles.json +8 -0
  39. package/dist/constraint-runtime/reference_data/subsystems/plugins.json +9 -0
  40. package/dist/constraint-runtime/reference_data/subsystems/remote.json +11 -0
  41. package/dist/constraint-runtime/reference_data/subsystems/schemas.json +8 -0
  42. package/dist/constraint-runtime/reference_data/subsystems/screens.json +10 -0
  43. package/dist/constraint-runtime/reference_data/subsystems/server.json +10 -0
  44. package/dist/constraint-runtime/reference_data/subsystems/services.json +32 -0
  45. package/dist/constraint-runtime/reference_data/subsystems/skills.json +27 -0
  46. package/dist/constraint-runtime/reference_data/subsystems/state.json +13 -0
  47. package/dist/constraint-runtime/reference_data/subsystems/types.json +18 -0
  48. package/dist/constraint-runtime/reference_data/subsystems/upstreamproxy.json +9 -0
  49. package/dist/constraint-runtime/reference_data/subsystems/utils.json +32 -0
  50. package/dist/constraint-runtime/reference_data/subsystems/vim.json +12 -0
  51. package/dist/constraint-runtime/reference_data/subsystems/voice.json +8 -0
  52. package/dist/constraint-runtime/reference_data/tools_snapshot.json +922 -0
  53. package/dist/context-compaction/auto-compact.js +7 -7
  54. package/dist/electron/config.js.map +1 -0
  55. package/dist/electron/dialogs.js.map +1 -0
  56. package/dist/electron/first-run.js +54 -54
  57. package/dist/electron/first-run.js.map +1 -0
  58. package/dist/electron/ipc.js.map +1 -0
  59. package/dist/electron/logger.js.map +1 -0
  60. package/dist/electron/main.js.map +1 -0
  61. package/dist/electron/menu.js.map +1 -0
  62. package/dist/electron/paths.js.map +1 -0
  63. package/dist/electron/server.js.map +1 -0
  64. package/dist/electron/tray.js.map +1 -0
  65. package/dist/electron/window.js.map +1 -0
  66. package/dist/electron-build/electron/config.js.map +1 -1
  67. package/dist/electron-build/electron/dialogs.js.map +1 -1
  68. package/dist/electron-build/electron/first-run.js +54 -54
  69. package/dist/electron-build/electron/first-run.js.map +1 -1
  70. package/dist/electron-build/electron/ipc.js.map +1 -1
  71. package/dist/electron-build/electron/logger.js.map +1 -1
  72. package/dist/electron-build/electron/menu.js.map +1 -1
  73. package/dist/electron-build/electron/paths.js.map +1 -1
  74. package/dist/electron-build/electron/server.js.map +1 -1
  75. package/dist/electron-build/electron/tray.js.map +1 -1
  76. package/dist/electron-build/electron/window.js.map +1 -1
  77. package/dist/electron-build/utils/auto-update.js.map +1 -1
  78. package/dist/electron-preload.js.map +1 -1
  79. package/dist/electron.js.map +1 -1
  80. package/dist/index.js +112 -112
  81. package/dist/llm/llm-judgment-client.js +102 -102
  82. package/dist/llm/pi-ai.js +48 -48
  83. package/dist/llm/system-prompt/layers/channel/human-async.md +41 -41
  84. package/dist/llm/system-prompt/layers/channel/local.md +14 -14
  85. package/dist/llm/system-prompt/layers/channel/p2p-agent.md +18 -18
  86. package/dist/llm/system-prompt/layers/channel/p2p-peer-sync.md +51 -51
  87. package/dist/llm/system-prompt/layers/channel/p2p-proactive.md +43 -43
  88. package/dist/llm/system-prompt/layers/channel/p2p-visitor.md +19 -19
  89. package/dist/llm/system-prompt/layers/channel/session-handoff.md +61 -61
  90. package/dist/llm/system-prompt/layers/core/artifacts_storage.md +89 -89
  91. package/dist/llm/system-prompt/layers/core/evenhandedness.md +21 -21
  92. package/dist/llm/system-prompt/layers/core/external-engagement.md +73 -73
  93. package/dist/llm/system-prompt/layers/core/hibs_reminders.md +15 -15
  94. package/dist/llm/system-prompt/layers/core/identity.md +48 -48
  95. package/dist/llm/system-prompt/layers/core/knowledge.md +17 -17
  96. package/dist/llm/system-prompt/layers/core/memory_system.md +12 -12
  97. package/dist/llm/system-prompt/layers/core/network_filesystem.md +28 -28
  98. package/dist/llm/system-prompt/layers/core/refusal.md +37 -37
  99. package/dist/llm/system-prompt/layers/core/tone.md +31 -31
  100. package/dist/llm/system-prompt/layers/core/tools.thin.md +13 -13
  101. package/dist/llm/system-prompt/layers/core/wellbeing.md +41 -41
  102. package/dist/llm/system-prompt/layers/role/architect.md +20 -20
  103. package/dist/llm/system-prompt/layers/role/expert.md +19 -19
  104. package/dist/llm/system-prompt/layers/role/implementer.md +15 -15
  105. package/dist/llm/system-prompt/layers/role/security.md +15 -15
  106. package/dist/llm/system-prompt/layers/tool/artifacts.md +72 -72
  107. package/dist/llm/system-prompt/layers/tool/bash.md +25 -25
  108. package/dist/llm/system-prompt/layers/tool/goal_handoff.md +77 -77
  109. package/dist/llm/system-prompt/layers/tool/hibs_api.md +171 -171
  110. package/dist/llm/system-prompt/layers/tool/image_search.md +70 -70
  111. package/dist/llm/system-prompt/layers/tool/manifest.md +89 -89
  112. package/dist/llm/system-prompt/layers/tool/mcp_apps.md +53 -53
  113. package/dist/llm/system-prompt/layers/tool/p2p_request.md +61 -61
  114. package/dist/llm/system-prompt/layers/tool/web_search.md +83 -83
  115. package/dist/llm/tool-manifest/ask_user_input.js +1 -1
  116. package/dist/llm/tool-manifest/bash.js +3 -3
  117. package/dist/llm/tool-manifest/create_file.js +4 -4
  118. package/dist/llm/tool-manifest/fetch_sports_data.js +3 -3
  119. package/dist/llm/tool-manifest/image_search.js +2 -2
  120. package/dist/llm/tool-manifest/index.js +59 -0
  121. package/dist/llm/tool-manifest/mcp.js +2 -2
  122. package/dist/llm/tool-manifest/message_compose.js +3 -3
  123. package/dist/llm/tool-manifest/places.js +2 -2
  124. package/dist/llm/tool-manifest/present_files.js +1 -1
  125. package/dist/llm/tool-manifest/recipe.js +2 -2
  126. package/dist/llm/tool-manifest/str_replace.js +5 -5
  127. package/dist/llm/tool-manifest/view.js +3 -3
  128. package/dist/llm/tool-manifest/weather.js +4 -4
  129. package/dist/llm/tool-manifest/web.js +4 -4
  130. package/dist/pi-ecosystem-judgment/causal-judge.js +51 -51
  131. package/dist/pi-ecosystem-judgment/distill-prompt.js +42 -42
  132. package/dist/pi-ecosystem-judgment/distillation.js +14 -14
  133. package/dist/pi-ecosystem-judgment/human-value-store.js +1 -1
  134. package/dist/pi-ecosystem-judgment/monitor-gate.js +28 -28
  135. package/dist/pi-ecosystem-judgment/value-injection.js +102 -102
  136. package/dist/pi-ecosystem-mcp/index.js +146 -5
  137. package/dist/security/context-router-tool.js +15 -15
  138. package/dist/utils/auto-update.js.map +1 -0
  139. package/dist/web/api-config.html +779 -779
  140. package/dist/web/client-hearth.js +10 -10
  141. package/dist/web/client.js.map +7 -0
  142. package/dist/web/components/wallet-viem.mjs +118 -118
  143. package/dist/web/edge-auth-client.js +120 -0
  144. package/dist/web/index.html +472 -472
  145. package/dist/web/manifest.json +20 -20
  146. package/dist/web/server.js +34 -67
  147. package/dist/web/style.css +4946 -4946
  148. package/package.json +195 -195
  149. package/scripts/build-cli.js +215 -215
  150. package/scripts/build-web.ts +130 -130
  151. package/scripts/postinstall.js +152 -152
  152. package/bin/bolloon.js +0 -157
  153. package/dist/pi-ecosystem-colony/index.js +0 -365
  154. package/dist/social/ant-colony/AdaptiveHeartbeat.js +0 -101
  155. package/dist/social/ant-colony/PheromoneEngine.js +0 -227
  156. package/dist/social/ant-colony/index.js +0 -6
  157. package/dist/social/ant-colony/types.js +0 -24
  158. package/dist/storage/trajectory.js +0 -101
  159. package/dist/test/ai-judgment-test.js +0 -80
  160. package/dist/test/bollharness-integration.test.js +0 -318
  161. package/dist/test/channel-agent-multi-dialogue.js +0 -205
  162. package/dist/test/channel-heartbeat-agent-test.js +0 -201
  163. package/dist/test/constraint-layer.test.js +0 -164
  164. package/dist/test/diap-identity-test.js +0 -172
  165. package/dist/test/diap-quick-test.js +0 -62
  166. package/dist/test/global-shared-context.test.js +0 -315
  167. package/dist/test/harness-judgment-injection.test.js +0 -246
  168. package/dist/test/harness-workflow-integrator-test.js +0 -228
  169. package/dist/test/human-value-store.test.js +0 -243
  170. package/dist/test/hybrid-integration-test.js +0 -118
  171. package/dist/test/hybrid-messenger-verify.js +0 -55
  172. package/dist/test/iroh-bistream-debug.js +0 -38
  173. package/dist/test/iroh-communication.test.js +0 -66
  174. package/dist/test/iroh-debug-test.js +0 -57
  175. package/dist/test/iroh-diap-test.js +0 -71
  176. package/dist/test/iroh-direct-connect.js +0 -55
  177. package/dist/test/iroh-e2e-fixed.js +0 -89
  178. package/dist/test/iroh-e2e-same-process.js +0 -63
  179. package/dist/test/iroh-e2e.js +0 -66
  180. package/dist/test/iroh-final-e2e.js +0 -72
  181. package/dist/test/iroh-relay-test.js +0 -37
  182. package/dist/test/iroh-simple-test.js +0 -41
  183. package/dist/test/iroh-transport-verify.js +0 -54
  184. package/dist/test/iroh-transport.test.js +0 -37
  185. package/dist/test/iroh-two-nodes.js +0 -70
  186. package/dist/test/iroh-verify.js +0 -44
  187. package/dist/test/judgment-decision.test.js +0 -219
  188. package/dist/test/llm-judgment-integration.test.js +0 -220
  189. package/dist/test/p2p-agent-complex-dialogue.js +0 -385
  190. package/dist/test/p2p-agent-dialogue.js +0 -341
  191. package/dist/test/p2p-agent-full-bidirectional.js +0 -510
  192. package/dist/test/p2p-agent-harness-flow.js +0 -437
  193. package/dist/test/p2p-agent-harness-single.js +0 -143
  194. package/dist/test/p2p-ai-dialogue-test.js +0 -318
  195. package/dist/test/p2p-cid-connect-test.js +0 -195
  196. package/dist/test/p2p-connect-receiver.js +0 -69
  197. package/dist/test/p2p-doc-transfer.js +0 -110
  198. package/dist/test/p2p-identity-page-test.js +0 -77
  199. package/dist/test/p2p-iroh-test.js +0 -171
  200. package/dist/test/p2p-minimal-test.js +0 -241
  201. package/dist/test/p2p-node-1.js +0 -148
  202. package/dist/test/p2p-node-2.js +0 -148
  203. package/dist/test/p2p-server.js +0 -281
  204. package/dist/test/p2p-two-nodes-test.js +0 -438
  205. package/dist/test/pi-sdk.test.js +0 -44
  206. package/dist/test/set-persona.js +0 -40
  207. package/dist/test/simple.test.js +0 -9
  208. package/dist/test/storage-integration.test.js +0 -150
  209. package/dist/test/subagent-manager.test.js +0 -276
  210. package/dist/test/test-gate-flow.test.js +0 -81
  211. package/dist/test/workflow-engine.test.js +0 -87
  212. package/dist/test/workflow-pivot-loop.test.js +0 -246
@@ -1,227 +0,0 @@
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();
@@ -1,6 +0,0 @@
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';
@@ -1,24 +0,0 @@
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
- };
@@ -1,101 +0,0 @@
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
- }
@@ -1,80 +0,0 @@
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
- });