@bolloon/bolloon-agent 0.1.35 → 0.1.37

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 (502) hide show
  1. package/README.md +1 -1
  2. package/dist/agents/p2p-chat-tools.js +6 -6
  3. package/dist/agents/permission-mode.js +115 -0
  4. package/dist/agents/pi-sdk.js +435 -25
  5. package/dist/agents/pre-tool-validator.js +194 -0
  6. package/dist/agents/workflow-pivot-loop.js +113 -12
  7. package/dist/bollharness-integration/context-router.js +2 -2
  8. package/dist/bollharness-integration/guard-checker.js +1 -1
  9. package/dist/bootstrap/bootstrap.js +3 -0
  10. package/dist/bootstrap/context-collector.js +17 -1
  11. package/dist/bootstrap/context-hierarchy.js +218 -0
  12. package/dist/bootstrap/lifecycle-hooks.js +86 -24
  13. package/dist/bootstrap/project-context.js +10 -3
  14. package/dist/context-compaction/auto-compact.js +144 -0
  15. package/dist/context-compaction/budget-gate.js +28 -0
  16. package/dist/context-compaction/budget-reduce.js +35 -0
  17. package/dist/context-compaction/context-collapse.js +66 -0
  18. package/dist/context-compaction/index.js +21 -0
  19. package/dist/context-compaction/microcompact.js +51 -0
  20. package/dist/context-compaction/pipeline.js +123 -0
  21. package/dist/context-compaction/snip.js +45 -0
  22. package/dist/context-compaction/token-estimator.js +35 -0
  23. package/dist/context-compaction/types.js +19 -0
  24. package/dist/heartbeat/HealthMonitor.js +3 -2
  25. package/dist/index.js +38 -2
  26. package/dist/llm/llm-judgment-client.js +32 -30
  27. package/dist/llm/pi-ai.js +103 -16
  28. package/dist/llm/system-prompt/health.js +129 -0
  29. package/dist/llm/system-prompt/registry.js +246 -0
  30. package/dist/llm/system-prompt/strip-hibsml.js +51 -0
  31. package/dist/llm/tool-manifest/ask_user_input.js +35 -0
  32. package/dist/llm/tool-manifest/bash.js +23 -0
  33. package/dist/llm/tool-manifest/create_file.js +24 -0
  34. package/dist/llm/tool-manifest/fetch_sports_data.js +26 -0
  35. package/dist/llm/tool-manifest/image_search.js +24 -0
  36. package/dist/llm/tool-manifest/index.js +69 -0
  37. package/dist/llm/tool-manifest/mcp.js +43 -0
  38. package/dist/llm/tool-manifest/message_compose.js +31 -0
  39. package/dist/llm/tool-manifest/places.js +83 -0
  40. package/dist/llm/tool-manifest/present_files.js +21 -0
  41. package/dist/llm/tool-manifest/recipe.js +40 -0
  42. package/dist/llm/tool-manifest/recommend_apps.js +23 -0
  43. package/dist/llm/tool-manifest/str_replace.js +27 -0
  44. package/dist/llm/tool-manifest/types.js +7 -0
  45. package/dist/llm/tool-manifest/view.js +24 -0
  46. package/dist/llm/tool-manifest/weather.js +27 -0
  47. package/dist/llm/tool-manifest/web.js +51 -0
  48. package/dist/network/p2p-direct.js +23 -0
  49. package/dist/network/source-intent-broadcaster.js +203 -0
  50. package/dist/network/source-intent.js +100 -0
  51. package/dist/pi-ecosystem-judgment/adaptive-scan.js +48 -0
  52. package/dist/pi-ecosystem-judgment/injection-gate.js +54 -12
  53. package/dist/pi-ecosystem-judgment/value-injection.js +8 -2
  54. package/dist/security/context-router-tool.js +1 -1
  55. package/dist/security/input-scanner.js +223 -0
  56. package/dist/web/client.js +3089 -4458
  57. package/dist/web/index.html +58 -67
  58. package/dist/web/server.js +299 -117
  59. package/dist/web/style.css +531 -249
  60. package/dist/web/ui/message-renderer.js +352 -0
  61. package/dist/web/ui/step-timeline.js +279 -0
  62. package/package.json +2 -2
  63. package/.auto-evolve-calls +0 -1
  64. package/.last-auto-evolve-baseline +0 -1
  65. package/Bolloon.md +0 -103
  66. package/dist/agents/constraint-layer.js.map +0 -1
  67. package/dist/agents/pi-sdk.js.map +0 -1
  68. package/dist/agents/workflow-engine.js.map +0 -1
  69. package/dist/bollharness/src/index.js +0 -5
  70. package/dist/bollharness/src/scripts/checks/check_adr_plan_numbering.js +0 -6
  71. package/dist/bollharness/src/scripts/checks/check_api_types.js +0 -45
  72. package/dist/bollharness/src/scripts/checks/check_artifact_link.js +0 -146
  73. package/dist/bollharness/src/scripts/checks/check_bridge_deps.js +0 -6
  74. package/dist/bollharness/src/scripts/checks/check_bugfix_binding.js +0 -6
  75. package/dist/bollharness/src/scripts/checks/check_bugfix_binding_ci.js +0 -6
  76. package/dist/bollharness/src/scripts/checks/check_doc_file_references.js +0 -6
  77. package/dist/bollharness/src/scripts/checks/check_doc_freshness.js +0 -135
  78. package/dist/bollharness/src/scripts/checks/check_doc_links.js +0 -31
  79. package/dist/bollharness/src/scripts/checks/check_file_existence_claims.js +0 -6
  80. package/dist/bollharness/src/scripts/checks/check_fragment_integrity.js +0 -34
  81. package/dist/bollharness/src/scripts/checks/check_hook_installed.js +0 -63
  82. package/dist/bollharness/src/scripts/checks/check_issue_closure.js +0 -41
  83. package/dist/bollharness/src/scripts/checks/check_mcp_parity.js +0 -6
  84. package/dist/bollharness/src/scripts/checks/check_security.js +0 -48
  85. package/dist/bollharness/src/scripts/checks/check_skill_parity.js +0 -6
  86. package/dist/bollharness/src/scripts/checks/check_versions.js +0 -6
  87. package/dist/bollharness/src/scripts/checks/finding.js +0 -13
  88. package/dist/bollharness/src/scripts/checks/next_decision_number.js +0 -20
  89. package/dist/bollharness/src/scripts/checks/regenerate_magic_docs.js +0 -6
  90. package/dist/bollharness/src/scripts/ci/detect_rebaseline_triggers.js +0 -8
  91. package/dist/bollharness/src/scripts/ci/scan_subprocess_cfg.js +0 -8
  92. package/dist/bollharness/src/scripts/ci/scan_verify_artifacts.js +0 -8
  93. package/dist/bollharness/src/scripts/ci/scan_yaml_schema.js +0 -8
  94. package/dist/bollharness/src/scripts/context_router.js +0 -67
  95. package/dist/bollharness/src/scripts/deploy-guard.js +0 -157
  96. package/dist/bollharness/src/scripts/guard-feedback.js +0 -192
  97. package/dist/bollharness/src/scripts/guard_router.js +0 -158
  98. package/dist/bollharness/src/scripts/hooks/_hook_output.js +0 -6
  99. package/dist/bollharness/src/scripts/hooks/auto-python3.js +0 -6
  100. package/dist/bollharness/src/scripts/hooks/deploy-progress-on-session-end.js +0 -6
  101. package/dist/bollharness/src/scripts/hooks/failure-analyzer.js +0 -6
  102. package/dist/bollharness/src/scripts/hooks/gate-judgment-inject.js +0 -92
  103. package/dist/bollharness/src/scripts/hooks/gate-transition-judgment.js +0 -63
  104. package/dist/bollharness/src/scripts/hooks/inbox-ack.js +0 -6
  105. package/dist/bollharness/src/scripts/hooks/inbox-inject-on-start.js +0 -6
  106. package/dist/bollharness/src/scripts/hooks/inbox-validate.js +0 -6
  107. package/dist/bollharness/src/scripts/hooks/inbox-write-ledger.js +0 -6
  108. package/dist/bollharness/src/scripts/hooks/initializer-agent.js +0 -6
  109. package/dist/bollharness/src/scripts/hooks/loop-detection.js +0 -73
  110. package/dist/bollharness/src/scripts/hooks/owner-guard.js +0 -6
  111. package/dist/bollharness/src/scripts/hooks/precompact.js +0 -6
  112. package/dist/bollharness/src/scripts/hooks/review-agent-gatekeeper.js +0 -6
  113. package/dist/bollharness/src/scripts/hooks/risk-tracker.js +0 -108
  114. package/dist/bollharness/src/scripts/hooks/sanitize-on-read.js +0 -6
  115. package/dist/bollharness/src/scripts/hooks/session-reflection.js +0 -7
  116. package/dist/bollharness/src/scripts/hooks/session-start-magic-docs.js +0 -7
  117. package/dist/bollharness/src/scripts/hooks/session-start-reset-risk.js +0 -7
  118. package/dist/bollharness/src/scripts/hooks/session-start-toolkit-reminder.js +0 -7
  119. package/dist/bollharness/src/scripts/hooks/stop-evaluator.js +0 -157
  120. package/dist/bollharness/src/scripts/hooks/tool-call-counter.js +0 -6
  121. package/dist/bollharness/src/scripts/hooks/trace-analyzer.js +0 -10
  122. package/dist/bollharness/src/scripts/install/install-trust-token.js +0 -7
  123. package/dist/bollharness/src/scripts/install/multi_project_registry.js +0 -9
  124. package/dist/bollharness/src/scripts/install/phase2_auto.js +0 -21
  125. package/dist/bollharness/src/scripts/install/pre_commit_installer.js +0 -6
  126. package/dist/bollharness/src/scripts/install/tier_selector.js +0 -7
  127. package/dist/bollharness/src/scripts/install/transcript_miner.js +0 -7
  128. package/dist/bollharness/src/scripts/lib/claim_patterns.js +0 -10
  129. package/dist/bollharness/src/scripts/lib/sanitize_patterns.js +0 -12
  130. package/dist/bollharness/src/scripts/sanitize.js +0 -6
  131. package/dist/bollharness-integration/context-router-judgment.js.map +0 -1
  132. package/dist/bollharness-integration/context-router.js.map +0 -1
  133. package/dist/bollharness-integration/gate-state-machine.js.map +0 -1
  134. package/dist/bollharness-integration/gate-transition-hooks.js.map +0 -1
  135. package/dist/bollharness-integration/guard-checker.js.map +0 -1
  136. package/dist/bollharness-integration/index.js.map +0 -1
  137. package/dist/bollharness-integration/integration.js.map +0 -1
  138. package/dist/bollharness-integration/llm/pi-ai.d.ts +0 -60
  139. package/dist/bollharness-integration/pi-ecosystem-colony/index.d.ts +0 -153
  140. package/dist/bollharness-integration/pi-ecosystem-goals/index.d.ts +0 -136
  141. package/dist/bollharness-integration/pi-ecosystem-judgment/decision.d.ts +0 -117
  142. package/dist/bollharness-integration/pi-ecosystem-judgment/distillation.d.ts +0 -78
  143. package/dist/bollharness-integration/pi-ecosystem-judgment/index.d.ts +0 -139
  144. package/dist/bollharness-integration/pi-ecosystem-mcp/index.d.ts +0 -127
  145. package/dist/bollharness-integration/pi-ecosystem-subagents/index.d.ts +0 -95
  146. package/dist/bollharness-integration/skill-adapter.js.map +0 -1
  147. package/dist/constraint-runtime/src/_archive_helper.js +0 -9
  148. package/dist/constraint-runtime/src/agent/coordinator.js +0 -48
  149. package/dist/constraint-runtime/src/agent/index.js +0 -1
  150. package/dist/constraint-runtime/src/assistant/index.js +0 -12
  151. package/dist/constraint-runtime/src/bootstrap/index.js +0 -12
  152. package/dist/constraint-runtime/src/bootstrap_graph.js +0 -13
  153. package/dist/constraint-runtime/src/bridge/index.js +0 -12
  154. package/dist/constraint-runtime/src/buddy/index.js +0 -12
  155. package/dist/constraint-runtime/src/cli/index.js +0 -12
  156. package/dist/constraint-runtime/src/command_graph.js +0 -10
  157. package/dist/constraint-runtime/src/commands.js +0 -60
  158. package/dist/constraint-runtime/src/components/index.js +0 -12
  159. package/dist/constraint-runtime/src/constants/index.js +0 -12
  160. package/dist/constraint-runtime/src/constraint/budget.js +0 -22
  161. package/dist/constraint-runtime/src/constraint/budget.js.map +0 -1
  162. package/dist/constraint-runtime/src/constraint/index.js +0 -2
  163. package/dist/constraint-runtime/src/constraint/permission.js +0 -20
  164. package/dist/constraint-runtime/src/constraint/permission.js.map +0 -1
  165. package/dist/constraint-runtime/src/context.js +0 -30
  166. package/dist/constraint-runtime/src/coordinator/index.js +0 -12
  167. package/dist/constraint-runtime/src/cost_hook.js +0 -4
  168. package/dist/constraint-runtime/src/cost_tracker.js +0 -8
  169. package/dist/constraint-runtime/src/deferred_init.js +0 -10
  170. package/dist/constraint-runtime/src/direct_modes.js +0 -6
  171. package/dist/constraint-runtime/src/dynamic-tool-loader.js +0 -85
  172. package/dist/constraint-runtime/src/entrypoints/index.js +0 -12
  173. package/dist/constraint-runtime/src/execution_registry.js +0 -44
  174. package/dist/constraint-runtime/src/history.js +0 -9
  175. package/dist/constraint-runtime/src/hooks/index.js +0 -12
  176. package/dist/constraint-runtime/src/index.js +0 -26
  177. package/dist/constraint-runtime/src/ink.js +0 -4
  178. package/dist/constraint-runtime/src/keybindings/index.js +0 -12
  179. package/dist/constraint-runtime/src/memdir/index.js +0 -12
  180. package/dist/constraint-runtime/src/migrations/index.js +0 -12
  181. package/dist/constraint-runtime/src/models.js +0 -1
  182. package/dist/constraint-runtime/src/models.js.map +0 -1
  183. package/dist/constraint-runtime/src/moreright/index.js +0 -12
  184. package/dist/constraint-runtime/src/native_ts/index.js +0 -12
  185. package/dist/constraint-runtime/src/output_styles/index.js +0 -12
  186. package/dist/constraint-runtime/src/parity_audit.js +0 -12
  187. package/dist/constraint-runtime/src/plugins/index.js +0 -12
  188. package/dist/constraint-runtime/src/port_manifest.js +0 -11
  189. package/dist/constraint-runtime/src/prefetch.js +0 -9
  190. package/dist/constraint-runtime/src/query.js +0 -1
  191. package/dist/constraint-runtime/src/remote/index.js +0 -12
  192. package/dist/constraint-runtime/src/remote_runtime.js +0 -9
  193. package/dist/constraint-runtime/src/runtime/index.js +0 -1
  194. package/dist/constraint-runtime/src/runtime/session.js +0 -35
  195. package/dist/constraint-runtime/src/schemas/index.js +0 -12
  196. package/dist/constraint-runtime/src/screens/index.js +0 -12
  197. package/dist/constraint-runtime/src/server/index.js +0 -12
  198. package/dist/constraint-runtime/src/services/index.js +0 -12
  199. package/dist/constraint-runtime/src/session_store.js +0 -22
  200. package/dist/constraint-runtime/src/setup.js +0 -30
  201. package/dist/constraint-runtime/src/skills/index.js +0 -1
  202. package/dist/constraint-runtime/src/skills/skill-registry.js +0 -28
  203. package/dist/constraint-runtime/src/state/index.js +0 -12
  204. package/dist/constraint-runtime/src/system_init.js +0 -20
  205. package/dist/constraint-runtime/src/thinking/engine.js +0 -42
  206. package/dist/constraint-runtime/src/thinking/index.js +0 -1
  207. package/dist/constraint-runtime/src/tool_pool.js +0 -8
  208. package/dist/constraint-runtime/src/tools/OpenCLI/execAdapter.js +0 -7
  209. package/dist/constraint-runtime/src/tools/OpenCLI/listAdapters.js +0 -7
  210. package/dist/constraint-runtime/src/tools/OpenCLI/runCommand.js +0 -7
  211. package/dist/constraint-runtime/src/tools/PolymarketSDK/cancelOrder.js +0 -6
  212. package/dist/constraint-runtime/src/tools/PolymarketSDK/createOrder.js +0 -6
  213. package/dist/constraint-runtime/src/tools/PolymarketSDK/getMarket.js +0 -5
  214. package/dist/constraint-runtime/src/tools/PolymarketSDK/getOrders.js +0 -6
  215. package/dist/constraint-runtime/src/tools/PolymarketSDK/listMarkets.js +0 -4
  216. package/dist/constraint-runtime/src/tools/SafeSDK/confirmTransaction.js +0 -6
  217. package/dist/constraint-runtime/src/tools/SafeSDK/createTransaction.js +0 -8
  218. package/dist/constraint-runtime/src/tools/SafeSDK/deploySafe.js +0 -6
  219. package/dist/constraint-runtime/src/tools/SafeSDK/executeTransaction.js +0 -6
  220. package/dist/constraint-runtime/src/tools/SafeSDK/getBalance.js +0 -6
  221. package/dist/constraint-runtime/src/tools/SafeSDK/getPendingTransactions.js +0 -6
  222. package/dist/constraint-runtime/src/tools/SafeSDK/proposeTransaction.js +0 -6
  223. package/dist/constraint-runtime/src/tools/WalletTools/autoPay.js +0 -29
  224. package/dist/constraint-runtime/src/tools/WalletTools/createWallet.js +0 -10
  225. package/dist/constraint-runtime/src/tools/WalletTools/getBalance.js +0 -13
  226. package/dist/constraint-runtime/src/tools/WalletTools/importWallet.js +0 -22
  227. package/dist/constraint-runtime/src/tools/WalletTools/sendTransaction.js +0 -25
  228. package/dist/constraint-runtime/src/tools/WalletTools/signMessage.js +0 -10
  229. package/dist/constraint-runtime/src/tools/WalletTools/transferToken.js +0 -25
  230. package/dist/constraint-runtime/src/tools.js +0 -80
  231. package/dist/constraint-runtime/src/transcript.js +0 -19
  232. package/dist/constraint-runtime/src/types/index.js +0 -12
  233. package/dist/constraint-runtime/src/upstream_proxy/index.js +0 -12
  234. package/dist/constraint-runtime/src/utils/index.js +0 -12
  235. package/dist/constraint-runtime/src/vim/index.js +0 -12
  236. package/dist/constraint-runtime/src/voice/index.js +0 -12
  237. package/dist/constraints/index.js.map +0 -1
  238. package/dist/documents/reader.js.map +0 -1
  239. package/dist/llm/config-store.js.map +0 -1
  240. package/dist/llm/pi-ai.js.map +0 -1
  241. package/dist/network/agent-network.js.map +0 -1
  242. package/dist/network/iroh-integration.js.map +0 -1
  243. package/dist/network/iroh-transport.js.map +0 -1
  244. package/dist/network/p2p.js.map +0 -1
  245. package/dist/network/storage/adapters/json-adapter.js.map +0 -1
  246. package/dist/pi-ecosystem-colony/index.js.map +0 -1
  247. package/dist/pi-ecosystem-goals/index.js.map +0 -1
  248. package/dist/pi-ecosystem-judgment/decision.js.map +0 -1
  249. package/dist/pi-ecosystem-judgment/distillation.js.map +0 -1
  250. package/dist/pi-ecosystem-judgment/human-value-store.js.map +0 -1
  251. package/dist/pi-ecosystem-judgment/index.js.map +0 -1
  252. package/dist/pi-ecosystem-judgment/value-injection.js.map +0 -1
  253. package/dist/pi-ecosystem-mcp/index.js.map +0 -1
  254. package/dist/pi-ecosystem-subagents/index.js.map +0 -1
  255. package/dist/social/ant-colony/AdaptiveHeartbeat.js.map +0 -1
  256. package/dist/social/ant-colony/PheromoneEngine.js.map +0 -1
  257. package/dist/social/ant-colony/types.js.map +0 -1
  258. package/dist/social/channels/ChannelManager.js.map +0 -1
  259. package/dist/social/channels/DiapChannelBridge.js.map +0 -1
  260. package/dist/social/channels/InterestMatcher.js.map +0 -1
  261. package/dist/social/channels/types.js.map +0 -1
  262. package/dist/social/global-shared-context.js.map +0 -1
  263. package/dist/social/heartbeat.js.map +0 -1
  264. package/lefthook.yml +0 -29
  265. package/scripts/auto-evolve-loop.ts +0 -376
  266. package/scripts/auto-evolve-oneshot.sh +0 -155
  267. package/scripts/auto-evolve-snapshot.sh +0 -136
  268. package/scripts/build-cli.js +0 -216
  269. package/scripts/build-web.ts +0 -82
  270. package/scripts/detect-schema-changes.sh +0 -48
  271. package/scripts/diff-reviewer.ts +0 -159
  272. package/scripts/postinstall.js +0 -153
  273. package/scripts/weekly-report.ts +0 -364
  274. package/src/agents/agent-manifest-protocol.ts +0 -117
  275. package/src/agents/constraint-layer.ts +0 -309
  276. package/src/agents/iroh-secret.ts +0 -32
  277. package/src/agents/p2p-chat-tools.ts +0 -383
  278. package/src/agents/p2p-document-tools.ts +0 -347
  279. package/src/agents/pi-sdk.ts +0 -2462
  280. package/src/agents/protocol.ts +0 -398
  281. package/src/agents/shell-guard.ts +0 -417
  282. package/src/agents/shell-tool.ts +0 -103
  283. package/src/agents/skill-loader.ts +0 -202
  284. package/src/agents/subagent-manager.ts +0 -553
  285. package/src/agents/workflow-engine.ts +0 -332
  286. package/src/agents/workflow-pivot-loop.ts +0 -675
  287. package/src/bollharness/.sanitize-report.json +0 -13
  288. package/src/bollharness/CLAUDE.md +0 -73
  289. package/src/bollharness/LICENSE +0 -21
  290. package/src/bollharness/README.md +0 -143
  291. package/src/bollharness/README.zh-CN.md +0 -131
  292. package/src/bollharness/package.json +0 -20
  293. package/src/bollharness/reference/SOURCE-COMMIT.txt +0 -3
  294. package/src/bollharness/reference/boll-reference/scripts/hooks/.sanitize-report.json +0 -12
  295. package/src/bollharness/reference/boll-reference/scripts/hooks/find-boll-root.sh +0 -27
  296. package/src/bollharness/reference/boll-reference/scripts/hooks/precompact.sh +0 -57
  297. package/src/bollharness/reference/boll-reference/scripts/hooks/stop-evaluator.md +0 -57
  298. package/src/bollharness/schemas/metrics-jsonl-allowlist.json +0 -67
  299. package/src/bollharness/scripts/checks/next_decision_number.sh +0 -48
  300. package/src/bollharness/scripts/ci/count-components.sh +0 -65
  301. package/src/bollharness/scripts/context-fragments/artifact-linkage.md +0 -14
  302. package/src/bollharness/scripts/context-fragments/auth-consumers.md +0 -17
  303. package/src/bollharness/scripts/context-fragments/bridge-constitution.md +0 -13
  304. package/src/bollharness/scripts/context-fragments/catalyst-distributed.md +0 -18
  305. package/src/bollharness/scripts/context-fragments/closure-checklist.md +0 -13
  306. package/src/bollharness/scripts/context-fragments/contract-consumers.md +0 -15
  307. package/src/bollharness/scripts/context-fragments/db-shared-structures.md +0 -15
  308. package/src/bollharness/scripts/context-fragments/fixed-three-layers.md +0 -19
  309. package/src/bollharness/scripts/context-fragments/general-dev-principles.md +0 -11
  310. package/src/bollharness/scripts/context-fragments/issue-first.md +0 -8
  311. package/src/bollharness/scripts/context-fragments/mcp-parity.md +0 -16
  312. package/src/bollharness/scripts/context-fragments/pi-agent-operations.md +0 -108
  313. package/src/bollharness/scripts/context-fragments/protocol-consumers.md +0 -15
  314. package/src/bollharness/scripts/context-fragments/run-events-consumers.md +0 -15
  315. package/src/bollharness/scripts/context-fragments/scene-fidelity.md +0 -13
  316. package/src/bollharness/scripts/context-fragments/truth-source-hierarchy.md +0 -15
  317. package/src/bollharness/scripts/context-fragments/two-language.md +0 -15
  318. package/src/bollharness/scripts/context-fragments/version-sources.md +0 -14
  319. package/src/bollharness/scripts/hooks/find-project-root.sh +0 -47
  320. package/src/bollharness/scripts/hooks/inbox-poll.sh +0 -78
  321. package/src/bollharness/scripts/hooks/precompact.sh +0 -56
  322. package/src/bollharness/scripts/hooks/stop-evaluator.md +0 -83
  323. package/src/bollharness/scripts/sync-from-upstream.sh +0 -281
  324. package/src/bollharness/src/index.ts +0 -5
  325. package/src/bollharness/src/scripts/checks/check_adr_plan_numbering.ts +0 -11
  326. package/src/bollharness/src/scripts/checks/check_api_types.ts +0 -52
  327. package/src/bollharness/src/scripts/checks/check_artifact_link.ts +0 -156
  328. package/src/bollharness/src/scripts/checks/check_bridge_deps.ts +0 -11
  329. package/src/bollharness/src/scripts/checks/check_bugfix_binding.ts +0 -11
  330. package/src/bollharness/src/scripts/checks/check_bugfix_binding_ci.ts +0 -11
  331. package/src/bollharness/src/scripts/checks/check_doc_file_references.ts +0 -11
  332. package/src/bollharness/src/scripts/checks/check_doc_freshness.ts +0 -141
  333. package/src/bollharness/src/scripts/checks/check_doc_links.ts +0 -36
  334. package/src/bollharness/src/scripts/checks/check_file_existence_claims.ts +0 -11
  335. package/src/bollharness/src/scripts/checks/check_fragment_integrity.ts +0 -40
  336. package/src/bollharness/src/scripts/checks/check_hook_installed.ts +0 -70
  337. package/src/bollharness/src/scripts/checks/check_issue_closure.ts +0 -51
  338. package/src/bollharness/src/scripts/checks/check_mcp_parity.ts +0 -11
  339. package/src/bollharness/src/scripts/checks/check_security.ts +0 -54
  340. package/src/bollharness/src/scripts/checks/check_skill_parity.ts +0 -11
  341. package/src/bollharness/src/scripts/checks/check_versions.ts +0 -11
  342. package/src/bollharness/src/scripts/checks/finding.ts +0 -35
  343. package/src/bollharness/src/scripts/checks/next_decision_number.ts +0 -24
  344. package/src/bollharness/src/scripts/checks/regenerate_magic_docs.ts +0 -11
  345. package/src/bollharness/src/scripts/ci/detect_rebaseline_triggers.ts +0 -14
  346. package/src/bollharness/src/scripts/ci/scan_subprocess_cfg.ts +0 -14
  347. package/src/bollharness/src/scripts/ci/scan_verify_artifacts.ts +0 -14
  348. package/src/bollharness/src/scripts/ci/scan_yaml_schema.ts +0 -14
  349. package/src/bollharness/src/scripts/context_router.ts +0 -76
  350. package/src/bollharness/src/scripts/deploy-guard.ts +0 -182
  351. package/src/bollharness/src/scripts/guard-feedback.ts +0 -215
  352. package/src/bollharness/src/scripts/guard_router.ts +0 -194
  353. package/src/bollharness/src/scripts/hooks/_hook_output.js +0 -3
  354. package/src/bollharness/src/scripts/hooks/_hook_output.ts +0 -11
  355. package/src/bollharness/src/scripts/hooks/auto-python3.ts +0 -10
  356. package/src/bollharness/src/scripts/hooks/deploy-progress-on-session-end.ts +0 -10
  357. package/src/bollharness/src/scripts/hooks/failure-analyzer.ts +0 -10
  358. package/src/bollharness/src/scripts/hooks/gate-judgment-inject.ts +0 -111
  359. package/src/bollharness/src/scripts/hooks/gate-transition-judgment.ts +0 -74
  360. package/src/bollharness/src/scripts/hooks/inbox-ack.ts +0 -10
  361. package/src/bollharness/src/scripts/hooks/inbox-inject-on-start.ts +0 -10
  362. package/src/bollharness/src/scripts/hooks/inbox-validate.ts +0 -10
  363. package/src/bollharness/src/scripts/hooks/inbox-write-ledger.ts +0 -10
  364. package/src/bollharness/src/scripts/hooks/initializer-agent.ts +0 -10
  365. package/src/bollharness/src/scripts/hooks/loop-detection.ts +0 -83
  366. package/src/bollharness/src/scripts/hooks/owner-guard.ts +0 -10
  367. package/src/bollharness/src/scripts/hooks/precompact.ts +0 -10
  368. package/src/bollharness/src/scripts/hooks/review-agent-gatekeeper.ts +0 -10
  369. package/src/bollharness/src/scripts/hooks/risk-tracker.ts +0 -121
  370. package/src/bollharness/src/scripts/hooks/sanitize-on-read.ts +0 -10
  371. package/src/bollharness/src/scripts/hooks/session-reflection.ts +0 -12
  372. package/src/bollharness/src/scripts/hooks/session-start-magic-docs.ts +0 -12
  373. package/src/bollharness/src/scripts/hooks/session-start-reset-risk.ts +0 -12
  374. package/src/bollharness/src/scripts/hooks/session-start-toolkit-reminder.ts +0 -12
  375. package/src/bollharness/src/scripts/hooks/stop-evaluator.ts +0 -164
  376. package/src/bollharness/src/scripts/hooks/tool-call-counter.ts +0 -10
  377. package/src/bollharness/src/scripts/hooks/trace-analyzer.ts +0 -14
  378. package/src/bollharness/src/scripts/install/install-trust-token.ts +0 -13
  379. package/src/bollharness/src/scripts/install/multi_project_registry.ts +0 -13
  380. package/src/bollharness/src/scripts/install/phase2_auto.ts +0 -28
  381. package/src/bollharness/src/scripts/install/pre_commit_installer.ts +0 -10
  382. package/src/bollharness/src/scripts/install/tier_selector.ts +0 -10
  383. package/src/bollharness/src/scripts/install/transcript_miner.ts +0 -13
  384. package/src/bollharness/src/scripts/lib/claim_patterns.ts +0 -11
  385. package/src/bollharness/src/scripts/lib/sanitize_patterns.ts +0 -13
  386. package/src/bollharness/src/scripts/sanitize.ts +0 -9
  387. package/src/bollharness/templates/persona/default.json +0 -19
  388. package/src/bollharness/templates/scaffold/.gitignore.append +0 -16
  389. package/src/bollharness/templates/scaffold/CLAUDE.md +0 -89
  390. package/src/bollharness-integration/channel-judgment-engine.ts +0 -634
  391. package/src/bollharness-integration/context-chain-router.ts +0 -474
  392. package/src/bollharness-integration/context-router-judgment.ts +0 -339
  393. package/src/bollharness-integration/context-router.ts +0 -583
  394. package/src/bollharness-integration/gate-state-machine.ts +0 -444
  395. package/src/bollharness-integration/gate-transition-hooks.ts +0 -137
  396. package/src/bollharness-integration/guard-checker.ts +0 -451
  397. package/src/bollharness-integration/index.ts +0 -195
  398. package/src/bollharness-integration/integration.ts +0 -538
  399. package/src/bollharness-integration/judgment-prompts.yaml +0 -535
  400. package/src/bollharness-integration/llm-judgment-engine.ts +0 -712
  401. package/src/bollharness-integration/skill-adapter.ts +0 -646
  402. package/src/bootstrap/bootstrap.ts +0 -132
  403. package/src/bootstrap/context-collector.ts +0 -342
  404. package/src/bootstrap/lifecycle-hooks.ts +0 -176
  405. package/src/bootstrap/project-context.ts +0 -163
  406. package/src/cli/interface.ts +0 -211
  407. package/src/cli-entry.ts +0 -304
  408. package/src/constraints/index.ts +0 -6
  409. package/src/documents/reader.ts +0 -85
  410. package/src/documents/store.ts +0 -252
  411. package/src/electron-preload.ts +0 -25
  412. package/src/electron.ts +0 -200
  413. package/src/heartbeat/DaemonManager.ts +0 -283
  414. package/src/heartbeat/HealthMonitor.ts +0 -316
  415. package/src/heartbeat/StartupVerifier.ts +0 -223
  416. package/src/heartbeat/Watchdog.ts +0 -208
  417. package/src/heartbeat/index.ts +0 -109
  418. package/src/heartbeat/self-improve-bus.ts +0 -110
  419. package/src/heartbeat/types.ts +0 -82
  420. package/src/index.ts +0 -1690
  421. package/src/llm/audio-config-store.ts +0 -246
  422. package/src/llm/config-store.ts +0 -400
  423. package/src/llm/llm-judgment-client.ts +0 -470
  424. package/src/llm/pi-ai.ts +0 -558
  425. package/src/llm/video-config-store.ts +0 -257
  426. package/src/network/agent-network.ts +0 -800
  427. package/src/network/hybrid-messenger.ts +0 -199
  428. package/src/network/iroh-bootstrap.ts +0 -57
  429. package/src/network/iroh-discovery.ts +0 -208
  430. package/src/network/iroh-integration.ts +0 -158
  431. package/src/network/iroh-transport.ts +0 -637
  432. package/src/network/known-peers.ts +0 -102
  433. package/src/network/p2p-direct.ts +0 -240
  434. package/src/network/p2p-secret.ts +0 -153
  435. package/src/network/p2p.ts +0 -964
  436. package/src/network/storage/adapters/json-adapter.ts +0 -454
  437. package/src/network/storage/index.ts +0 -203
  438. package/src/network/storage/types.ts +0 -166
  439. package/src/security/builtin-guards.ts +0 -162
  440. package/src/security/context-router-tool.ts +0 -122
  441. package/src/security/react-harness.ts +0 -177
  442. package/src/security/tool-gate.ts +0 -294
  443. package/src/social/ant-colony/index.js +0 -19
  444. package/src/social/channels/ChannelManager.ts +0 -485
  445. package/src/social/channels/DiapChannelBridge.ts +0 -501
  446. package/src/social/channels/InterestMatcher.ts +0 -189
  447. package/src/social/channels/agent-workflow-config.json +0 -214
  448. package/src/social/channels/agent-workflow-config.yaml +0 -334
  449. package/src/social/channels/channel-agent-session.ts +0 -407
  450. package/src/social/channels/channel-heartbeat-agent.ts +0 -622
  451. package/src/social/channels/diap-doc-parser.ts +0 -282
  452. package/src/social/channels/harness-workflow-integrator.ts +0 -594
  453. package/src/social/channels/index.ts +0 -22
  454. package/src/social/channels/types.ts +0 -115
  455. package/src/social/global-shared-context.ts +0 -506
  456. package/src/social/heartbeat.ts +0 -1057
  457. package/src/social/persona/enhanced-persona.ts +0 -359
  458. package/src/types.d.ts +0 -12
  459. package/src/utils/auto-evolve-policy.ts +0 -138
  460. package/src/utils/auto-update.ts +0 -482
  461. package/src/utils/clamp.ts +0 -5
  462. package/src/web/agent-delegate-server.ts +0 -148
  463. package/src/web/api-config.html +0 -520
  464. package/src/web/client.js +0 -4898
  465. package/src/web/components/p2p/P2PModal.tsx +0 -416
  466. package/src/web/components/p2p/index.ts +0 -566
  467. package/src/web/components/p2p/index.tsx +0 -297
  468. package/src/web/components/p2p/p2p-connection.ts +0 -338
  469. package/src/web/components/p2p/p2p-identity.ts +0 -92
  470. package/src/web/components/p2p/p2p-manager.ts +0 -147
  471. package/src/web/components/p2p/p2p-messages.ts +0 -219
  472. package/src/web/components/p2p/p2p-modal.ts +0 -685
  473. package/src/web/components/p2p/p2p-store-memory.ts +0 -162
  474. package/src/web/components/p2p/p2p-tools.ts +0 -315
  475. package/src/web/components/p2p/types.ts +0 -170
  476. package/src/web/components/wallet-viem.mjs +0 -118
  477. package/src/web/design.md +0 -99
  478. package/src/web/icons/apple-touch-icon.png +0 -0
  479. package/src/web/icons/favicon-16x16.png +0 -0
  480. package/src/web/icons/favicon-192x192.png +0 -0
  481. package/src/web/icons/favicon-32x32.png +0 -0
  482. package/src/web/icons/favicon-48x48.png +0 -0
  483. package/src/web/icons/favicon-512x512.png +0 -0
  484. package/src/web/icons/favicon.icns +0 -0
  485. package/src/web/icons/favicon.ico +0 -0
  486. package/src/web/icons/icon.png +0 -0
  487. package/src/web/icons/image.png +0 -0
  488. package/src/web/index.html +0 -382
  489. package/src/web/iroh-delegate-transport.ts +0 -139
  490. package/src/web/manifest.json +0 -21
  491. package/src/web/server.ts +0 -5571
  492. package/src/web/style.css +0 -4455
  493. package/staging/auto-evolve/clean-001/.review-verdict +0 -9
  494. package/staging/auto-evolve/clean-001/clean-001.patch +0 -14
  495. package/staging/auto-evolve/e2e-001/.patch-id +0 -1
  496. package/staging/auto-evolve/e2e-001/.review-verdict +0 -12
  497. package/staging/auto-evolve/e2e-001/e2e-001.patch +0 -11
  498. package/staging/auto-evolve/test-bad/.review-verdict +0 -12
  499. package/staging/auto-evolve/test-bad/test-bad.patch +0 -11
  500. package/tsconfig.cli.json +0 -16
  501. package/tsconfig.electron.json +0 -20
  502. package/tsconfig.json +0 -18
package/src/index.ts DELETED
@@ -1,1690 +0,0 @@
1
- import {
2
- HyperswarmCommunicator,
3
- createHyperswarmCommunicator,
4
- createTopic,
5
- KeyManager,
6
- AgentAuthManager,
7
- AgentVerificationManager,
8
- createVerificationManager,
9
- type P2PMessage,
10
- type P2PConnection,
11
- } from '@diap/sdk';
12
- import { irohTransport } from './network/iroh-transport.js';
13
- import { HybridMessenger } from './network/hybrid-messenger.js';
14
- import * as ed25519 from '@noble/ed25519';
15
- import { sha512 } from '@noble/hashes/sha2.js';
16
- import * as fs from 'fs/promises';
17
- import * as path from 'path';
18
- import { documentReader } from './documents/reader.js';
19
- import { initMinimax } from './constraints/index.js';
20
- import { createAgentSession } from './agents/pi-sdk.js';
21
- import { createSubAgentManager } from './agents/subagent-manager.js';
22
- import { getGlobalSharedContext } from './social/global-shared-context.js';
23
- import { BollharnessIntegration, createBollharnessIntegration } from './bollharness-integration/index.js';
24
- import * as readline from 'readline';
25
- // 启动时自动检查更新已禁用 (改用 --update-check / --update-now 显式触发)
26
-
27
-
28
- const RESET = '\x1b[0m';
29
- const BOLD = '\x1b[1m';
30
- const DIM = '\x1b[2m';
31
- const CYAN = '\x1b[36m';
32
- const GREEN = '\x1b[32m';
33
- const YELLOW = '\x1b[33m';
34
- const BLUE = '\x1b[34m';
35
- const MAGENTA = '\x1b[35m';
36
- const WHITE = '\x1b[37m';
37
- const GRAY = '\x1b[90m';
38
- const BG_WHITE = '\x1b[47m';
39
- const BG_BLUE = '\x1b[44m';
40
- const BLACK = '\x1b[30m';
41
- const MOVE_UP = '\x1b[A';
42
- const CLEAR_LINE = '\x1b[2K';
43
- const HIDE_CURSOR = '\x1b[?25l';
44
- const SHOW_CURSOR = '\x1b[?25h';
45
-
46
- const s = {
47
- banner: () => console.log(`\n${CYAN}${BOLD}
48
- ╔═══════════════════════════════════════════╗
49
- ║ ${WHITE}🤖 Bolloon ${CYAN} ║
50
- ║ ${WHITE}P2P AI Document Processor${CYAN} ║
51
- ╚═══════════════════════════════════════════╝${RESET}\n`),
52
-
53
- step: (num: number, total: number, text: string, status?: 'ok' | 'loading' | 'warn' | 'error') => {
54
- const check = status === 'ok' ? `${GREEN}✓` :
55
- status === 'loading' ? `${YELLOW}⟳` :
56
- status === 'warn' ? `${YELLOW}⚠` :
57
- status === 'error' ? `${MAGENTA}✗` :
58
- `${CYAN}●`;
59
- console.log(` ${check} ${WHITE}[${num}/${total}]${GRAY} ${text}${RESET}`);
60
- },
61
-
62
- success: (text: string) => console.log(` ${GREEN}✓${RESET} ${text}`),
63
- warn: (text: string) => console.log(` ${YELLOW}⚠${RESET} ${text}`),
64
- error: (text: string) => console.log(` ${MAGENTA}✗${RESET} ${text}`),
65
- info: (text: string) => console.log(` ${CYAN}●${RESET} ${text}`),
66
-
67
- section: (title: string) => {
68
- console.log(`\n${BLUE}━━━ ${WHITE}${BOLD}${title}${RESET} ${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}`);
69
- },
70
-
71
- divider: () => console.log(`\n${GRAY}${'─'.repeat(50)}${RESET}\n`),
72
-
73
- prompt: (text: string) => console.log(`\n${CYAN}❯ ${WHITE}${text}${RESET}`),
74
-
75
- response: (label: string, content: string) => {
76
- console.log(`\n${GREEN}${label}${RESET}\n${content}\n`);
77
- },
78
-
79
- agentCard: (agent: { name: string; id: string; status: string; capabilities: string[]; did?: string }) => {
80
- const statusColor = agent.status === 'active' ? GREEN :
81
- agent.status === 'idle' ? YELLOW :
82
- agent.status === 'busy' ? MAGENTA : GRAY;
83
- console.log(` ${WHITE}${BOLD}${agent.name}${RESET}`);
84
- console.log(` ${GRAY}ID:${RESET} ${agent.id}`);
85
- console.log(` ${GRAY}状态:${RESET} ${statusColor}${agent.status}${RESET}`);
86
- console.log(` ${GRAY}能力:${RESET} ${agent.capabilities.join(', ')}`);
87
- if (agent.did) console.log(` ${GRAY}DID:${RESET} ${agent.did}`);
88
- console.log();
89
- },
90
-
91
- Thinking: () => {
92
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
93
- let i = 0;
94
- return setInterval(() => {
95
- process.stdout.write(`\r ${YELLOW}${frames[i++ % frames.length]} 思考中...${RESET} `);
96
- }, 80);
97
- },
98
-
99
- clearThinking: (interval: ReturnType<typeof setInterval>) => {
100
- clearInterval(interval);
101
- process.stdout.write('\r' + ' '.repeat(30) + '\r');
102
- },
103
-
104
- dialog: async (title: string, promptText: string): Promise<string> => {
105
- return new Promise((resolve) => {
106
- const rl = readline.createInterface({
107
- input: process.stdin,
108
- output: process.stdout
109
- });
110
-
111
- rl.question(`${CYAN}❯ ${RESET}`, (input) => {
112
- rl.close();
113
- resolve(input.trim());
114
- });
115
- });
116
- }
117
- };
118
-
119
- // @ts-ignore - noble/ed25519 v3 requires sha512 to be set
120
- (ed25519.hashes as any).sha512 = sha512;
121
-
122
- // ---------------------------------------------------------------------------
123
- // Message envelope
124
- // Sender wraps: DID:<hex_did>|{"id":"...","type":"summarize|improve","documentPath":"...","requirements":"..."}
125
- // So receiver can verify identity before dispatching
126
- // ---------------------------------------------------------------------------
127
-
128
- type TaskType = 'summarize' | 'improve';
129
-
130
- interface RpcTask {
131
- id: string;
132
- type: TaskType;
133
- documentPath?: string;
134
- requirements?: string;
135
- from: string; // DID of sender, extracted from message prefix
136
- }
137
-
138
- // ---------------------------------------------------------------------------
139
- // Harness loop ─ poll-free event-driven (Hyperswarm DHT 自动推送)
140
- // ---------------------------------------------------------------------------
141
-
142
- /** 原始 Hyperswarm stream 缓存; HyperswarmCommunicator.sendToConnection 只打日志不写流 */
143
- const rawStreams = new Map<string, any>();
144
-
145
- function sendRawMsg(conn: P2PConnection, text: string): void {
146
- const raw = rawStreams.get(conn as any);
147
- if (raw && raw.writable) raw.write(Buffer.from(text));
148
- }
149
-
150
- // ---------------------------------------------------------------------------
151
- // DIAP 身份初始化 ─ KeyManager → DID → DID Builder → IPFS publish
152
- // ---------------------------------------------------------------------------
153
-
154
- function getUserName(): string {
155
- const home = process.env.HOME || process.env.USERPROFILE || '';
156
- const match = home.match(/\/Users\/(\w+)/);
157
- if (match) return match[1];
158
- const user = process.env.USERNAME || process.env.USER || 'user';
159
- return user.toLowerCase().replace(/[^a-z0-9]/g, '');
160
- }
161
-
162
- async function bootstrapIdentity(): Promise<{ keypair: import('@diap/sdk').KeyPair; did: string; name: string }> {
163
- s.step(1, 5, '生成 DIAP 身份', 'loading');
164
- const kp = KeyManager.generate();
165
- const did = kp.did;
166
- const username = getUserName();
167
- const suffix = did.split(':').pop()?.substring(0, 4);
168
- const name = `blln-${username}-${suffix}`;
169
- console.log(` ${GRAY}DID:${RESET} ${did}`);
170
- console.log(` ${GRAY}名称:${RESET} ${name}`);
171
- s.step(1, 5, '生成 DIAP 身份', 'ok');
172
- return { keypair: kp, did, name };
173
- }
174
-
175
- function publishDID(name: string, kp: import('@diap/sdk').KeyPair): Promise<{ cid?: string; ipnsName?: string }> {
176
- s.step(2, 5, '发布 DID → IPFS (后台)', 'loading');
177
-
178
- return new Promise((resolve) => {
179
- const attempt = async () => {
180
- let lastLogTime = 0;
181
- const retryWithBackoff = async (retries: number): Promise<void> => {
182
- try {
183
- const auth = await AgentAuthManager.newWithRemoteIpfs('http://127.0.0.1:5001', 'http://127.0.0.1:8080');
184
- const result = await auth.registerAgent({ name, services: [] }, kp, '');
185
- s.step(2, 5, '发布 DID → IPFS', 'ok');
186
- resolve({ cid: result.cid });
187
- } catch (e: any) {
188
- const now = Date.now();
189
- if (now - lastLogTime > 30000) {
190
- process.stdout.write(` ${YELLOW}⏳ IPNS发布中 (失败${retries}次), 后台重试...${RESET}\r`);
191
- lastLogTime = now;
192
- }
193
- if (retries < 10) {
194
- setTimeout(() => retryWithBackoff(retries + 1), 60000);
195
- } else {
196
- process.stdout.write(` ${YELLOW}⚠ IPNS发布重试结束,本地模式运行${RESET}\n`);
197
- resolve({});
198
- }
199
- }
200
- };
201
-
202
- setTimeout(() => retryWithBackoff(1), 100);
203
- };
204
-
205
- attempt();
206
- });
207
- }
208
-
209
- // ---------------------------------------------------------------------------
210
- // P2P 节点初始化
211
- // ---------------------------------------------------------------------------
212
-
213
- async function bootstrapP2P(
214
- verifier: AgentVerificationManager,
215
- ): Promise<HyperswarmCommunicator> {
216
- s.step(3, 5, '启动 P2P 网络', 'loading');
217
- const rawSeed = crypto.getRandomValues(new Uint8Array(32));
218
- const seed: any = rawSeed;
219
- const comm = createHyperswarmCommunicator({ server: true, client: true, autoConnect: true, maxConnections: 50, seed });
220
-
221
- comm.on('connection', (conn: P2PConnection) => {
222
- const shortId = conn.publicKey.substring(0, 8);
223
- s.info(`🔌 连接: ${shortId}...`);
224
- const all: Map<string, P2PConnection> = (comm as any).connections as Map<string, P2PConnection>;
225
- for (const [k, v] of all) {
226
- if (v.publicKey === conn.publicKey) {
227
- rawStreams.set(v['id'], (comm as any)['__pendingStream']);
228
- break;
229
- }
230
- }
231
- });
232
-
233
- comm.on('message', async (msg: P2PMessage, conn: P2PConnection) => {
234
- const content = new TextDecoder().decode(msg.content);
235
- const shortId = conn.publicKey.substring(0, 8);
236
- s.prompt(`📩 收到 ${shortId}: ${content.substring(0, 50)}...`);
237
- const reply = await dispatchTask(content);
238
- sendRawMsg(conn, reply);
239
- });
240
-
241
- await comm.start();
242
- const topic = createTopic('bolloon-agent-harness') as Buffer;
243
- await comm.joinTopic(topic);
244
- console.log(` ${GRAY}主题:${RESET} ${topic.slice(0, 8).toString('hex')}...`);
245
- s.step(3, 5, '启动 P2P 网络', 'ok');
246
- return comm;
247
- }
248
-
249
- // ---------------------------------------------------------------------------
250
- // iroh/Hybrid P2P 初始化
251
- // ---------------------------------------------------------------------------
252
-
253
- async function bootstrapIroh(keypair: any, name: string): Promise<void> {
254
- s.step(4, 5, '启动 iroh P2P', 'loading');
255
-
256
- try {
257
- const node = await irohTransport.start();
258
- console.log(` ${GRAY}iroh:${RESET} ${node.nodeId.substring(0, 16)}...`);
259
-
260
- hybridMessenger = new HybridMessenger({
261
- preferIrohForLarge: true,
262
- largeThresholdBytes: 64 * 1024,
263
- enableRelay: true,
264
- });
265
-
266
- hybridMessenger.onMessage('task', async (msg) => {
267
- console.log(`[iroh] Task from ${msg.from.substring(0, 12)}...: ${new TextDecoder().decode(msg.payload).substring(0, 50)}...`);
268
- });
269
-
270
- hybridMessenger.onMessage('blob', async (msg) => {
271
- console.log(`[iroh] Blob from ${msg.from.substring(0, 12)}...: ${msg.payload.length} bytes`);
272
- });
273
-
274
- hybridMessenger.onMessage('response', async (msg) => {
275
- console.log(`[iroh] Response from ${msg.from.substring(0, 12)}...`);
276
- });
277
-
278
- if (agentIdentity) {
279
- agentIdentity.irohNodeId = node.nodeId;
280
- }
281
-
282
- s.step(4, 5, '启动 iroh P2P', 'ok');
283
- } catch (e: any) {
284
- s.step(4, 5, '启动 iroh P2P', 'warn');
285
- console.log(` ${YELLOW}iroh 启动失败: ${e.message}${RESET}`);
286
- console.log(` ${GRAY}继续使用 Hyperswarm P2P${RESET}`);
287
- }
288
- }
289
-
290
- // ---------------------------------------------------------------------------
291
- // Agent 懒加载
292
- // ---------------------------------------------------------------------------
293
-
294
- let agent: Awaited<ReturnType<typeof createAgentSession>> | null = null;
295
- let harness: BollharnessIntegration | null = null;
296
- let hybridMessenger: HybridMessenger | null = null;
297
- let agentIdentity: {
298
- did: string;
299
- name: string;
300
- publicKey: string;
301
- peerId?: string;
302
- p2pChannel?: string;
303
- cid?: string;
304
- ipnsName?: string;
305
- irohNodeId?: string;
306
- } | null = null;
307
-
308
- async function getAgent() {
309
- if (!agent) {
310
- const identityDoc = agentIdentity ? {
311
- did: agentIdentity.did,
312
- name: agentIdentity.name,
313
- publicKey: agentIdentity.publicKey,
314
- createdAt: Date.now(),
315
- peerId: agentIdentity.peerId,
316
- p2pChannel: agentIdentity.p2pChannel,
317
- cid: agentIdentity.cid,
318
- ipnsName: agentIdentity.ipnsName
319
- } : undefined;
320
- agent = await createAgentSession({
321
- cwd: process.cwd(),
322
- peerId: 'harness',
323
- identityDoc
324
- });
325
- }
326
- return agent;
327
- }
328
-
329
- // ---------------------------------------------------------------------------
330
- // Dispatch
331
- // ---------------------------------------------------------------------------
332
-
333
- async function dispatchTask(raw: string): Promise<string> {
334
- const body = raw.startsWith('DID:') ? raw.split('|', 1)[1] || '' : raw;
335
- const task = safeParse<RpcTask>(body);
336
- if (!task) return `ERR|${JSON.stringify({ code: 'bad_format' })}`;
337
-
338
- console.log(`\n📥 [${task.type}] from=${task.from?.substring(0, 18)}... id=${task.id}`);
339
- try {
340
- switch (task.type) {
341
- case 'summarize':
342
- return await handleSummarize(task);
343
- case 'improve':
344
- return await handleImprove(task);
345
- default:
346
- return `ERR|${JSON.stringify({ code: 'unknown', type: task.type })}`;
347
- }
348
- } catch (e: any) {
349
- return `ERR|${JSON.stringify({ code: 'error', msg: e.message })}`;
350
- }
351
- }
352
-
353
- async function handleSummarize(task: RpcTask): Promise<string> {
354
- if (!task.documentPath) return `ERR|${JSON.stringify({ code: 'no_path' })}`;
355
- const a = await getAgent();
356
- const { summary, qualityScore } = await a.summarizeDocument(task.documentPath);
357
- console.log(` ✅ 质量=${(qualityScore * 10).toFixed(1)}/10`);
358
- return `OK|${JSON.stringify({ id: task.id, type: 'summarize', qualityScore, summary })}`;
359
- }
360
-
361
- async function handleImprove(task: RpcTask): Promise<string> {
362
- if (!task.documentPath || !task.requirements) {
363
- return `ERR|${JSON.stringify({ code: 'no_path_or_req' })}`;
364
- }
365
- const a = await getAgent();
366
- const res = await a.improveDocument({
367
- originalPath: task.documentPath,
368
- requirements: task.requirements,
369
- context: `来自节点: ${task.from}`,
370
- });
371
- const ok = res.improved ?? false;
372
- console.log(` ✅ 改进${ok ? '成功' : '失败'} 质量=${(res.qualityScore * 10).toFixed(1)}/10 自动发送=${res.shouldAutoSend}`);
373
- return `OK|${JSON.stringify({
374
- id: task.id, type: 'improve', improved: ok,
375
- qualityScore: res.qualityScore, shouldAutoSend: res.shouldAutoSend,
376
- newContent: res.newContent,
377
- })}`;
378
- }
379
-
380
- // ---------------------------------------------------------------------------
381
- // Utils
382
- // ---------------------------------------------------------------------------
383
-
384
- function safeParse<T>(s: string): T | null {
385
- try { return JSON.parse(s) as T; } catch { return null; }
386
- }
387
-
388
- function rpcErr(code: string, msg: string): string {
389
- return `ERR|${JSON.stringify({ code, msg })}`;
390
- }
391
-
392
- // ---------------------------------------------------------------------------
393
- // CLI with persistent bottom prompt
394
- // ---------------------------------------------------------------------------
395
-
396
- const SAVE_CURSOR = '\x1b[s';
397
- const RESTORE_CURSOR = '\x1b[u';
398
- const MOVE_TO_BOTTOM = '\x1b[999A';
399
- const HIDE_CURSOR_SEQ = '\x1b[?25l';
400
- const SHOW_CURSOR_SEQ = '\x1b[?25h';
401
- const MOVE_UP_1 = '\x1b[1A';
402
-
403
- let isRunning = false;
404
- let currentInput = '';
405
- let promptVisible = false;
406
-
407
- function getTermHeight(): number {
408
- return process.stdout.rows || 24;
409
- }
410
-
411
- function moveCursorToBottom(): void {
412
- const height = getTermHeight();
413
- process.stdout.write(`\x1b[${height};1H`);
414
- }
415
-
416
- function showBottomPrompt(): void {
417
- if (!isRunning) return;
418
- promptVisible = true;
419
- process.stdout.write(SAVE_CURSOR);
420
- moveCursorToBottom();
421
- process.stdout.write(`${CYAN}❯ ${RESET}${currentInput}${HIDE_CURSOR_SEQ}`);
422
- process.stdout.write(RESTORE_CURSOR);
423
- }
424
-
425
- function clearPromptLine(): void {
426
- if (!promptVisible) return;
427
- process.stdout.write(SAVE_CURSOR);
428
- moveCursorToBottom();
429
- process.stdout.write(CLEAR_LINE);
430
- process.stdout.write(RESTORE_CURSOR);
431
- promptVisible = false;
432
- }
433
-
434
- function startCLI(comm: HyperswarmCommunicator): void {
435
- isRunning = true;
436
- currentInput = '';
437
- promptVisible = false;
438
-
439
- try {
440
- (process.stdin as any).setRawMode(true);
441
- } catch {
442
- }
443
- readline.emitKeypressEvents(process.stdin);
444
-
445
- process.stdout.write(CLEAR_LINE);
446
- showBottomPrompt();
447
-
448
- const promptTimer = setInterval(() => {
449
- if (isRunning && promptVisible) {
450
- showBottomPrompt();
451
- }
452
- }, 500);
453
-
454
- const handleInput = (chunk: Buffer, key: { name: string; ctrl: boolean }) => {
455
- if (!isRunning) return;
456
-
457
- if (key.ctrl && key.name === 'c') {
458
- clearPromptLine();
459
- process.stdout.write(`\n${CYAN}👋 再见!${RESET}\n`);
460
- try { (process.stdin as any).setRawMode(false); } catch {}
461
- clearInterval(promptTimer);
462
- process.exit(0);
463
- return;
464
- }
465
-
466
- if (key.name === 'return') {
467
- const trimmed = currentInput.trim();
468
- currentInput = '';
469
- clearPromptLine();
470
-
471
- if (trimmed) {
472
- process.stdout.write('\n');
473
- processInput(trimmed, comm).then(() => {
474
- if (isRunning) showBottomPrompt();
475
- });
476
- } else {
477
- showBottomPrompt();
478
- }
479
- return;
480
- }
481
-
482
- if (key.name === 'backspace') {
483
- if (currentInput.length > 0) {
484
- currentInput = currentInput.slice(0, -1);
485
- showBottomPrompt();
486
- }
487
- return;
488
- }
489
-
490
- if (key.name === 'escape' || (key.ctrl && key.name === 'u')) {
491
- currentInput = '';
492
- showBottomPrompt();
493
- return;
494
- }
495
-
496
- if (key.name === 'tab') {
497
- return;
498
- }
499
-
500
- if (key.name && key.name.length === 1) {
501
- currentInput += chunk.toString();
502
- showBottomPrompt();
503
- }
504
- };
505
-
506
- process.stdin.on('data', handleInput);
507
-
508
- process.on('exit', () => {
509
- isRunning = false;
510
- process.stdout.write(SHOW_CURSOR_SEQ);
511
- });
512
- }
513
-
514
- async function processInput(input: string, comm: HyperswarmCommunicator): Promise<void> {
515
- const trimmed = input.trim();
516
-
517
- if (trimmed === '退出' || trimmed === 'exit' || trimmed === 'quit') {
518
- clearPromptLine();
519
- process.stdout.write(`${CYAN}👋 再见!${RESET}\n`);
520
- isRunning = false;
521
- process.stdin.destroy();
522
- comm.stop();
523
- return;
524
- }
525
-
526
- if (trimmed.toLowerCase() === 'peers') {
527
- const peers = comm.getConnections();
528
- process.stdout.write(`${GRAY}已连接节点: ${peers.length}${RESET}\n`);
529
- for (const c of peers) {
530
- process.stdout.write(` ${GRAY}·${RESET} ${c.publicKey.substring(0, 16)}...\n`);
531
- }
532
- return;
533
- }
534
-
535
- if (trimmed.toLowerCase() === 'iroh') {
536
- const nodeId = irohTransport.getNodeId();
537
- const running = irohTransport.isRunning();
538
- const peers = irohTransport.getPeers();
539
- process.stdout.write(`${GRAY}iroh 状态:${RESET}\n`);
540
- process.stdout.write(` ${GRAY}运行中:${RESET} ${running ? '是' : '否'}\n`);
541
- process.stdout.write(` ${GRAY}Node ID:${RESET} ${nodeId ? nodeId.substring(0, 24) + '...' : 'N/A'}\n`);
542
- process.stdout.write(` ${GRAY}已知节点:${RESET} ${peers.length}\n`);
543
- if (hybridMessenger) {
544
- process.stdout.write(` ${GRAY}HybridMessenger:${RESET} 就绪\n`);
545
- }
546
- return;
547
- }
548
-
549
- try {
550
- const a = await getAgent();
551
- const thinking = setInterval(() => {
552
- if (!isRunning) return;
553
- process.stdout.write('\r \x1b[33m⟳\x1b[0m 思考中... \x1b[?25l');
554
- }, 80);
555
- const response = await a.prompt(trimmed);
556
- clearInterval(thinking);
557
- process.stdout.write('\r' + ' '.repeat(30) + '\r');
558
- process.stdout.write(`${response}\n`);
559
- } catch (e: any) {
560
- if (!e.message?.includes('ERR_USE_AFTER_CLOSE') && !e.message?.includes('write after end')) {
561
- process.stdout.write(`${MAGENTA}❌ ${e.message}${RESET}\n`);
562
- }
563
- }
564
- }
565
-
566
- // ---------------------------------------------------------------------------
567
- // Non-Interactive Mode (for AI consumption)
568
- // ---------------------------------------------------------------------------
569
-
570
- interface NonInteractiveResult {
571
- success: boolean;
572
- response?: string;
573
- error?: string;
574
- metadata?: {
575
- duration?: number;
576
- qualityScore?: number;
577
- peers?: number;
578
- file?: string;
579
- };
580
- }
581
-
582
- const AVAILABLE_TOOLS = [
583
- { name: 'read_document', description: '读取文档 (txt, md, pdf, docx)', example: '--read <file>' },
584
- { name: 'summarize_document', description: '总结文档内容', example: '--summarize <file>' },
585
- { name: 'improve_document', description: '改进文档内容', example: '--improve <file> <requirements>' },
586
- { name: 'list_peers', description: '列出已连接的对等节点', example: '--peers' },
587
- { name: 'send_message', description: '向对等节点发送消息', example: '--send <peerId> <message>' },
588
- { name: 'broadcast_message', description: '广播消息到所有节点', example: '--broadcast <message>' },
589
- { name: 'get_identity', description: '获取当前智能体身份', example: '--identity' },
590
- { name: 'get_operation_logs', description: '获取操作日志', example: '--logs' },
591
- { name: 'search_files', description: '搜索文件', example: '--search <keyword>' },
592
- { name: 'prompt', description: '通用 AI 对话', example: '--prompt <text>' },
593
- { name: 'list_agents', description: '列出所有 SubAgent', example: '--agents' },
594
- { name: 'register_agent', description: '注册新 SubAgent', example: '--register-agent <name> [capabilities...]' },
595
- { name: 'delegate_task', description: '委派任务给最佳 Agent', example: '--delegate <task> [capabilities...]' },
596
- { name: 'global_context', description: '显示全局共享上下文', example: '--context' },
597
- { name: 'global_agents', description: '显示全局 Agent 注册表', example: '--global-agents' },
598
- { name: 'add_action', description: '添加用户行动到共享上下文', example: '--add-action <content> [importance]' },
599
- { name: 'harness_init', description: '初始化 Bollharness 治理框架', example: '--harness-init' },
600
- { name: 'harness_gate', description: '显示当前 Gate 状态', example: '--harness-gate' },
601
- { name: 'harness_transition', description: '执行 Gate 转移', example: '--harness-transition [PASS|BLOCK]' },
602
- { name: 'harness_skill', description: '执行 Harness Skill', example: '--harness-skill <name> [action]' },
603
- { name: 'harness_classify', description: '分类变更类型', example: '--harness-classify <description>' },
604
- { name: 'harness_context', description: '获取文件上下文', example: '--harness-context <file>' },
605
- { name: 'harness_check', description: '执行 Guard 检查', example: '--harness-check <file>' },
606
- { name: 'update_check', description: '检查 npm 包更新', example: '--update-check' },
607
- { name: 'update_now', description: '立即更新到最新版本', example: '--update-now [package]' },
608
- ];
609
-
610
- async function runToolCommand(
611
- tool: string,
612
- args: string[],
613
- outputJson: boolean,
614
- comm: HyperswarmCommunicator
615
- ): Promise<void> {
616
- const a = await getAgent();
617
- const startTime = Date.now();
618
- let response: string;
619
- let error: string | undefined;
620
- let metadata: NonInteractiveResult['metadata'] = {
621
- peers: comm?.getConnections().length || 0
622
- };
623
-
624
- const toolLabels: Record<string, string> = {
625
- 'read': '读取文档',
626
- 'summarize': '总结文档',
627
- 'improve': '改进文档',
628
- 'prompt': 'AI 对话',
629
- 'agents': '列出 Agent',
630
- 'register-agent': '注册 Agent',
631
- 'delegate': '委派任务',
632
- 'context': '全局上下文',
633
- 'global-agents': 'Agent 注册表',
634
- 'add-action': '添加行动',
635
- 'peers': '列出节点',
636
- 'broadcast': '广播消息',
637
- 'identity': '显示身份',
638
- 'logs': '操作日志',
639
- 'tools': '可用工具'
640
- };
641
-
642
- const label = toolLabels[tool] || tool;
643
- const thinking = s.Thinking();
644
-
645
- try {
646
- switch (tool) {
647
- case 'read': {
648
- const [filePath] = args;
649
- if (!filePath) {
650
- response = '错误: 缺少文件路径参数';
651
- error = response;
652
- break;
653
- }
654
- const content = await documentReader.read(filePath);
655
- response = `${GREEN}📄 ${content.metadata.filename}${RESET}\n${GRAY}大小: ${content.metadata.size} 字节${RESET}\n\n${content.text}`;
656
- break;
657
- }
658
-
659
- case 'summarize': {
660
- const [filePath, ...ctx] = args;
661
- if (!filePath) {
662
- response = '错误: 缺少文件路径参数';
663
- error = response;
664
- break;
665
- }
666
- const result = await a.summarizeDocument(filePath, ctx.join(' '));
667
- response = `📝 摘要:\n${result.summary}\n\n质量评分: ${(result.qualityScore * 10).toFixed(1)}/10`;
668
- metadata.qualityScore = result.qualityScore;
669
- break;
670
- }
671
-
672
- case 'improve': {
673
- const [filePath, ...req] = args;
674
- if (!filePath || req.length === 0) {
675
- response = '错误: 缺少文件路径或需求参数';
676
- error = response;
677
- break;
678
- }
679
- const result = await a.improveDocument({
680
- originalPath: filePath,
681
- requirements: req.join(' ')
682
- });
683
- response = result.newContent || '';
684
- if (!result.improved) {
685
- response = '错误: 改进失败';
686
- error = response;
687
- }
688
- metadata.qualityScore = result.qualityScore;
689
- break;
690
- }
691
-
692
- case 'peers': {
693
- const peers = comm?.getConnections() || [];
694
- if (peers.length === 0) {
695
- response = '当前无连接的对等节点';
696
- } else {
697
- response = `已连接节点 (${peers.length}):\n${peers.map((c: P2PConnection) => ` · ${c.publicKey.substring(0, 16)}...`).join('\n')}`;
698
- }
699
- break;
700
- }
701
-
702
- case 'iroh': {
703
- const nodeId = irohTransport.getNodeId();
704
- const running = irohTransport.isRunning();
705
- const irohPeers = irohTransport.getPeers();
706
- const messenger = hybridMessenger ? 'HybridMessenger 就绪' : 'HybridMessenger 未初始化';
707
- response = `iroh P2P 状态:
708
- 运行中: ${running ? '是' : '否'}
709
- Node ID: ${nodeId ? nodeId.substring(0, 32) + '...' : 'N/A'}
710
- 已知节点: ${irohPeers.length}
711
- ${messenger}`;
712
- break;
713
- }
714
-
715
- case 'identity': {
716
- const identity = a.getIdentity();
717
- response = JSON.stringify(identity, null, 2);
718
- break;
719
- }
720
-
721
- case 'logs': {
722
- const logs = (a as any).getOperationLogs?.() || [];
723
- response = logs.length === 0
724
- ? '暂无操作日志'
725
- : logs.map((l: { timestamp: number; status: string; action: string }) => `[${new Date(l.timestamp).toISOString()}] ${l.status}: ${l.action}`).join('\n');
726
- break;
727
- }
728
-
729
- case 'search': {
730
- const [keyword] = args;
731
- if (!keyword) {
732
- response = '错误: 缺少搜索关键词';
733
- error = response;
734
- break;
735
- }
736
- response = `搜索功能开发中,关键字: ${keyword}`;
737
- break;
738
- }
739
-
740
- case 'broadcast': {
741
- const [message] = args;
742
- if (!message) {
743
- response = '错误: 缺少广播消息内容';
744
- error = response;
745
- break;
746
- }
747
- await a.broadcast(message);
748
- response = `广播已发送: ${message.substring(0, 50)}...`;
749
- break;
750
- }
751
-
752
- case 'send': {
753
- const [peerId, ...messageParts] = args;
754
- if (!peerId || messageParts.length === 0) {
755
- response = '错误: 缺少节点ID或消息内容';
756
- error = response;
757
- break;
758
- }
759
- await a.sendMessage(peerId, messageParts.join(' '));
760
- response = `消息已发送到 ${peerId.substring(0, 16)}...`;
761
- break;
762
- }
763
-
764
- case 'prompt': {
765
- const [text] = args;
766
- if (!text) {
767
- response = '错误: 缺少 prompt 文本';
768
- error = response;
769
- break;
770
- }
771
- response = await a.prompt(text);
772
- break;
773
- }
774
-
775
- case 'tools': {
776
- response = '🛠️ 可用工具:\n\n' + AVAILABLE_TOOLS.map(t =>
777
- ` ${t.name}\n ${t.description}\n 示例: ${t.example}`
778
- ).join('\n\n');
779
- break;
780
- }
781
-
782
- // ==================== Bollharness Commands ====================
783
-
784
- case 'harness-init': {
785
- harness = createBollharnessIntegration();
786
- const skills = harness!.listSkills();
787
- const harnessSkills = harness!.listHarnessSkills();
788
- response = `✅ Bollharness 初始化成功\n\n` +
789
- `已加载 Skills: ${skills.length}\n` +
790
- `已加载 Harness Skills: ${harnessSkills.length}\n\n` +
791
- `Skills:\n${skills.map(s => ` - ${s.name}: ${s.description}`).join('\n')}\n\n` +
792
- `Gates: 0-8 (8-Gate 工作流)`;
793
- break;
794
- }
795
-
796
- case 'harness-gate': {
797
- if (!harness) {
798
- harness = createBollharnessIntegration();
799
- }
800
- const gate = harness!.getCurrentGate();
801
- const gatePack = harness!.getGatePack();
802
- const blockers = (gatePack.blockers as string[]) || [];
803
- response = `🚪 当前 Gate: ${gate}\n\n` +
804
- `Entry: ${gatePack.entry_satisfied ? '✅ 满足' : '❌ 未满足'}\n` +
805
- `要求产物: ${gatePack.required_artifact}\n` +
806
- `下一步 Skill: ${gatePack.required_next_skill}\n` +
807
- `Blockers: ${blockers.length > 0 ? blockers.join(', ') : '无'}`;
808
- break;
809
- }
810
-
811
- case 'harness-transition': {
812
- if (!harness) {
813
- harness = createBollharnessIntegration();
814
- }
815
- const [verdict] = args;
816
- const result = await harness!.transitionGate(
817
- verdict ? { verdict: verdict as 'PASS' | 'BLOCK', details: '' } : undefined
818
- );
819
- const transitionBlockers = (result.transition as { blockers?: string[] })?.blockers || [];
820
- response = `🔄 Gate 转移: ${result.success ? '✅ 成功' : '❌ 失败'}\n` +
821
- `Blockers: ${transitionBlockers.length > 0 ? transitionBlockers.join(', ') : '无'}`;
822
- break;
823
- }
824
-
825
- case 'harness-skill': {
826
- if (!harness) {
827
- harness = createBollharnessIntegration();
828
- }
829
- const [skillName, action] = args;
830
- if (!skillName) {
831
- const skills = harness!.listSkills();
832
- response = `📋 可用 Skills (${skills.length}):\n\n` +
833
- skills.map(s => ` ${s.name}: ${s.description}`).join('\n');
834
- break;
835
- }
836
- const result = await harness!.executeSkill(skillName, { action: action || 'get_gate' });
837
- response = `🎯 Skill '${skillName}' 执行结果:\n\n${result.result || result.error}`;
838
- break;
839
- }
840
-
841
- case 'harness-classify': {
842
- if (!harness) {
843
- harness = createBollharnessIntegration();
844
- }
845
- const [description] = args;
846
- if (!description) {
847
- response = '用法: --harness-classify <变更描述>';
848
- error = response;
849
- break;
850
- }
851
- const result = harness!.classifyChange(description);
852
- response = `📊 变更分类: ${result.classification}\n` +
853
- `最小路径: ${result.minimum_gates}\n` +
854
- `快速通道: ${result.fast_track ? '✅ 可用' : '❌ 不可用'}`;
855
- break;
856
- }
857
-
858
- case 'harness-context': {
859
- if (!harness) {
860
- harness = createBollharnessIntegration();
861
- }
862
- const [filePath] = args;
863
- if (!filePath) {
864
- response = '用法: --harness-context <文件路径>';
865
- error = response;
866
- break;
867
- }
868
- const context = harness!.getContext(filePath);
869
- response = `📄 文件: ${filePath}\n\n上下文:\n${context || '无匹配上下文'}`;
870
- break;
871
- }
872
-
873
- case 'harness-check': {
874
- if (!harness) {
875
- harness = createBollharnessIntegration();
876
- }
877
- const [filePath] = args;
878
- if (!filePath) {
879
- response = '用法: --harness-check <文件路径>';
880
- error = response;
881
- break;
882
- }
883
- const result = await harness!.processFileEdit(filePath);
884
- response = `🔍 Guard 检查: ${filePath}\n\n` +
885
- `通过: ${result.success ? '✅' : '❌'}\n` +
886
- `错误: ${result.errors.length > 0 ? result.errors.join('\n') : '无'}`;
887
- break;
888
- }
889
-
890
- case 'harness-archive': {
891
- const a = await getAgent();
892
- const sessionHarness = (a as any).getHarness?.();
893
- if (sessionHarness) {
894
- (a as any).archiveToHarness?.();
895
- response = `📦 Session 已归档到 Pi SDK Harness`;
896
- } else {
897
- if (!harness) {
898
- harness = createBollharnessIntegration();
899
- }
900
- const logs = (a as any).getOperationLogs?.() || [];
901
- const archive = harness.archiveSession(logs);
902
- response = `📦 Session 已归档:\n` +
903
- `ID: ${archive.id}\n` +
904
- `Gate: ${archive.gate}\n` +
905
- `动作数: ${archive.actionCount}\n` +
906
- `摘要: ${archive.summary}`;
907
- }
908
- break;
909
- }
910
-
911
- case 'harness-sessions': {
912
- const a = await getAgent();
913
- const sessionHarness = (a as any).getHarness?.();
914
- if (sessionHarness) {
915
- harness = sessionHarness;
916
- }
917
- if (!harness) {
918
- harness = createBollharnessIntegration();
919
- }
920
- const archives = harness.getSessionArchives();
921
- if (archives.length === 0) {
922
- response = '暂无 Session 归档记录';
923
- break;
924
- }
925
- response = `📜 Session 归档记录 (${archives.length}):\n\n`;
926
- for (const archive of archives.slice(-10)) {
927
- response += `### ${archive.id}\n`;
928
- response += `Gate: ${archive.gate} | 动作: ${archive.actionCount}\n`;
929
- response += `摘要: ${archive.summary}\n\n`;
930
- }
931
- break;
932
- }
933
-
934
- case 'harness-session-context': {
935
- const a = await getAgent();
936
- const sessionHarness = (a as any).getHarness?.();
937
- if (sessionHarness) {
938
- const [sessionId] = args;
939
- const context = sessionHarness.getSessionContext(sessionId || undefined);
940
- response = `📄 Pi SDK Session 上下文:\n\n${context}`;
941
- } else {
942
- if (!harness) {
943
- harness = createBollharnessIntegration();
944
- }
945
- const [sessionId] = args;
946
- const context = harness.getSessionContext(sessionId || undefined);
947
- response = `📄 Session 上下文:\n\n${context}`;
948
- }
949
- break;
950
- }
951
-
952
- case 'agents': {
953
- const manager = await createSubAgentManager();
954
- const agents = await manager.getAllAgents();
955
- if (agents.length === 0) {
956
- response = '暂无注册的 SubAgent';
957
- } else {
958
- response = `📋 已注册 SubAgent (${agents.length}):\n\n`;
959
- for (const agent of agents) {
960
- response += ` [${agent.status}] ${agent.name} (${agent.id})\n`;
961
- response += ` 能力: ${agent.capabilities.join(', ')}\n`;
962
- response += ` DID: ${agent.did || 'N/A'}\n\n`;
963
- }
964
- }
965
- break;
966
- }
967
-
968
- case 'register-agent': {
969
- const [name, ...capabilities] = args;
970
- if (!name) {
971
- response = '用法: --register-agent <name> [capability1] [capability2] ...';
972
- error = response;
973
- break;
974
- }
975
- const manager = await createSubAgentManager();
976
- const agent = await manager.registerAgent({
977
- name,
978
- capabilities: capabilities.length > 0 ? capabilities : ['general'],
979
- did: `did:local:${Date.now()}`
980
- });
981
- response = `✅ SubAgent 注册成功:\n ID: ${agent.id}\n 名称: ${agent.name}\n 能力: ${agent.capabilities.join(', ')}`;
982
- break;
983
- }
984
-
985
- case 'delegate': {
986
- const [taskDesc, ...requiredCaps] = args;
987
- if (!taskDesc) {
988
- response = '用法: --delegate <任务描述> [能力要求1] [能力要求2] ...';
989
- error = response;
990
- break;
991
- }
992
- const manager = await createSubAgentManager();
993
- const a = await getAgent();
994
- const { task, agent } = await manager.delegateTask(
995
- 'cli-user',
996
- taskDesc,
997
- requiredCaps.length > 0 ? requiredCaps : ['general']
998
- );
999
- if (agent) {
1000
- response = `✅ 任务已委派:\n 任务ID: ${task.id}\n 执行Agent: ${agent.name} (${agent.id})\n 状态: ${task.status}`;
1001
- } else {
1002
- response = `⚠️ 未找到合适的Agent,任务已创建:\n 任务ID: ${task.id}\n 状态: ${task.status}`;
1003
- }
1004
- break;
1005
- }
1006
-
1007
- case 'context': {
1008
- const ctx = await getGlobalSharedContext();
1009
- response = await ctx.getContextSummary();
1010
- break;
1011
- }
1012
-
1013
- case 'global-agents': {
1014
- const ctx = await getGlobalSharedContext();
1015
- const agents = await ctx.getAllAgents();
1016
- if (agents.length === 0) {
1017
- response = '全局注册表暂无 Agent';
1018
- } else {
1019
- response = `🌐 全局 Agent 注册表 (${agents.length}):\n\n`;
1020
- for (const agent of agents) {
1021
- response += ` [${agent.status}] ${agent.name || agent.agentId}\n`;
1022
- response += ` ID: ${agent.agentId}\n`;
1023
- response += ` DID: ${agent.did || 'N/A'}\n`;
1024
- response += ` 能力: ${agent.capabilities.join(', ')}\n\n`;
1025
- }
1026
- }
1027
- break;
1028
- }
1029
-
1030
- case 'add-action': {
1031
- const [content, importance] = args;
1032
- if (!content) {
1033
- response = '用法: --add-action <内容> [重要性(1-10)]';
1034
- error = response;
1035
- break;
1036
- }
1037
- const ctx = await getGlobalSharedContext();
1038
- await ctx.addUserAction(content, undefined, undefined, parseInt(importance || '5', 10));
1039
- response = `✅ 已添加用户行动: ${content.substring(0, 50)}...`;
1040
- break;
1041
- }
1042
-
1043
- // ==================== Update Commands ====================
1044
-
1045
- case 'update-check': {
1046
- const { checkForUpdates } = await import('./utils/auto-update.js');
1047
- const info = await checkForUpdates();
1048
- if (info && info.outdated) {
1049
- response = `📦 发现更新可用:\n\n` +
1050
- `当前版本: ${info.version}\n` +
1051
- `最新版本: ${info.latest}\n\n` +
1052
- `待更新包:\n${info.packages.map(p => ` - ${p.name}: ${p.current} → ${p.latest}`).join('\n')}\n\n` +
1053
- `运行 --update-now 进行更新`;
1054
- } else {
1055
- response = `✅ 已是最新版本 (${info?.version || 'unknown'})`;
1056
- }
1057
- break;
1058
- }
1059
-
1060
- case 'update-now': {
1061
- const { performUpdate } = await import('./utils/auto-update.js');
1062
- const packages = args.length > 0 ? args : undefined;
1063
- const result = await performUpdate(packages as string[] | undefined);
1064
- if (result.success) {
1065
- response = `✅ 更新成功${result.updatedPackages ? `: ${result.updatedPackages.join(', ')}` : ''}`;
1066
- if (result.updated) {
1067
- response += `\n\n${YELLOW}请重新启动应用以使用新版本${RESET}`;
1068
- }
1069
- } else {
1070
- response = `❌ 更新失败: ${result.error}`;
1071
- error = response;
1072
- }
1073
- break;
1074
- }
1075
-
1076
- default:
1077
- response = `错误: 未知工具 "${tool}"`;
1078
- error = response;
1079
- }
1080
- } catch (e: any) {
1081
- response = `错误: ${e.message}`;
1082
- error = response;
1083
- }
1084
-
1085
- metadata.duration = Date.now() - startTime;
1086
-
1087
- s.clearThinking(thinking);
1088
-
1089
- if (outputJson) {
1090
- const result: NonInteractiveResult = {
1091
- success: !error,
1092
- response,
1093
- error,
1094
- metadata
1095
- };
1096
- console.log(JSON.stringify(result, null, 2));
1097
- } else {
1098
- if (error) {
1099
- s.divider();
1100
- console.log(`${MAGENTA}${error}${RESET}\n`);
1101
- } else {
1102
- s.divider();
1103
- console.log(`${response}\n`);
1104
- }
1105
- console.log(`${GRAY}耗时: ${metadata.duration}ms${RESET}`);
1106
- }
1107
- }
1108
-
1109
- async function runNonInteractive(
1110
- args: ParsedArgs,
1111
- comm: HyperswarmCommunicator
1112
- ): Promise<void> {
1113
- const { prompt, json, output, tool, toolArgs } = args;
1114
-
1115
- if (output) {
1116
- const originalLog = console.log;
1117
- let outputBuffer = '';
1118
- console.log = (...params: any[]) => {
1119
- outputBuffer += params.join(' ') + '\n';
1120
- };
1121
-
1122
- if (tool) {
1123
- await runToolCommand(tool, toolArgs, false, comm);
1124
- } else if (prompt) {
1125
- const a = await getAgent();
1126
- console.log(await a.prompt(prompt));
1127
- }
1128
-
1129
- console.log = originalLog;
1130
- await fs.writeFile(output, outputBuffer.trim(), 'utf-8');
1131
- console.log(`✅ 结果已保存到: ${output}`);
1132
- return;
1133
- }
1134
-
1135
- if (tool) {
1136
- await runToolCommand(tool, toolArgs, !!json, comm);
1137
- } else if (prompt) {
1138
- const startTime = Date.now();
1139
- const a = await getAgent();
1140
- let response: string;
1141
- try {
1142
- response = await a.prompt(prompt);
1143
- } catch (e: any) {
1144
- response = `错误: ${e.message}`;
1145
- }
1146
-
1147
- const duration = Date.now() - startTime;
1148
- const peers = comm?.getConnections().length || 0;
1149
-
1150
- if (json) {
1151
- const result: NonInteractiveResult = {
1152
- success: !response.startsWith('错误:'),
1153
- response,
1154
- error: response.startsWith('错误:') ? response : undefined,
1155
- metadata: { duration, peers }
1156
- };
1157
- console.log(JSON.stringify(result, null, 2));
1158
- } else {
1159
- console.log(response);
1160
- }
1161
- }
1162
- }
1163
-
1164
- interface ParsedArgs {
1165
- prompt?: string;
1166
- json?: boolean;
1167
- web?: boolean;
1168
- help?: boolean;
1169
- tools?: boolean;
1170
- read?: boolean;
1171
- summarize?: boolean;
1172
- improve?: boolean;
1173
- peers?: boolean;
1174
- iroh?: boolean;
1175
- identity?: boolean;
1176
- logs?: boolean;
1177
- broadcast?: boolean;
1178
- send?: boolean;
1179
- search?: boolean;
1180
- model?: string;
1181
- output?: string;
1182
- tool?: string;
1183
- toolArgs: string[];
1184
- agents?: boolean;
1185
- registerAgent?: boolean;
1186
- delegate?: boolean;
1187
- context?: boolean;
1188
- globalAgents?: boolean;
1189
- addAction?: boolean;
1190
- tui?: boolean;
1191
- updateCheck?: boolean;
1192
- updateNow?: boolean;
1193
- }
1194
-
1195
- function parseArgs(): ParsedArgs {
1196
- const args = process.argv.slice(2);
1197
- const result: ParsedArgs = { toolArgs: [] };
1198
-
1199
- for (let i = 0; i < args.length; i++) {
1200
- const arg = args[i];
1201
-
1202
- switch (arg) {
1203
- case '--prompt':
1204
- case '-p':
1205
- result.prompt = args[++i];
1206
- result.tool = 'prompt';
1207
- break;
1208
- case '--json':
1209
- case '-j':
1210
- result.json = true;
1211
- break;
1212
- case '--web':
1213
- result.web = true;
1214
- break;
1215
- case '--help':
1216
- case '-h':
1217
- result.help = true;
1218
- break;
1219
- case '--tools':
1220
- result.tools = true;
1221
- result.tool = 'tools';
1222
- break;
1223
- case '--read':
1224
- result.read = true;
1225
- result.tool = 'read';
1226
- result.toolArgs = [args[++i]].filter(Boolean);
1227
- break;
1228
- case '--summarize':
1229
- result.summarize = true;
1230
- result.tool = 'summarize';
1231
- const summarizeArgs: string[] = [];
1232
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1233
- summarizeArgs.push(args[++i]);
1234
- }
1235
- result.toolArgs = summarizeArgs;
1236
- break;
1237
- case '--improve':
1238
- result.improve = true;
1239
- result.tool = 'improve';
1240
- const improveArgs: string[] = [];
1241
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1242
- improveArgs.push(args[++i]);
1243
- }
1244
- result.toolArgs = improveArgs;
1245
- break;
1246
- case '--peers':
1247
- result.peers = true;
1248
- result.tool = 'peers';
1249
- break;
1250
- case '--iroh':
1251
- result.iroh = true;
1252
- result.tool = 'iroh';
1253
- break;
1254
- case '--identity':
1255
- result.identity = true;
1256
- result.tool = 'identity';
1257
- break;
1258
- case '--logs':
1259
- result.logs = true;
1260
- result.tool = 'logs';
1261
- break;
1262
- case '--broadcast':
1263
- result.broadcast = true;
1264
- result.tool = 'broadcast';
1265
- result.toolArgs = [args[++i]].filter(Boolean);
1266
- break;
1267
- case '--send':
1268
- result.send = true;
1269
- result.tool = 'send';
1270
- const sendArgs: string[] = [];
1271
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1272
- sendArgs.push(args[++i]);
1273
- }
1274
- result.toolArgs = sendArgs;
1275
- break;
1276
- case '--search':
1277
- result.search = true;
1278
- result.tool = 'search';
1279
- result.toolArgs = [args[++i]].filter(Boolean);
1280
- break;
1281
- case '--agents':
1282
- result.agents = true;
1283
- result.tool = 'agents';
1284
- break;
1285
- case '--register-agent':
1286
- result.registerAgent = true;
1287
- result.tool = 'register-agent';
1288
- const regArgs: string[] = [];
1289
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1290
- regArgs.push(args[++i]);
1291
- }
1292
- result.toolArgs = regArgs;
1293
- break;
1294
- case '--delegate':
1295
- result.delegate = true;
1296
- result.tool = 'delegate';
1297
- const delArgs: string[] = [];
1298
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1299
- delArgs.push(args[++i]);
1300
- }
1301
- result.toolArgs = delArgs;
1302
- break;
1303
- case '--context':
1304
- result.context = true;
1305
- result.tool = 'context';
1306
- break;
1307
- case '--global-agents':
1308
- result.globalAgents = true;
1309
- result.tool = 'global-agents';
1310
- break;
1311
- case '--add-action':
1312
- result.addAction = true;
1313
- result.tool = 'add-action';
1314
- const actionArgs: string[] = [];
1315
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1316
- actionArgs.push(args[++i]);
1317
- }
1318
- result.toolArgs = actionArgs;
1319
- break;
1320
- case '--harness-init':
1321
- result.tool = 'harness-init';
1322
- break;
1323
- case '--harness-gate':
1324
- result.tool = 'harness-gate';
1325
- break;
1326
- case '--harness-transition':
1327
- result.tool = 'harness-transition';
1328
- const transitionArgs: string[] = [];
1329
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1330
- transitionArgs.push(args[++i]);
1331
- }
1332
- result.toolArgs = transitionArgs;
1333
- break;
1334
- case '--harness-skill':
1335
- result.tool = 'harness-skill';
1336
- const skillArgs: string[] = [];
1337
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1338
- skillArgs.push(args[++i]);
1339
- }
1340
- result.toolArgs = skillArgs;
1341
- break;
1342
- case '--harness-classify':
1343
- result.tool = 'harness-classify';
1344
- const classifyArgs: string[] = [];
1345
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1346
- classifyArgs.push(args[++i]);
1347
- }
1348
- result.toolArgs = classifyArgs;
1349
- break;
1350
- case '--harness-context':
1351
- result.tool = 'harness-context';
1352
- const contextArgs: string[] = [];
1353
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1354
- contextArgs.push(args[++i]);
1355
- }
1356
- result.toolArgs = contextArgs;
1357
- break;
1358
- case '--harness-check':
1359
- result.tool = 'harness-check';
1360
- const checkArgs: string[] = [];
1361
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1362
- checkArgs.push(args[++i]);
1363
- }
1364
- result.toolArgs = checkArgs;
1365
- break;
1366
- case '--harness-archive':
1367
- result.tool = 'harness-archive';
1368
- break;
1369
- case '--harness-sessions':
1370
- result.tool = 'harness-sessions';
1371
- break;
1372
- case '--harness-session-context':
1373
- result.tool = 'harness-session-context';
1374
- const sessionArgs: string[] = [];
1375
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1376
- sessionArgs.push(args[++i]);
1377
- }
1378
- result.toolArgs = sessionArgs;
1379
- break;
1380
- case '--update-check':
1381
- result.updateCheck = true;
1382
- result.tool = 'update-check';
1383
- break;
1384
- case '--update-now':
1385
- result.updateNow = true;
1386
- result.tool = 'update-now';
1387
- const updateArgs: string[] = [];
1388
- while (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1389
- updateArgs.push(args[++i]);
1390
- }
1391
- result.toolArgs = updateArgs;
1392
- break;
1393
- case '--tui':
1394
- result.tui = true;
1395
- break;
1396
- case '--model':
1397
- result.model = args[++i];
1398
- break;
1399
- case '--output':
1400
- case '-o':
1401
- result.output = args[++i];
1402
- break;
1403
- case '--':
1404
- result.toolArgs = args.slice(i + 1);
1405
- i = args.length;
1406
- break;
1407
- default:
1408
- if (!arg.startsWith('-') && !result.prompt && !result.tool) {
1409
- result.prompt = arg;
1410
- result.tool = 'prompt';
1411
- }
1412
- }
1413
- }
1414
-
1415
- return result;
1416
- }
1417
-
1418
- function printHelp(): void {
1419
- console.log(`
1420
- 🤖 Bolloon Agent - AI 可调用文档处理智能体
1421
-
1422
- 用法:
1423
- npx tsx src/index.ts [选项] [参数]
1424
-
1425
- 选项:
1426
- # 文档处理
1427
- --read <file> 读取文档 (txt, md, pdf, docx)
1428
- --summarize <file> [ctx] 总结文档,可选上下文
1429
- --improve <file> <req> 改进文档,req 为改进要求
1430
-
1431
- # P2P 网络
1432
- --peers 列出已连接的对等节点
1433
- --broadcast <msg> 广播消息到所有节点
1434
- --send <peerId> <msg> 向指定节点发送消息
1435
-
1436
- # 智能体
1437
- --identity 显示当前智能体身份
1438
- --logs 显示操作日志
1439
- --search <keyword> 搜索文件
1440
- --tools 显示所有可用工具
1441
-
1442
- # SubAgent 管理
1443
- --agents 列出所有 SubAgent
1444
- --register-agent <name> [cap1] [cap2]... 注册新 SubAgent
1445
- --delegate <任务描述> [能力要求...] 委派任务给最佳 Agent
1446
-
1447
- # 全局共享上下文
1448
- --context 显示全局共享上下文摘要
1449
- --global-agents 显示全局 Agent 注册表
1450
- --add-action <内容> [重要性] 添加用户行动到共享上下文
1451
-
1452
- # Bollharness 治理框架
1453
- --harness-init 初始化 Bollharness 治理框架
1454
- --harness-gate 显示当前 Gate 状态
1455
- --harness-transition [PASS|BLOCK] 执行 Gate 转移
1456
- --harness-skill <name> [action] 执行 Harness Skill
1457
- --harness-classify <描述> 分类变更类型
1458
- --harness-context <file> 获取文件上下文
1459
- --harness-check <file> 执行 Guard 检查
1460
- --harness-archive 归档当前 Session 到 Harness
1461
- --harness-sessions 列出 Session 归档记录
1462
- --harness-session-context [id] 获取 Session 上下文
1463
-
1464
- # 自动更新
1465
- --update-check 检查 npm 包更新
1466
- --update-now [pkg] 更新到最新版本
1467
-
1468
- # AI 对话
1469
- --prompt, -p <text> 通用 AI 对话(默认)
1470
- --model <name> 指定使用的模型
1471
-
1472
- # 输出控制
1473
- --json, -j 输出 JSON 格式
1474
- --output, -o <file> 结果保存到文件
1475
- --web 启动 Web UI 模式
1476
- --help, -h 显示帮助信息
1477
-
1478
- 示例:
1479
- # 文档处理
1480
- npx tsx src/index.ts --read 想法.md
1481
- npx tsx src/index.ts --summarize docs/想法.md
1482
- npx tsx src/index.ts --improve docs/README.md "让内容更简洁"
1483
- npx tsx src/index.ts --read 想法.md -o summary.txt
1484
-
1485
- # P2P 网络
1486
- npx tsx src/index.ts --peers
1487
- npx tsx src/index.ts --broadcast "Hello everyone"
1488
- npx tsx src/index.ts --send QmABC... "私信内容"
1489
-
1490
- # AI 对话
1491
- npx tsx src/index.ts --prompt "总结 README.md"
1492
- npx tsx src/index.ts -p "分析这个项目" -j
1493
-
1494
- # 交互模式
1495
- npx tsx src/index.ts
1496
-
1497
- # Web 模式
1498
- npx tsx src/index.ts --web
1499
-
1500
- 环境变量:
1501
- MINIMAX_API_KEY MiniMax API 密钥
1502
- DEEPSEEK_API_KEY DeepSeek API 密钥
1503
- KIMI_API_KEY / MOONSHOT_API_KEY Kimi/Moonshot API 密钥
1504
- GLM_API_KEY / ZHIPU_API_KEY 智谱 GLM API 密钥
1505
- QWEN_API_KEY / DASHSCOPE_API_KEY 通义千问 API 密钥
1506
- OPENAI_API_KEY OpenAI API 密钥(Pi SDK)
1507
- ANTHROPIC_API_KEY Anthropic API 密钥(Pi SDK)
1508
- PORT Web 服务端口(默认 54188)
1509
- `);
1510
- }
1511
-
1512
- // ---------------------------------------------------------------------------
1513
- // Entry point
1514
- // ---------------------------------------------------------------------------
1515
-
1516
- async function main() {
1517
- const args = parseArgs();
1518
-
1519
- if (args.help) {
1520
- printHelp();
1521
- process.exit(0);
1522
- }
1523
-
1524
- // 自动更新已禁用: 启动时不再自动检查/安装更新.
1525
- // 想手动检查: bolloon --update-check
1526
- // 想手动更新: bolloon --update-now [package]
1527
- // 想完全屏蔽 (CI / sandbox): BOLLOON_SKIP_UPDATE=true
1528
-
1529
- const mode = args.web ? 'web' : 'cli';
1530
- const isNonInteractive = !!(args.tool || args.prompt);
1531
- const isTuiMode = mode === 'cli' && !isNonInteractive && args.tui;
1532
-
1533
- const originalLog = console.log;
1534
- const originalInfo = console.info;
1535
- const originalStdoutWrite = process.stdout.write.bind(process.stdout);
1536
-
1537
- const isSdkLog = (msg: string): boolean => {
1538
- return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(msg);
1539
- };
1540
-
1541
- if (isTuiMode) {
1542
- console.log = (...args: any[]) => {
1543
- const msg = args.join(' ');
1544
- if (isSdkLog(msg)) return;
1545
- originalLog.apply(console, args);
1546
- };
1547
- console.info = (...args: any[]) => {
1548
- const msg = args.join(' ');
1549
- if (isSdkLog(msg)) return;
1550
- originalInfo.apply(console, args);
1551
- };
1552
- process.stdout.write = (chunk: any, ...args: any[]) => {
1553
- const msg = String(chunk);
1554
- if (isSdkLog(msg)) return true;
1555
- return originalStdoutWrite(chunk, ...args);
1556
- };
1557
- }
1558
-
1559
- if (isNonInteractive) {
1560
- console.error = () => {};
1561
- }
1562
-
1563
- s.banner();
1564
-
1565
- s.section('系统初始化');
1566
-
1567
- const hasOpenAI = !!process.env.OPENAI_API_KEY;
1568
- const hasAnthropic = !!process.env.ANTHROPIC_API_KEY;
1569
- const hasMinimax = !!process.env.MINIMAX_API_KEY;
1570
- const hasDeepSeek = !!process.env.DEEPSEEK_API_KEY;
1571
- const hasKimi = !!(process.env.KIMI_API_KEY || process.env.MOONSHOT_API_KEY);
1572
- const hasGlm = !!(process.env.GLM_API_KEY || process.env.ZHIPU_API_KEY);
1573
- const hasQwen = !!(process.env.QWEN_API_KEY || process.env.DASHSCOPE_API_KEY);
1574
- const hasOpenRouter = !!process.env.OPENROUTER_API_KEY;
1575
- const hasGemini = !!process.env.GEMINI_API_KEY;
1576
- const hasOllama = !!process.env.OLLAMA_BASE_URL;
1577
-
1578
- const llmProvider = hasOpenAI ? 'OpenAI' :
1579
- hasAnthropic ? 'Anthropic' :
1580
- hasOpenRouter ? 'OpenRouter' :
1581
- hasGemini ? 'Gemini' :
1582
- hasOllama ? 'Ollama' :
1583
- hasMinimax ? 'MiniMax' :
1584
- hasDeepSeek ? 'DeepSeek' :
1585
- hasKimi ? 'Kimi' :
1586
- hasGlm ? 'GLM' :
1587
- hasQwen ? 'Qwen' : null;
1588
-
1589
- if (llmProvider) {
1590
- s.step(0, 4, `LLM: ${llmProvider}`, 'ok');
1591
- initMinimax({ provider: llmProvider.toLowerCase() as any });
1592
- } else {
1593
- s.step(0, 4, 'LLM: 未配置', 'warn');
1594
- if (isNonInteractive) {
1595
- s.warn('未设置任何 LLM API Key,功能受限');
1596
- }
1597
- }
1598
-
1599
- const { keypair, did, name } = await bootstrapIdentity();
1600
- agentIdentity = { did, name, publicKey: Buffer.from(keypair.publicKey).toString('hex') };
1601
-
1602
- publishDID(name, keypair).then(({ cid, ipnsName }) => {
1603
- if (cid) agentIdentity!.cid = cid;
1604
- if (ipnsName) agentIdentity!.ipnsName = ipnsName;
1605
- }).catch(() => {});
1606
-
1607
- const verifier = createVerificationManager();
1608
- let comm: HyperswarmCommunicator | null = null;
1609
-
1610
- try {
1611
- if (mode === 'web') {
1612
- bootstrapP2P(verifier).then(c => {
1613
- comm = c;
1614
- const connections = c.getConnections();
1615
- if (connections.length > 0) {
1616
- agentIdentity!.peerId = connections[0].publicKey;
1617
- agentIdentity!.p2pChannel = 'bolloon-agent-harness';
1618
- }
1619
- }).catch(err => {
1620
- s.warn(`P2P Web 模式启动失败: ${err.message}`);
1621
- });
1622
- } else {
1623
- comm = await bootstrapP2P(verifier);
1624
- const connections = comm.getConnections();
1625
- if (connections.length > 0) {
1626
- agentIdentity.peerId = connections[0].publicKey;
1627
- agentIdentity.p2pChannel = 'bolloon-agent-harness';
1628
- }
1629
- }
1630
- } catch (err: any) {
1631
- s.warn(`P2P 初始化失败: ${err.message}`);
1632
- s.warn('将使用无 P2P 模式运行');
1633
- }
1634
-
1635
- await bootstrapIroh(keypair, name);
1636
-
1637
- // Bolloon Bootstrap: 启动扫描 + Context 收集 + 挂定时任务
1638
- // 失败静默 (主流程不被阻塞)
1639
- try {
1640
- const { bootstrapBolloon } = await import('./pi-ecosystem-judgment/human-value-pipeline.js');
1641
- s.info('正在 bootstrap bolloon 上下文...');
1642
- const bs = await bootstrapBolloon({ cwd: process.cwd() });
1643
- s.info(`Bootstrap 完成 (${bs.durationMs}ms, ${bs.errors.length} 个非致命错误)`);
1644
- } catch (err: any) {
1645
- s.warn(`Bootstrap 失败 (非致命, 主流程继续): ${err.message}`);
1646
- }
1647
-
1648
- s.divider();
1649
-
1650
- if (mode === 'web') {
1651
- const port = parseInt(process.env.PORT || '54188');
1652
- const { createWebServer, openBrowser } = await import('./web/server.js');
1653
-
1654
- s.info(`启动 Web 服务端口 ${port}...`);
1655
- const { port: actualPort } = await createWebServer(port);
1656
-
1657
- s.success(`浏览器已打开 → http://localhost:${actualPort}`);
1658
- openBrowser(`http://localhost:${actualPort}`);
1659
- } else if (isNonInteractive) {
1660
- console.log = originalLog;
1661
- console.info = originalInfo;
1662
- process.stdout.write = originalStdoutWrite;
1663
- s.info('执行命令...');
1664
- console.log();
1665
- await runNonInteractive(args, comm!);
1666
- comm?.stop();
1667
- process.exit(0);
1668
- } else {
1669
- s.section('对话模式');
1670
- console.log(`${GRAY}输入命令即可开始对话,示例:${RESET}\n`);
1671
- console.log(` ${CYAN}读取 想法.md${RESET} ${GRAY}- 读取文档${RESET}`);
1672
- console.log(` ${CYAN}总结 文档.md${RESET} ${GRAY}- 总结文档${RESET}`);
1673
- console.log(` ${CYAN}--agents${RESET} ${GRAY}- 查看 SubAgent${RESET}`);
1674
- console.log(` ${CYAN}--context${RESET} ${GRAY}- 查看全局上下文${RESET}`);
1675
- console.log(` ${CYAN}--delegate 任务 coding${RESET} ${GRAY}- 委派任务${RESET}`);
1676
- console.log(` ${CYAN}peers${RESET} ${GRAY}- 查看 P2P 节点${RESET}`);
1677
- console.log(` ${CYAN}iroh${RESET} ${GRAY}- 查看 iroh 状态${RESET}`);
1678
- console.log(` ${CYAN}退出${RESET} ${GRAY}- 结束对话${RESET}\n`);
1679
-
1680
- if (!isTuiMode) {
1681
- console.log = originalLog;
1682
- console.info = originalInfo;
1683
- process.stdout.write = originalStdoutWrite;
1684
- }
1685
-
1686
- startCLI(comm!);
1687
- }
1688
- }
1689
-
1690
- main().catch(e => { console.error('Fatal:', e); process.exit(1); });