@bolloon/bolloon-agent 0.1.36 → 0.1.38

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 (518) hide show
  1. package/package.json +2 -2
  2. package/.auto-evolve-calls +0 -1
  3. package/.last-auto-evolve-baseline +0 -1
  4. package/.playwright-mcp/page-2026-06-16T07-51-45-706Z.yml +0 -130
  5. package/.playwright-mcp/page-2026-06-16T07-56-44-116Z.yml +0 -131
  6. package/Bolloon.md +0 -144
  7. package/Dive-into/CITATION.cff +0 -17
  8. package/Dive-into/LICENSE +0 -25
  9. package/Dive-into/README.md +0 -598
  10. package/Dive-into/README_zh.md +0 -599
  11. package/Dive-into/assets/context.png +0 -0
  12. package/Dive-into/assets/extensibility.png +0 -0
  13. package/Dive-into/assets/iteration.png +0 -0
  14. package/Dive-into/assets/layered_architecture.png +0 -0
  15. package/Dive-into/assets/main_structure.png +0 -0
  16. package/Dive-into/assets/permission.png +0 -0
  17. package/Dive-into/assets/session_compact.png +0 -0
  18. package/Dive-into/assets/subagent.png +0 -0
  19. package/Dive-into/paper/Dive_into_Claude_Code.pdf +0 -0
  20. package/dist/agents/constraint-layer.js.map +0 -1
  21. package/dist/agents/pi-sdk.js.map +0 -1
  22. package/dist/agents/workflow-engine.js.map +0 -1
  23. package/dist/bollharness/src/index.js +0 -5
  24. package/dist/bollharness/src/scripts/checks/check_adr_plan_numbering.js +0 -6
  25. package/dist/bollharness/src/scripts/checks/check_api_types.js +0 -45
  26. package/dist/bollharness/src/scripts/checks/check_artifact_link.js +0 -146
  27. package/dist/bollharness/src/scripts/checks/check_bridge_deps.js +0 -6
  28. package/dist/bollharness/src/scripts/checks/check_bugfix_binding.js +0 -6
  29. package/dist/bollharness/src/scripts/checks/check_bugfix_binding_ci.js +0 -6
  30. package/dist/bollharness/src/scripts/checks/check_doc_file_references.js +0 -6
  31. package/dist/bollharness/src/scripts/checks/check_doc_freshness.js +0 -135
  32. package/dist/bollharness/src/scripts/checks/check_doc_links.js +0 -31
  33. package/dist/bollharness/src/scripts/checks/check_file_existence_claims.js +0 -6
  34. package/dist/bollharness/src/scripts/checks/check_fragment_integrity.js +0 -34
  35. package/dist/bollharness/src/scripts/checks/check_hook_installed.js +0 -63
  36. package/dist/bollharness/src/scripts/checks/check_issue_closure.js +0 -41
  37. package/dist/bollharness/src/scripts/checks/check_mcp_parity.js +0 -6
  38. package/dist/bollharness/src/scripts/checks/check_security.js +0 -48
  39. package/dist/bollharness/src/scripts/checks/check_skill_parity.js +0 -6
  40. package/dist/bollharness/src/scripts/checks/check_versions.js +0 -6
  41. package/dist/bollharness/src/scripts/checks/finding.js +0 -13
  42. package/dist/bollharness/src/scripts/checks/next_decision_number.js +0 -20
  43. package/dist/bollharness/src/scripts/checks/regenerate_magic_docs.js +0 -6
  44. package/dist/bollharness/src/scripts/ci/detect_rebaseline_triggers.js +0 -8
  45. package/dist/bollharness/src/scripts/ci/scan_subprocess_cfg.js +0 -8
  46. package/dist/bollharness/src/scripts/ci/scan_verify_artifacts.js +0 -8
  47. package/dist/bollharness/src/scripts/ci/scan_yaml_schema.js +0 -8
  48. package/dist/bollharness/src/scripts/context_router.js +0 -67
  49. package/dist/bollharness/src/scripts/deploy-guard.js +0 -157
  50. package/dist/bollharness/src/scripts/guard-feedback.js +0 -192
  51. package/dist/bollharness/src/scripts/guard_router.js +0 -158
  52. package/dist/bollharness/src/scripts/hooks/_hook_output.js +0 -6
  53. package/dist/bollharness/src/scripts/hooks/auto-python3.js +0 -6
  54. package/dist/bollharness/src/scripts/hooks/deploy-progress-on-session-end.js +0 -6
  55. package/dist/bollharness/src/scripts/hooks/failure-analyzer.js +0 -6
  56. package/dist/bollharness/src/scripts/hooks/gate-judgment-inject.js +0 -92
  57. package/dist/bollharness/src/scripts/hooks/gate-transition-judgment.js +0 -63
  58. package/dist/bollharness/src/scripts/hooks/inbox-ack.js +0 -6
  59. package/dist/bollharness/src/scripts/hooks/inbox-inject-on-start.js +0 -6
  60. package/dist/bollharness/src/scripts/hooks/inbox-validate.js +0 -6
  61. package/dist/bollharness/src/scripts/hooks/inbox-write-ledger.js +0 -6
  62. package/dist/bollharness/src/scripts/hooks/initializer-agent.js +0 -6
  63. package/dist/bollharness/src/scripts/hooks/loop-detection.js +0 -73
  64. package/dist/bollharness/src/scripts/hooks/owner-guard.js +0 -6
  65. package/dist/bollharness/src/scripts/hooks/precompact.js +0 -6
  66. package/dist/bollharness/src/scripts/hooks/review-agent-gatekeeper.js +0 -6
  67. package/dist/bollharness/src/scripts/hooks/risk-tracker.js +0 -108
  68. package/dist/bollharness/src/scripts/hooks/sanitize-on-read.js +0 -6
  69. package/dist/bollharness/src/scripts/hooks/session-reflection.js +0 -7
  70. package/dist/bollharness/src/scripts/hooks/session-start-magic-docs.js +0 -7
  71. package/dist/bollharness/src/scripts/hooks/session-start-reset-risk.js +0 -7
  72. package/dist/bollharness/src/scripts/hooks/session-start-toolkit-reminder.js +0 -7
  73. package/dist/bollharness/src/scripts/hooks/stop-evaluator.js +0 -157
  74. package/dist/bollharness/src/scripts/hooks/tool-call-counter.js +0 -6
  75. package/dist/bollharness/src/scripts/hooks/trace-analyzer.js +0 -10
  76. package/dist/bollharness/src/scripts/install/install-trust-token.js +0 -7
  77. package/dist/bollharness/src/scripts/install/multi_project_registry.js +0 -9
  78. package/dist/bollharness/src/scripts/install/phase2_auto.js +0 -21
  79. package/dist/bollharness/src/scripts/install/pre_commit_installer.js +0 -6
  80. package/dist/bollharness/src/scripts/install/tier_selector.js +0 -7
  81. package/dist/bollharness/src/scripts/install/transcript_miner.js +0 -7
  82. package/dist/bollharness/src/scripts/lib/claim_patterns.js +0 -10
  83. package/dist/bollharness/src/scripts/lib/sanitize_patterns.js +0 -12
  84. package/dist/bollharness/src/scripts/sanitize.js +0 -6
  85. package/dist/bollharness-integration/context-router-judgment.js.map +0 -1
  86. package/dist/bollharness-integration/context-router.js.map +0 -1
  87. package/dist/bollharness-integration/gate-state-machine.js.map +0 -1
  88. package/dist/bollharness-integration/gate-transition-hooks.js.map +0 -1
  89. package/dist/bollharness-integration/guard-checker.js.map +0 -1
  90. package/dist/bollharness-integration/index.js.map +0 -1
  91. package/dist/bollharness-integration/integration.js.map +0 -1
  92. package/dist/bollharness-integration/llm/pi-ai.d.ts +0 -60
  93. package/dist/bollharness-integration/pi-ecosystem-colony/index.d.ts +0 -153
  94. package/dist/bollharness-integration/pi-ecosystem-goals/index.d.ts +0 -136
  95. package/dist/bollharness-integration/pi-ecosystem-judgment/decision.d.ts +0 -117
  96. package/dist/bollharness-integration/pi-ecosystem-judgment/distillation.d.ts +0 -78
  97. package/dist/bollharness-integration/pi-ecosystem-judgment/index.d.ts +0 -139
  98. package/dist/bollharness-integration/pi-ecosystem-mcp/index.d.ts +0 -127
  99. package/dist/bollharness-integration/pi-ecosystem-subagents/index.d.ts +0 -95
  100. package/dist/bollharness-integration/skill-adapter.js.map +0 -1
  101. package/dist/constraint-runtime/src/_archive_helper.js +0 -9
  102. package/dist/constraint-runtime/src/agent/coordinator.js +0 -48
  103. package/dist/constraint-runtime/src/agent/index.js +0 -1
  104. package/dist/constraint-runtime/src/assistant/index.js +0 -12
  105. package/dist/constraint-runtime/src/bootstrap/index.js +0 -12
  106. package/dist/constraint-runtime/src/bootstrap_graph.js +0 -13
  107. package/dist/constraint-runtime/src/bridge/index.js +0 -12
  108. package/dist/constraint-runtime/src/buddy/index.js +0 -12
  109. package/dist/constraint-runtime/src/cli/index.js +0 -12
  110. package/dist/constraint-runtime/src/command_graph.js +0 -10
  111. package/dist/constraint-runtime/src/commands.js +0 -60
  112. package/dist/constraint-runtime/src/components/index.js +0 -12
  113. package/dist/constraint-runtime/src/constants/index.js +0 -12
  114. package/dist/constraint-runtime/src/constraint/budget.js +0 -22
  115. package/dist/constraint-runtime/src/constraint/budget.js.map +0 -1
  116. package/dist/constraint-runtime/src/constraint/index.js +0 -2
  117. package/dist/constraint-runtime/src/constraint/permission.js +0 -20
  118. package/dist/constraint-runtime/src/constraint/permission.js.map +0 -1
  119. package/dist/constraint-runtime/src/context.js +0 -30
  120. package/dist/constraint-runtime/src/coordinator/index.js +0 -12
  121. package/dist/constraint-runtime/src/cost_hook.js +0 -4
  122. package/dist/constraint-runtime/src/cost_tracker.js +0 -8
  123. package/dist/constraint-runtime/src/deferred_init.js +0 -10
  124. package/dist/constraint-runtime/src/direct_modes.js +0 -6
  125. package/dist/constraint-runtime/src/dynamic-tool-loader.js +0 -85
  126. package/dist/constraint-runtime/src/entrypoints/index.js +0 -12
  127. package/dist/constraint-runtime/src/execution_registry.js +0 -44
  128. package/dist/constraint-runtime/src/history.js +0 -9
  129. package/dist/constraint-runtime/src/hooks/index.js +0 -12
  130. package/dist/constraint-runtime/src/index.js +0 -26
  131. package/dist/constraint-runtime/src/ink.js +0 -4
  132. package/dist/constraint-runtime/src/keybindings/index.js +0 -12
  133. package/dist/constraint-runtime/src/memdir/index.js +0 -12
  134. package/dist/constraint-runtime/src/migrations/index.js +0 -12
  135. package/dist/constraint-runtime/src/models.js +0 -1
  136. package/dist/constraint-runtime/src/models.js.map +0 -1
  137. package/dist/constraint-runtime/src/moreright/index.js +0 -12
  138. package/dist/constraint-runtime/src/native_ts/index.js +0 -12
  139. package/dist/constraint-runtime/src/output_styles/index.js +0 -12
  140. package/dist/constraint-runtime/src/parity_audit.js +0 -12
  141. package/dist/constraint-runtime/src/plugins/index.js +0 -12
  142. package/dist/constraint-runtime/src/port_manifest.js +0 -11
  143. package/dist/constraint-runtime/src/prefetch.js +0 -9
  144. package/dist/constraint-runtime/src/query.js +0 -1
  145. package/dist/constraint-runtime/src/remote/index.js +0 -12
  146. package/dist/constraint-runtime/src/remote_runtime.js +0 -9
  147. package/dist/constraint-runtime/src/runtime/index.js +0 -1
  148. package/dist/constraint-runtime/src/runtime/session.js +0 -35
  149. package/dist/constraint-runtime/src/schemas/index.js +0 -12
  150. package/dist/constraint-runtime/src/screens/index.js +0 -12
  151. package/dist/constraint-runtime/src/server/index.js +0 -12
  152. package/dist/constraint-runtime/src/services/index.js +0 -12
  153. package/dist/constraint-runtime/src/session_store.js +0 -22
  154. package/dist/constraint-runtime/src/setup.js +0 -30
  155. package/dist/constraint-runtime/src/skills/index.js +0 -1
  156. package/dist/constraint-runtime/src/skills/skill-registry.js +0 -28
  157. package/dist/constraint-runtime/src/state/index.js +0 -12
  158. package/dist/constraint-runtime/src/system_init.js +0 -20
  159. package/dist/constraint-runtime/src/thinking/engine.js +0 -42
  160. package/dist/constraint-runtime/src/thinking/index.js +0 -1
  161. package/dist/constraint-runtime/src/tool_pool.js +0 -8
  162. package/dist/constraint-runtime/src/tools/OpenCLI/execAdapter.js +0 -7
  163. package/dist/constraint-runtime/src/tools/OpenCLI/listAdapters.js +0 -7
  164. package/dist/constraint-runtime/src/tools/OpenCLI/runCommand.js +0 -7
  165. package/dist/constraint-runtime/src/tools/PolymarketSDK/cancelOrder.js +0 -6
  166. package/dist/constraint-runtime/src/tools/PolymarketSDK/createOrder.js +0 -6
  167. package/dist/constraint-runtime/src/tools/PolymarketSDK/getMarket.js +0 -5
  168. package/dist/constraint-runtime/src/tools/PolymarketSDK/getOrders.js +0 -6
  169. package/dist/constraint-runtime/src/tools/PolymarketSDK/listMarkets.js +0 -4
  170. package/dist/constraint-runtime/src/tools/SafeSDK/confirmTransaction.js +0 -6
  171. package/dist/constraint-runtime/src/tools/SafeSDK/createTransaction.js +0 -8
  172. package/dist/constraint-runtime/src/tools/SafeSDK/deploySafe.js +0 -6
  173. package/dist/constraint-runtime/src/tools/SafeSDK/executeTransaction.js +0 -6
  174. package/dist/constraint-runtime/src/tools/SafeSDK/getBalance.js +0 -6
  175. package/dist/constraint-runtime/src/tools/SafeSDK/getPendingTransactions.js +0 -6
  176. package/dist/constraint-runtime/src/tools/SafeSDK/proposeTransaction.js +0 -6
  177. package/dist/constraint-runtime/src/tools/WalletTools/autoPay.js +0 -29
  178. package/dist/constraint-runtime/src/tools/WalletTools/createWallet.js +0 -10
  179. package/dist/constraint-runtime/src/tools/WalletTools/getBalance.js +0 -13
  180. package/dist/constraint-runtime/src/tools/WalletTools/importWallet.js +0 -22
  181. package/dist/constraint-runtime/src/tools/WalletTools/sendTransaction.js +0 -25
  182. package/dist/constraint-runtime/src/tools/WalletTools/signMessage.js +0 -10
  183. package/dist/constraint-runtime/src/tools/WalletTools/transferToken.js +0 -25
  184. package/dist/constraint-runtime/src/tools.js +0 -80
  185. package/dist/constraint-runtime/src/transcript.js +0 -19
  186. package/dist/constraint-runtime/src/types/index.js +0 -12
  187. package/dist/constraint-runtime/src/upstream_proxy/index.js +0 -12
  188. package/dist/constraint-runtime/src/utils/index.js +0 -12
  189. package/dist/constraint-runtime/src/vim/index.js +0 -12
  190. package/dist/constraint-runtime/src/voice/index.js +0 -12
  191. package/dist/constraints/index.js.map +0 -1
  192. package/dist/documents/reader.js.map +0 -1
  193. package/dist/llm/config-store.js.map +0 -1
  194. package/dist/llm/pi-ai.js.map +0 -1
  195. package/dist/network/agent-network.js.map +0 -1
  196. package/dist/network/iroh-integration.js.map +0 -1
  197. package/dist/network/iroh-transport.js.map +0 -1
  198. package/dist/network/p2p.js.map +0 -1
  199. package/dist/network/storage/adapters/json-adapter.js.map +0 -1
  200. package/dist/pi-ecosystem-colony/index.js.map +0 -1
  201. package/dist/pi-ecosystem-goals/index.js.map +0 -1
  202. package/dist/pi-ecosystem-judgment/decision.js.map +0 -1
  203. package/dist/pi-ecosystem-judgment/distillation.js.map +0 -1
  204. package/dist/pi-ecosystem-judgment/human-value-store.js.map +0 -1
  205. package/dist/pi-ecosystem-judgment/index.js.map +0 -1
  206. package/dist/pi-ecosystem-judgment/value-injection.js.map +0 -1
  207. package/dist/pi-ecosystem-mcp/index.js.map +0 -1
  208. package/dist/pi-ecosystem-subagents/index.js.map +0 -1
  209. package/dist/social/ant-colony/AdaptiveHeartbeat.js.map +0 -1
  210. package/dist/social/ant-colony/PheromoneEngine.js.map +0 -1
  211. package/dist/social/ant-colony/types.js.map +0 -1
  212. package/dist/social/channels/ChannelManager.js.map +0 -1
  213. package/dist/social/channels/DiapChannelBridge.js.map +0 -1
  214. package/dist/social/channels/InterestMatcher.js.map +0 -1
  215. package/dist/social/channels/types.js.map +0 -1
  216. package/dist/social/global-shared-context.js.map +0 -1
  217. package/dist/social/heartbeat.js.map +0 -1
  218. package/lefthook.yml +0 -33
  219. package/scripts/auto-evolve-loop.ts +0 -481
  220. package/scripts/build-web.ts +0 -116
  221. package/scripts/diff-reviewer.ts +0 -159
  222. package/scripts/validate-system-prompt.ts +0 -142
  223. package/scripts/weekly-report.ts +0 -364
  224. package/src/agents/agent-manifest-protocol.ts +0 -117
  225. package/src/agents/constraint-layer.ts +0 -309
  226. package/src/agents/iroh-secret.ts +0 -32
  227. package/src/agents/p2p-chat-tools.ts +0 -383
  228. package/src/agents/p2p-document-tools.ts +0 -347
  229. package/src/agents/permission-mode.ts +0 -127
  230. package/src/agents/pi-sdk.ts +0 -2895
  231. package/src/agents/pre-tool-validator.ts +0 -213
  232. package/src/agents/protocol.ts +0 -398
  233. package/src/agents/shell-guard.ts +0 -417
  234. package/src/agents/shell-tool.ts +0 -103
  235. package/src/agents/skill-loader.ts +0 -202
  236. package/src/agents/subagent-manager.ts +0 -553
  237. package/src/agents/workflow-engine.ts +0 -332
  238. package/src/agents/workflow-pivot-loop.ts +0 -766
  239. package/src/bollharness/.sanitize-report.json +0 -13
  240. package/src/bollharness/CLAUDE.md +0 -73
  241. package/src/bollharness/LICENSE +0 -21
  242. package/src/bollharness/README.md +0 -143
  243. package/src/bollharness/README.zh-CN.md +0 -131
  244. package/src/bollharness/package.json +0 -20
  245. package/src/bollharness/reference/SOURCE-COMMIT.txt +0 -3
  246. package/src/bollharness/reference/boll-reference/scripts/hooks/.sanitize-report.json +0 -12
  247. package/src/bollharness/reference/boll-reference/scripts/hooks/find-boll-root.sh +0 -27
  248. package/src/bollharness/reference/boll-reference/scripts/hooks/precompact.sh +0 -57
  249. package/src/bollharness/reference/boll-reference/scripts/hooks/stop-evaluator.md +0 -57
  250. package/src/bollharness/schemas/metrics-jsonl-allowlist.json +0 -67
  251. package/src/bollharness/scripts/checks/next_decision_number.sh +0 -48
  252. package/src/bollharness/scripts/ci/count-components.sh +0 -65
  253. package/src/bollharness/scripts/context-fragments/artifact-linkage.md +0 -14
  254. package/src/bollharness/scripts/context-fragments/auth-consumers.md +0 -17
  255. package/src/bollharness/scripts/context-fragments/bridge-constitution.md +0 -13
  256. package/src/bollharness/scripts/context-fragments/catalyst-distributed.md +0 -18
  257. package/src/bollharness/scripts/context-fragments/closure-checklist.md +0 -13
  258. package/src/bollharness/scripts/context-fragments/contract-consumers.md +0 -15
  259. package/src/bollharness/scripts/context-fragments/db-shared-structures.md +0 -15
  260. package/src/bollharness/scripts/context-fragments/fixed-three-layers.md +0 -19
  261. package/src/bollharness/scripts/context-fragments/general-dev-principles.md +0 -11
  262. package/src/bollharness/scripts/context-fragments/issue-first.md +0 -8
  263. package/src/bollharness/scripts/context-fragments/mcp-parity.md +0 -16
  264. package/src/bollharness/scripts/context-fragments/pi-agent-operations.md +0 -108
  265. package/src/bollharness/scripts/context-fragments/protocol-consumers.md +0 -15
  266. package/src/bollharness/scripts/context-fragments/run-events-consumers.md +0 -15
  267. package/src/bollharness/scripts/context-fragments/scene-fidelity.md +0 -13
  268. package/src/bollharness/scripts/context-fragments/truth-source-hierarchy.md +0 -15
  269. package/src/bollharness/scripts/context-fragments/two-language.md +0 -15
  270. package/src/bollharness/scripts/context-fragments/version-sources.md +0 -14
  271. package/src/bollharness/scripts/hooks/find-project-root.sh +0 -47
  272. package/src/bollharness/scripts/hooks/inbox-poll.sh +0 -78
  273. package/src/bollharness/scripts/hooks/precompact.sh +0 -56
  274. package/src/bollharness/scripts/hooks/stop-evaluator.md +0 -83
  275. package/src/bollharness/scripts/sync-from-upstream.sh +0 -281
  276. package/src/bollharness/src/index.ts +0 -5
  277. package/src/bollharness/src/scripts/checks/check_adr_plan_numbering.ts +0 -11
  278. package/src/bollharness/src/scripts/checks/check_api_types.ts +0 -52
  279. package/src/bollharness/src/scripts/checks/check_artifact_link.ts +0 -156
  280. package/src/bollharness/src/scripts/checks/check_bridge_deps.ts +0 -11
  281. package/src/bollharness/src/scripts/checks/check_bugfix_binding.ts +0 -11
  282. package/src/bollharness/src/scripts/checks/check_bugfix_binding_ci.ts +0 -11
  283. package/src/bollharness/src/scripts/checks/check_doc_file_references.ts +0 -11
  284. package/src/bollharness/src/scripts/checks/check_doc_freshness.ts +0 -141
  285. package/src/bollharness/src/scripts/checks/check_doc_links.ts +0 -36
  286. package/src/bollharness/src/scripts/checks/check_file_existence_claims.ts +0 -11
  287. package/src/bollharness/src/scripts/checks/check_fragment_integrity.ts +0 -40
  288. package/src/bollharness/src/scripts/checks/check_hook_installed.ts +0 -70
  289. package/src/bollharness/src/scripts/checks/check_issue_closure.ts +0 -51
  290. package/src/bollharness/src/scripts/checks/check_mcp_parity.ts +0 -11
  291. package/src/bollharness/src/scripts/checks/check_security.ts +0 -54
  292. package/src/bollharness/src/scripts/checks/check_skill_parity.ts +0 -11
  293. package/src/bollharness/src/scripts/checks/check_versions.ts +0 -11
  294. package/src/bollharness/src/scripts/checks/finding.ts +0 -35
  295. package/src/bollharness/src/scripts/checks/next_decision_number.ts +0 -24
  296. package/src/bollharness/src/scripts/checks/regenerate_magic_docs.ts +0 -11
  297. package/src/bollharness/src/scripts/ci/detect_rebaseline_triggers.ts +0 -14
  298. package/src/bollharness/src/scripts/ci/scan_subprocess_cfg.ts +0 -14
  299. package/src/bollharness/src/scripts/ci/scan_verify_artifacts.ts +0 -14
  300. package/src/bollharness/src/scripts/ci/scan_yaml_schema.ts +0 -14
  301. package/src/bollharness/src/scripts/context_router.ts +0 -76
  302. package/src/bollharness/src/scripts/deploy-guard.ts +0 -182
  303. package/src/bollharness/src/scripts/guard-feedback.ts +0 -215
  304. package/src/bollharness/src/scripts/guard_router.ts +0 -194
  305. package/src/bollharness/src/scripts/hooks/_hook_output.js +0 -3
  306. package/src/bollharness/src/scripts/hooks/_hook_output.ts +0 -11
  307. package/src/bollharness/src/scripts/hooks/auto-python3.ts +0 -10
  308. package/src/bollharness/src/scripts/hooks/deploy-progress-on-session-end.ts +0 -10
  309. package/src/bollharness/src/scripts/hooks/failure-analyzer.ts +0 -10
  310. package/src/bollharness/src/scripts/hooks/gate-judgment-inject.ts +0 -111
  311. package/src/bollharness/src/scripts/hooks/gate-transition-judgment.ts +0 -74
  312. package/src/bollharness/src/scripts/hooks/inbox-ack.ts +0 -10
  313. package/src/bollharness/src/scripts/hooks/inbox-inject-on-start.ts +0 -10
  314. package/src/bollharness/src/scripts/hooks/inbox-validate.ts +0 -10
  315. package/src/bollharness/src/scripts/hooks/inbox-write-ledger.ts +0 -10
  316. package/src/bollharness/src/scripts/hooks/initializer-agent.ts +0 -10
  317. package/src/bollharness/src/scripts/hooks/loop-detection.ts +0 -83
  318. package/src/bollharness/src/scripts/hooks/owner-guard.ts +0 -10
  319. package/src/bollharness/src/scripts/hooks/precompact.ts +0 -10
  320. package/src/bollharness/src/scripts/hooks/review-agent-gatekeeper.ts +0 -10
  321. package/src/bollharness/src/scripts/hooks/risk-tracker.ts +0 -121
  322. package/src/bollharness/src/scripts/hooks/sanitize-on-read.ts +0 -10
  323. package/src/bollharness/src/scripts/hooks/session-reflection.ts +0 -12
  324. package/src/bollharness/src/scripts/hooks/session-start-magic-docs.ts +0 -12
  325. package/src/bollharness/src/scripts/hooks/session-start-reset-risk.ts +0 -12
  326. package/src/bollharness/src/scripts/hooks/session-start-toolkit-reminder.ts +0 -12
  327. package/src/bollharness/src/scripts/hooks/stop-evaluator.ts +0 -164
  328. package/src/bollharness/src/scripts/hooks/tool-call-counter.ts +0 -10
  329. package/src/bollharness/src/scripts/hooks/trace-analyzer.ts +0 -14
  330. package/src/bollharness/src/scripts/install/install-trust-token.ts +0 -13
  331. package/src/bollharness/src/scripts/install/multi_project_registry.ts +0 -13
  332. package/src/bollharness/src/scripts/install/phase2_auto.ts +0 -28
  333. package/src/bollharness/src/scripts/install/pre_commit_installer.ts +0 -10
  334. package/src/bollharness/src/scripts/install/tier_selector.ts +0 -10
  335. package/src/bollharness/src/scripts/install/transcript_miner.ts +0 -13
  336. package/src/bollharness/src/scripts/lib/claim_patterns.ts +0 -11
  337. package/src/bollharness/src/scripts/lib/sanitize_patterns.ts +0 -13
  338. package/src/bollharness/src/scripts/sanitize.ts +0 -9
  339. package/src/bollharness/templates/persona/default.json +0 -19
  340. package/src/bollharness/templates/scaffold/.gitignore.append +0 -16
  341. package/src/bollharness/templates/scaffold/CLAUDE.md +0 -89
  342. package/src/bollharness-integration/channel-judgment-engine.ts +0 -634
  343. package/src/bollharness-integration/context-chain-router.ts +0 -474
  344. package/src/bollharness-integration/context-router-judgment.ts +0 -339
  345. package/src/bollharness-integration/context-router.ts +0 -583
  346. package/src/bollharness-integration/gate-state-machine.ts +0 -444
  347. package/src/bollharness-integration/gate-transition-hooks.ts +0 -137
  348. package/src/bollharness-integration/guard-checker.ts +0 -451
  349. package/src/bollharness-integration/index.ts +0 -195
  350. package/src/bollharness-integration/integration.ts +0 -538
  351. package/src/bollharness-integration/judgment-prompts.yaml +0 -535
  352. package/src/bollharness-integration/llm-judgment-engine.ts +0 -712
  353. package/src/bollharness-integration/skill-adapter.ts +0 -646
  354. package/src/bootstrap/bootstrap.ts +0 -135
  355. package/src/bootstrap/context-collector.ts +0 -371
  356. package/src/bootstrap/context-hierarchy.ts +0 -283
  357. package/src/bootstrap/lifecycle-hooks.ts +0 -289
  358. package/src/bootstrap/project-context.ts +0 -171
  359. package/src/cli/interface.ts +0 -211
  360. package/src/cli-entry.ts +0 -304
  361. package/src/constraints/index.ts +0 -6
  362. package/src/context-compaction/auto-compact.ts +0 -153
  363. package/src/context-compaction/budget-gate.ts +0 -32
  364. package/src/context-compaction/budget-reduce.ts +0 -37
  365. package/src/context-compaction/context-collapse.ts +0 -72
  366. package/src/context-compaction/index.ts +0 -24
  367. package/src/context-compaction/microcompact.ts +0 -54
  368. package/src/context-compaction/pipeline.ts +0 -133
  369. package/src/context-compaction/snip.ts +0 -51
  370. package/src/context-compaction/token-estimator.ts +0 -36
  371. package/src/context-compaction/types.ts +0 -99
  372. package/src/documents/reader.ts +0 -85
  373. package/src/documents/store.ts +0 -252
  374. package/src/electron-preload.ts +0 -25
  375. package/src/electron.ts +0 -200
  376. package/src/heartbeat/DaemonManager.ts +0 -283
  377. package/src/heartbeat/HealthMonitor.ts +0 -317
  378. package/src/heartbeat/StartupVerifier.ts +0 -223
  379. package/src/heartbeat/Watchdog.ts +0 -208
  380. package/src/heartbeat/index.ts +0 -109
  381. package/src/heartbeat/self-improve-bus.ts +0 -110
  382. package/src/heartbeat/types.ts +0 -82
  383. package/src/index.ts +0 -1724
  384. package/src/llm/audio-config-store.ts +0 -246
  385. package/src/llm/config-store.ts +0 -400
  386. package/src/llm/llm-judgment-client.ts +0 -471
  387. package/src/llm/pi-ai.ts +0 -653
  388. package/src/llm/system-prompt/health.ts +0 -159
  389. package/src/llm/system-prompt/layers/channel/local.md +0 -14
  390. package/src/llm/system-prompt/layers/channel/p2p-agent.md +0 -18
  391. package/src/llm/system-prompt/layers/channel/p2p-visitor.md +0 -19
  392. package/src/llm/system-prompt/layers/core/artifacts_storage.md +0 -89
  393. package/src/llm/system-prompt/layers/core/evenhandedness.md +0 -21
  394. package/src/llm/system-prompt/layers/core/hibs_reminders.md +0 -15
  395. package/src/llm/system-prompt/layers/core/identity.md +0 -37
  396. package/src/llm/system-prompt/layers/core/knowledge.md +0 -17
  397. package/src/llm/system-prompt/layers/core/memory_system.md +0 -12
  398. package/src/llm/system-prompt/layers/core/network_filesystem.md +0 -28
  399. package/src/llm/system-prompt/layers/core/refusal.md +0 -37
  400. package/src/llm/system-prompt/layers/core/tone.md +0 -31
  401. package/src/llm/system-prompt/layers/core/tools.thin.md +0 -13
  402. package/src/llm/system-prompt/layers/core/wellbeing.md +0 -41
  403. package/src/llm/system-prompt/layers/role/architect.md +0 -20
  404. package/src/llm/system-prompt/layers/role/expert.md +0 -19
  405. package/src/llm/system-prompt/layers/role/implementer.md +0 -15
  406. package/src/llm/system-prompt/layers/role/security.md +0 -15
  407. package/src/llm/system-prompt/layers/tool/artifacts.md +0 -72
  408. package/src/llm/system-prompt/layers/tool/bash.md +0 -25
  409. package/src/llm/system-prompt/layers/tool/hibs_api.md +0 -171
  410. package/src/llm/system-prompt/layers/tool/image_search.md +0 -70
  411. package/src/llm/system-prompt/layers/tool/manifest.md +0 -89
  412. package/src/llm/system-prompt/layers/tool/mcp_apps.md +0 -53
  413. package/src/llm/system-prompt/layers/tool/web_search.md +0 -83
  414. package/src/llm/system-prompt/registry.ts +0 -325
  415. package/src/llm/system-prompt/strip-hibsml.ts +0 -52
  416. package/src/llm/tool-manifest/ask_user_input.ts +0 -37
  417. package/src/llm/tool-manifest/bash.ts +0 -25
  418. package/src/llm/tool-manifest/create_file.ts +0 -26
  419. package/src/llm/tool-manifest/fetch_sports_data.ts +0 -28
  420. package/src/llm/tool-manifest/image_search.ts +0 -26
  421. package/src/llm/tool-manifest/index.ts +0 -88
  422. package/src/llm/tool-manifest/mcp.ts +0 -46
  423. package/src/llm/tool-manifest/message_compose.ts +0 -33
  424. package/src/llm/tool-manifest/places.ts +0 -86
  425. package/src/llm/tool-manifest/present_files.ts +0 -23
  426. package/src/llm/tool-manifest/recipe.ts +0 -42
  427. package/src/llm/tool-manifest/recommend_apps.ts +0 -25
  428. package/src/llm/tool-manifest/str_replace.ts +0 -29
  429. package/src/llm/tool-manifest/types.ts +0 -52
  430. package/src/llm/tool-manifest/view.ts +0 -26
  431. package/src/llm/tool-manifest/weather.ts +0 -29
  432. package/src/llm/tool-manifest/web.ts +0 -54
  433. package/src/llm/video-config-store.ts +0 -257
  434. package/src/network/agent-network.ts +0 -800
  435. package/src/network/hybrid-messenger.ts +0 -199
  436. package/src/network/iroh-bootstrap.ts +0 -57
  437. package/src/network/iroh-discovery.ts +0 -208
  438. package/src/network/iroh-integration.ts +0 -158
  439. package/src/network/iroh-transport.ts +0 -637
  440. package/src/network/known-peers.ts +0 -102
  441. package/src/network/p2p-direct.ts +0 -262
  442. package/src/network/p2p-secret.ts +0 -153
  443. package/src/network/p2p.ts +0 -964
  444. package/src/network/source-intent-broadcaster.ts +0 -242
  445. package/src/network/source-intent.ts +0 -167
  446. package/src/network/storage/adapters/json-adapter.ts +0 -454
  447. package/src/network/storage/index.ts +0 -203
  448. package/src/network/storage/types.ts +0 -166
  449. package/src/security/builtin-guards.ts +0 -162
  450. package/src/security/context-router-tool.ts +0 -122
  451. package/src/security/input-scanner.ts +0 -287
  452. package/src/security/react-harness.ts +0 -177
  453. package/src/security/tool-gate.ts +0 -294
  454. package/src/social/ant-colony/index.js +0 -19
  455. package/src/social/channels/ChannelManager.ts +0 -485
  456. package/src/social/channels/DiapChannelBridge.ts +0 -501
  457. package/src/social/channels/InterestMatcher.ts +0 -189
  458. package/src/social/channels/agent-workflow-config.json +0 -214
  459. package/src/social/channels/agent-workflow-config.yaml +0 -334
  460. package/src/social/channels/channel-agent-session.ts +0 -407
  461. package/src/social/channels/channel-heartbeat-agent.ts +0 -622
  462. package/src/social/channels/diap-doc-parser.ts +0 -282
  463. package/src/social/channels/harness-workflow-integrator.ts +0 -594
  464. package/src/social/channels/index.ts +0 -22
  465. package/src/social/channels/types.ts +0 -115
  466. package/src/social/global-shared-context.ts +0 -506
  467. package/src/social/heartbeat.ts +0 -1057
  468. package/src/social/persona/enhanced-persona.ts +0 -359
  469. package/src/types.d.ts +0 -12
  470. package/src/utils/auto-evolve-policy.ts +0 -138
  471. package/src/utils/auto-update.ts +0 -482
  472. package/src/utils/clamp.ts +0 -5
  473. package/src/web/agent-delegate-server.ts +0 -148
  474. package/src/web/api-config.html +0 -520
  475. package/src/web/client.js +0 -2352
  476. package/src/web/client.ts +0 -4326
  477. package/src/web/components/p2p/P2PModal.tsx +0 -416
  478. package/src/web/components/p2p/index.ts +0 -566
  479. package/src/web/components/p2p/index.tsx +0 -297
  480. package/src/web/components/p2p/p2p-connection.ts +0 -338
  481. package/src/web/components/p2p/p2p-identity.ts +0 -92
  482. package/src/web/components/p2p/p2p-manager.ts +0 -147
  483. package/src/web/components/p2p/p2p-messages.ts +0 -219
  484. package/src/web/components/p2p/p2p-modal.ts +0 -685
  485. package/src/web/components/p2p/p2p-store-memory.ts +0 -162
  486. package/src/web/components/p2p/p2p-tools.ts +0 -315
  487. package/src/web/components/p2p/types.ts +0 -170
  488. package/src/web/components/wallet-viem.mjs +0 -118
  489. package/src/web/design.md +0 -99
  490. package/src/web/icons/apple-touch-icon.png +0 -0
  491. package/src/web/icons/favicon-16x16.png +0 -0
  492. package/src/web/icons/favicon-192x192.png +0 -0
  493. package/src/web/icons/favicon-32x32.png +0 -0
  494. package/src/web/icons/favicon-48x48.png +0 -0
  495. package/src/web/icons/favicon-512x512.png +0 -0
  496. package/src/web/icons/favicon.icns +0 -0
  497. package/src/web/icons/favicon.ico +0 -0
  498. package/src/web/icons/icon.png +0 -0
  499. package/src/web/icons/image.png +0 -0
  500. package/src/web/index.html +0 -373
  501. package/src/web/iroh-delegate-transport.ts +0 -139
  502. package/src/web/manifest.json +0 -21
  503. package/src/web/server.ts +0 -5731
  504. package/src/web/style.css +0 -4737
  505. package/src/web/ui/message-renderer.ts +0 -540
  506. package/src/web/ui/step-timeline.ts +0 -394
  507. package/staging/auto-evolve/clean-001/.review-verdict +0 -9
  508. package/staging/auto-evolve/clean-001/clean-001.patch +0 -14
  509. package/staging/auto-evolve/e2e-001/.patch-id +0 -1
  510. package/staging/auto-evolve/e2e-001/.review-verdict +0 -12
  511. package/staging/auto-evolve/e2e-001/e2e-001.patch +0 -11
  512. package/staging/auto-evolve/test-bad/.review-verdict +0 -12
  513. package/staging/auto-evolve/test-bad/test-bad.patch +0 -11
  514. package/test-results/.last-run.json +0 -6
  515. package/test-results/src-test-web-loop-status-b-5734c-atus-bar-/346/230/276/347/244/272-spinner-/344/270/215/346/230/276/347/244/272/345/276/252/347/216/257/350/256/241/346/225/260/error-context.md +0 -285
  516. package/tsconfig.cli.json +0 -16
  517. package/tsconfig.electron.json +0 -20
  518. package/tsconfig.json +0 -18
@@ -1,766 +0,0 @@
1
- /**
2
- * WorkflowPivotLoop - Robust Agent Loop with Adaptive Iteration Control
3
- *
4
- * Based on the architecture pattern:
5
- * 1. Loop interrupted by max iterations
6
- * 2. Model decides via pending_tool_uses (empty = normal completion)
7
- * 3. Conditional routing based on tool call presence
8
- *
9
- * Key improvements over simple ReAct:
10
- * - Dynamic loop length based on task complexity
11
- * - Multi-dimensional exit conditions
12
- * - Consecutive invalid iteration detection
13
- * - Token budget awareness
14
- */
15
-
16
- import type { Tool, ToolResult, StreamCallback, StreamEvent } from './pi-sdk.js';
17
-
18
- export interface PivotLoopConfig {
19
- maxIterations: number;
20
- minIterations?: number;
21
- qualityThreshold?: number;
22
- maxConsecutiveNoProgress?: number;
23
- maxTokenBudget?: number;
24
- complexity?: TaskComplexity;
25
- }
26
-
27
- export interface PivotLoopState {
28
- iteration: number;
29
- totalTokens: number;
30
- toolCallsCount: number;
31
- consecutiveNoProgress: number;
32
- qualityScores: number[];
33
- pendingToolUses: ToolDefinition[];
34
- lastMeaningfulWork: number;
35
- }
36
-
37
- export interface ToolDefinition {
38
- name: string;
39
- description: string;
40
- parameters: Record<string, string>;
41
- args?: Record<string, string>;
42
- }
43
-
44
- export interface LoopResult {
45
- success: boolean;
46
- response: string;
47
- iterations: number;
48
- toolCalls: number;
49
- qualityScore: number;
50
- exitReason: ExitReason;
51
- state: PivotLoopState;
52
- }
53
-
54
- export type ExitReason =
55
- | 'max_iterations'
56
- | 'no_pending_tools'
57
- | 'quality_threshold_met'
58
- | 'no_progress_exhausted'
59
- | 'token_budget_exceeded'
60
- | 'min_iterations_not_met'
61
- | 'error';
62
-
63
- export type TaskComplexity = 'simple' | 'moderate' | 'complex';
64
-
65
- export interface TaskProfile {
66
- complexity: TaskComplexity;
67
- estimatedSteps: number;
68
- suggestedMaxIterations: number;
69
- tokenBudget: number;
70
- }
71
-
72
- /**
73
- * Analyze input to determine task complexity
74
- */
75
- function analyzeTaskComplexity(input: string): TaskProfile {
76
- const inputLower = input.toLowerCase();
77
- const inputLength = input.length;
78
-
79
- // Simple task indicators
80
- const simpleIndicators = [
81
- '读取', '查看', '显示', '列出', '获取', 'what is', 'show me',
82
- 'list', 'get', 'show', 'read', 'view', 'display'
83
- ];
84
-
85
- // Complex task indicators
86
- const complexIndicators = [
87
- '分析', '比较', '改进', '优化', '重构', '实现', '设计', '创建',
88
- 'analyze', 'compare', 'improve', 'optimize', 'refactor', 'implement',
89
- 'design', 'create', 'build', 'develop'
90
- ];
91
-
92
- // Question patterns suggest moderate complexity
93
- const questionPatterns = [
94
- '如何', '怎么', '为什么', '什么', 'which', 'how', 'why', 'what', '?'
95
- ];
96
-
97
- const simpleCount = simpleIndicators.filter(i => inputLower.includes(i)).length;
98
- const complexCount = complexIndicators.filter(i => inputLower.includes(i)).length;
99
- const questionCount = questionPatterns.filter(p => inputLower.includes(p)).length;
100
-
101
- let complexity: TaskComplexity;
102
- let estimatedSteps: number;
103
-
104
- if (complexCount > simpleCount && complexCount > 1) {
105
- complexity = 'complex';
106
- estimatedSteps = 5 + complexCount * 2;
107
- } else if (questionCount > 2 || (simpleCount > 0 && complexCount > 0)) {
108
- complexity = 'moderate';
109
- estimatedSteps = 3 + questionCount;
110
- } else if (inputLength < 50 && simpleCount > 0) {
111
- complexity = 'simple';
112
- estimatedSteps = 1 + simpleCount;
113
- } else if (complexCount > 0) {
114
- complexity = 'complex';
115
- estimatedSteps = 4 + complexCount;
116
- } else {
117
- complexity = 'moderate';
118
- estimatedSteps = 3;
119
- }
120
-
121
- // Adjust based on input length (longer inputs often mean more complex tasks)
122
- if (inputLength > 500 && complexity !== 'complex') {
123
- complexity = 'moderate';
124
- estimatedSteps = Math.max(estimatedSteps, 4);
125
- }
126
-
127
- // Suggested max iterations: 2-3x estimated steps for safety margin
128
- const suggestedMaxIterations = Math.min(Math.max(estimatedSteps * 3, 10), 100);
129
- const tokenBudget = estimatedSteps * 800; // ~800 tokens per step estimate
130
-
131
- return { complexity, estimatedSteps, suggestedMaxIterations, tokenBudget };
132
- }
133
-
134
- /**
135
- * WorkflowPivotLoop - Main loop controller
136
- */
137
- export class WorkflowPivotLoop {
138
- private config: Required<PivotLoopConfig>;
139
- private state: PivotLoopState;
140
- private tools: Map<string, Tool>;
141
- private messageHistory: Array<{ role: string; content: string; toolCall?: ToolDefinition; toolResult?: ToolResult }>;
142
- private streamCallback?: StreamCallback;
143
-
144
- constructor(config: PivotLoopConfig) {
145
- this.tools = new Map();
146
-
147
- // Default configuration based on task complexity if not provided
148
- const defaults: Required<PivotLoopConfig> = {
149
- maxIterations: config.maxIterations || 50,
150
- minIterations: config.minIterations || 2,
151
- qualityThreshold: config.qualityThreshold || 0.7,
152
- maxConsecutiveNoProgress: config.maxConsecutiveNoProgress || 5,
153
- maxTokenBudget: config.maxTokenBudget || 50000,
154
- complexity: config.complexity || 'moderate'
155
- };
156
-
157
- this.config = defaults;
158
-
159
- this.state = this.createInitialState();
160
- this.messageHistory = [];
161
- }
162
-
163
- private createInitialState(): PivotLoopState {
164
- return {
165
- iteration: 0,
166
- totalTokens: 0,
167
- toolCallsCount: 0,
168
- consecutiveNoProgress: 0,
169
- qualityScores: [],
170
- pendingToolUses: [],
171
- lastMeaningfulWork: 0
172
- };
173
- }
174
-
175
- /**
176
- * Register a tool for use in the loop
177
- */
178
- registerTool(tool: Tool): void {
179
- this.tools.set(tool.name, tool);
180
- }
181
-
182
- /**
183
- * Register multiple tools at once
184
- */
185
- registerTools(tools: Tool[]): void {
186
- for (const tool of tools) {
187
- this.registerTool(tool);
188
- }
189
- }
190
-
191
- /**
192
- * Execute the pivot loop
193
- */
194
- async execute(
195
- input: string,
196
- llm: LLMInterface,
197
- systemPrompt: string,
198
- streamCallback?: StreamCallback
199
- ): Promise<LoopResult> {
200
- this.streamCallback = streamCallback;
201
- this.state = this.createInitialState();
202
- this.messageHistory = [{ role: 'user', content: input }];
203
-
204
- // Analyze task complexity and adapt config
205
- const taskProfile = analyzeTaskComplexity(input);
206
- const effectiveConfig = this.adaptConfigForTask(taskProfile);
207
-
208
- this.emit({
209
- type: 'status',
210
- content: `🔍 任务复杂度: ${taskProfile.complexity} (预估 ${taskProfile.estimatedSteps} 步)`,
211
- tool: 'system'
212
- });
213
-
214
- this.emit({
215
- type: 'status',
216
- content: `⚙️ 动态配置: maxIterations=${effectiveConfig.maxIterations}, tokenBudget=${effectiveConfig.maxTokenBudget}`,
217
- tool: 'system'
218
- });
219
-
220
- let response = '';
221
-
222
- while (this.shouldContinue(effectiveConfig)) {
223
- this.state.iteration++;
224
-
225
- this.emit({
226
- type: 'status',
227
- content: `🔄 循环 ${this.state.iteration}/${effectiveConfig.maxIterations}`,
228
- tool: 'loop'
229
- });
230
-
231
- // Build context for LLM
232
- const context = this.buildContext();
233
- const fullPrompt = `${systemPrompt}\n\n${context}`;
234
-
235
- try {
236
- // Call LLM
237
- const llmResponse = await llm.chat(context, systemPrompt);
238
- const reply = llmResponse.reply.trim();
239
-
240
- this.emit({ type: 'token', content: reply.substring(0, 100) });
241
-
242
- // Estimate token usage
243
- this.state.totalTokens += this.estimateTokens(fullPrompt) + this.estimateTokens(reply);
244
-
245
- // Check token budget
246
- if (this.state.totalTokens > effectiveConfig.maxTokenBudget) {
247
- this.emit({
248
- type: 'error',
249
- content: '⚠️ Token 预算超支,中断循环'
250
- });
251
- return this.createResult(false, response, 'token_budget_exceeded');
252
- }
253
-
254
- // Check if this is a final response (no tool calls)
255
- const pendingTools = this.extractPendingToolUses(reply);
256
-
257
- if (pendingTools.length === 0) {
258
- // No pending tool uses - this is a normal completion
259
- this.state.pendingToolUses = [];
260
-
261
- // Evaluate quality before accepting
262
- const quality = this.evaluateQuality(reply);
263
- this.state.qualityScores.push(quality);
264
-
265
- this.emit({
266
- type: 'status',
267
- content: `✅ 检测到最终回复 (质量: ${(quality * 10).toFixed(1)}/10)`,
268
- tool: 'system'
269
- });
270
-
271
- // Check if quality threshold met
272
- if (quality >= effectiveConfig.qualityThreshold) {
273
- response = reply;
274
- return this.createResult(true, reply, 'quality_threshold_met');
275
- }
276
-
277
- // Quality not met but no more tools to call
278
- // Accept response if we've done minimum iterations
279
- if (this.state.iteration >= effectiveConfig.minIterations) {
280
- response = reply;
281
- return this.createResult(true, reply, 'no_pending_tools');
282
- }
283
-
284
- // Too early, continue to see if we can improve
285
- this.state.consecutiveNoProgress++;
286
- this.emit({
287
- type: 'status',
288
- content: `📊 质量未达标 (${(quality * 10).toFixed(1)}/${(effectiveConfig.qualityThreshold * 10).toFixed(1)}),继续循环`,
289
- tool: 'system'
290
- });
291
- continue;
292
- }
293
-
294
- // We have pending tool uses - execute them
295
- this.state.pendingToolUses = pendingTools;
296
- this.state.lastMeaningfulWork = this.state.iteration;
297
- this.state.consecutiveNoProgress = 0;
298
-
299
- for (const toolCall of pendingTools) {
300
- this.state.toolCallsCount++;
301
-
302
- const tool = this.tools.get(toolCall.name);
303
- if (!tool) {
304
- this.emit({
305
- type: 'error',
306
- content: `❌ 未知工具: ${toolCall.name}`
307
- });
308
- // 2026-06-15: step-timeline — 未知工具也开/关一个 step 节点
309
- this.emit({
310
- type: 'step_start',
311
- content: `未知工具 ${toolCall.name}`,
312
- tool: toolCall.name,
313
- args: toolCall.args || {},
314
- });
315
- this.emit({
316
- type: 'step_error',
317
- content: `未知工具 ${toolCall.name}`,
318
- tool: toolCall.name,
319
- error: 'Unknown tool',
320
- });
321
- this.messageHistory.push({
322
- role: 'tool',
323
- content: JSON.stringify({ success: false, error: `Unknown tool: ${toolCall.name}` })
324
- });
325
- continue;
326
- }
327
-
328
- this.emit({
329
- type: 'tool',
330
- content: `🔧 执行: ${toolCall.name}`,
331
- tool: toolCall.name
332
- });
333
- // 2026-06-15: step-timeline — 开节点
334
- this.emit({
335
- type: 'step_start',
336
- content: `调用 ${toolCall.name}`,
337
- tool: toolCall.name,
338
- args: toolCall.args || {},
339
- });
340
-
341
- try {
342
- const result = await tool.execute(toolCall.args ?? {});
343
-
344
- // 2026-06-15: step-timeline — 关闭节点 (success / error)
345
- this.emit({
346
- type: result.success ? 'step_done' : 'step_error',
347
- content: result.success
348
- ? `${toolCall.name} 成功`
349
- : `${toolCall.name} 失败: ${result.error}`,
350
- tool: toolCall.name,
351
- success: result.success,
352
- output: result.output,
353
- error: result.error,
354
- });
355
- this.emit({
356
- type: result.success ? 'status' : 'error',
357
- content: result.success
358
- ? `✅ ${toolCall.name} 成功`
359
- : `❌ ${toolCall.name} 失败: ${result.error}`
360
- });
361
-
362
- this.messageHistory.push({
363
- role: 'assistant',
364
- content: reply,
365
- toolCall,
366
- toolResult: result
367
- });
368
-
369
- // Record quality from tool result
370
- const toolQuality = this.evaluateToolResult(result);
371
- this.state.qualityScores.push(toolQuality);
372
-
373
- } catch (execError) {
374
- this.emit({
375
- type: 'error',
376
- content: `❌ 工具执行异常: ${execError}`
377
- });
378
- this.messageHistory.push({
379
- role: 'tool',
380
- content: JSON.stringify({ success: false, error: String(execError) })
381
- });
382
- }
383
- }
384
-
385
- } catch (error) {
386
- this.emit({
387
- type: 'error',
388
- content: `❌ 循环异常: ${error}`
389
- });
390
- return this.createResult(false, response, 'error');
391
- }
392
- }
393
-
394
- // Loop exited - determine reason
395
- const exitReason = this.determineExitReason(effectiveConfig);
396
-
397
- if (!response && this.messageHistory.length > 0) {
398
- const lastAssistant = this.messageHistory
399
- .filter(m => m.role === 'assistant')
400
- .pop();
401
- response = lastAssistant?.content || '任务处理超时';
402
- }
403
-
404
- return this.createResult(
405
- exitReason !== 'error',
406
- response,
407
- exitReason
408
- );
409
- }
410
-
411
- /**
412
- * Determine if loop should continue
413
- */
414
- private shouldContinue(config: Required<PivotLoopConfig>): boolean {
415
- // Hard stop: max iterations reached
416
- if (this.state.iteration >= config.maxIterations) {
417
- this.emit({
418
- type: 'status',
419
- content: `🛑 达到最大迭代次数 ${config.maxIterations}`
420
- });
421
- return false;
422
- }
423
-
424
- // Soft stop: consecutive no progress
425
- if (this.state.consecutiveNoProgress >= config.maxConsecutiveNoProgress) {
426
- this.emit({
427
- type: 'status',
428
- content: `🛑 连续 ${config.maxConsecutiveNoProgress} 次无进展`
429
- });
430
- return false;
431
- }
432
-
433
- return true;
434
- }
435
-
436
- /**
437
- * Adapt configuration based on task profile
438
- */
439
- private adaptConfigForTask(profile: TaskProfile): Required<PivotLoopConfig> {
440
- return {
441
- ...this.config,
442
- maxIterations: Math.min(this.config.maxIterations, profile.suggestedMaxIterations),
443
- maxTokenBudget: Math.min(this.config.maxTokenBudget, profile.tokenBudget),
444
- complexity: profile.complexity
445
- };
446
- }
447
-
448
- /**
449
- * Extract pending tool uses from LLM response
450
- */
451
- private extractPendingToolUses(content: string): ToolDefinition[] {
452
- const pending: ToolDefinition[] = [];
453
-
454
- // Pattern 0: <tool_use>{...JSON...}</tool_use> (Anthropic 风格 + minimax 也用)
455
- // 这次 LLM 输出: <tool_use>\n{"name": "read_document", "arguments": {"path": "/Users/.../README.md"}}\n</tool_use>
456
- const toolUseRe = /<tool_use>\s*(\{[\s\S]*?\})\s*<\/tool_use>/g;
457
- let match;
458
- while ((match = toolUseRe.exec(content)) !== null) {
459
- try {
460
- const obj = JSON.parse(match[1]);
461
- if (obj && obj.name && this.tools.has(obj.name)) {
462
- const args = this.normalizeArgs(obj.arguments || {});
463
- pending.push({ name: obj.name, args, description: '', parameters: {} });
464
- }
465
- } catch (e) {
466
- // JSON 解析失败, 继续下一 match
467
- }
468
- }
469
-
470
- // Pattern 0b: <function_calls><invoke name="X"><parameter name="k">v</parameter>...</invoke></function_calls>
471
- // 这次 minimax LLM 用这种 Anthropic 风格 XML
472
- const fnCallsRe = /<function_calls>([\s\S]*?)<\/function_calls>/g;
473
- while ((match = fnCallsRe.exec(content)) !== null) {
474
- const block = match[1];
475
- // 抓 <invoke name="X">...</invoke>
476
- const invokeRe = /<invoke\s+name="(\w+)"\s*>([\s\S]*?)<\/invoke>/g;
477
- let im;
478
- while ((im = invokeRe.exec(block)) !== null) {
479
- const name = im[1];
480
- if (!this.tools.has(name)) continue;
481
- // 抓 <parameter name="k">v</parameter> 列表
482
- const args: Record<string, string> = {};
483
- const paramRe = /<parameter\s+name="(\w+)"\s*>([\s\S]*?)<\/parameter>/g;
484
- let pm;
485
- while ((pm = paramRe.exec(im[2])) !== null) {
486
- args[pm[1]] = pm[2].trim().replace(/^["']|['"]$/g, '');
487
- }
488
- // 避免重复添加
489
- if (!pending.some(p => p.name === name)) {
490
- pending.push({ name, args, description: '', parameters: {} });
491
- }
492
- }
493
- }
494
-
495
- // Pattern 1: Chinese format "调用工具: tool_name(args)"
496
- const pattern1 = /调用工具[::]\s*(\w+)\s*\(([^)]*)\)/g;
497
- while ((match = pattern1.exec(content)) !== null) {
498
- const name = match[1];
499
- const argsStr = match[2];
500
- const args = this.parseArgs(argsStr);
501
- if (this.tools.has(name)) {
502
- pending.push({ name, args, description: '', parameters: {} });
503
- }
504
- }
505
-
506
- // Pattern 2: tool_name(args) format
507
- const pattern2 = /(\w+)\s*\(\s*([^)]*)\s*\)/g;
508
- while ((match = pattern2.exec(content)) !== null) {
509
- const name = match[1];
510
- const argsStr = match[2];
511
- // Skip if already matched or doesn't look like a tool call
512
- if (pending.some(p => p.name === name)) continue;
513
- if (!this.tools.has(name)) continue;
514
-
515
- const args = this.parseArgs(argsStr);
516
- pending.push({ name, args, description: '', parameters: {} });
517
- }
518
-
519
- // Pattern 3: JSON format tool calls
520
- try {
521
- const jsonMatch = content.match(/\{[\s\S]*"tool_calls"[\s\S]*\}/);
522
- if (jsonMatch) {
523
- const parsed = JSON.parse(jsonMatch[0]);
524
- if (Array.isArray(parsed.tool_calls)) {
525
- for (const tc of parsed.tool_calls) {
526
- if (this.tools.has(tc.name)) {
527
- pending.push({ name: tc.name, args: tc.args || {}, description: '', parameters: {} });
528
- }
529
- }
530
- }
531
- }
532
- } catch {
533
- // JSON parsing failed, ignore
534
- }
535
-
536
- return pending;
537
- }
538
-
539
- /**
540
- * Parse tool arguments from string
541
- */
542
- private parseArgs(argsStr: string): Record<string, string> {
543
- const args: Record<string, string> = {};
544
- if (!argsStr || !argsStr.trim()) return args;
545
-
546
- const pairs = argsStr.split(',').map(s => s.trim()).filter(Boolean);
547
- for (const pair of pairs) {
548
- // 2026-06-15: LLM 实际输出 3 种格式 — 全支持
549
- // 1) JSON 风格: {"key":"value"} (服务器日志显示, 但 LLM 不会真输出完整 JSON)
550
- // 2) key="value" 含双引号 (本次 read_document(path="/Users/..."))
551
- // 3) key='value' 含单引号
552
- // 4) key:value (老 Chinese 格式)
553
- // 5) key value (positional 兜底)
554
- let m = pair.match(/^["']?([\w-]+)["']?\s*=\s*["']([^"']*)["']$/);
555
- if (m) { args[m[1]] = m[2]; continue; }
556
- m = pair.match(/^["']?([\w-]+)["']?\s*[:=]\s*([^,]+)$/);
557
- if (m) { args[m[1]] = m[2].trim().replace(/^['"]|['"]$/g, ''); continue; }
558
- m = pair.match(/^["']?([\w-]+)["']?\s*[:]\s*["']?([^"']*)["']?$/);
559
- if (m) { args[m[1]] = m[2].trim(); continue; }
560
- // positional 兜底
561
- const parts = pair.split(/\s+/);
562
- if (parts.length >= 2) {
563
- args[parts[0]] = parts.slice(1).join(' ');
564
- }
565
- }
566
- return args;
567
- }
568
-
569
- /**
570
- * 把 tool_use JSON 里的 arguments (已经是对象) 转成 Record<string, string>
571
- * JSON parser 直接给对象, 但 tool.execute 期望 Record<string, string>
572
- * 非字符串值 JSON.stringify 一下
573
- */
574
- private normalizeArgs(args: Record<string, unknown>): Record<string, string> {
575
- const out: Record<string, string> = {};
576
- for (const [k, v] of Object.entries(args || {})) {
577
- if (v == null) continue;
578
- if (typeof v === 'string') out[k] = v;
579
- else out[k] = JSON.stringify(v);
580
- }
581
- return out;
582
- }
583
-
584
- /**
585
- * Build context from message history
586
- */
587
- private buildContext(): string {
588
- return this.messageHistory.map(m => {
589
- if (m.role === 'user') return `用户: ${m.content}`;
590
- if (m.role === 'assistant') return `助手: ${m.content}`;
591
- if (m.role === 'tool' && m.toolResult) {
592
- return `工具结果: ${JSON.stringify(m.toolResult)}`;
593
- }
594
- return '';
595
- }).filter(Boolean).join('\n');
596
- }
597
-
598
- /**
599
- * Evaluate response quality
600
- */
601
- private evaluateQuality(response: string): number {
602
- let score = 0.5;
603
-
604
- // Length-based scoring
605
- if (response.length > 100) score += 0.1;
606
- if (response.length > 500) score += 0.1;
607
- if (response.length < 30) score -= 0.2;
608
-
609
- // Structure indicators
610
- if (response.includes('\n')) score += 0.05;
611
- if (response.includes('-') || response.includes('•')) score += 0.05;
612
- if (response.includes('```')) score += 0.1;
613
-
614
- // Content quality indicators
615
- const conclusionWords = ['完成', '结果', '总结', '所以', '因此', '答案', '推荐', '建议'];
616
- if (conclusionWords.some(w => response.includes(w))) score += 0.1;
617
-
618
- // Negative indicators
619
- if (response.includes('调用工具') || response.includes('tool(')) score -= 0.15;
620
- if (response.includes('??') || response.includes('未知')) score -= 0.1;
621
-
622
- return Math.max(0, Math.min(1, score));
623
- }
624
-
625
- /**
626
- * Evaluate tool result quality
627
- */
628
- private evaluateToolResult(result: ToolResult): number {
629
- if (!result.success) return 0.2;
630
-
631
- let score = 0.6;
632
- if (result.output) {
633
- score += 0.2;
634
- if (result.output.length > 100) score += 0.1;
635
- if (result.output.includes('error') || result.output.includes('❌')) score -= 0.2;
636
- if (result.output.includes('success') || result.output.includes('✅')) score += 0.1;
637
- }
638
- if (result.error) score -= 0.3;
639
-
640
- return Math.max(0, Math.min(1, score));
641
- }
642
-
643
- /**
644
- * Estimate token count (rough approximation)
645
- */
646
- private estimateTokens(text: string): number {
647
- // Rough estimate: ~4 characters per token for Chinese/English mix
648
- return Math.ceil(text.length / 4);
649
- }
650
-
651
- /**
652
- * Create result object
653
- */
654
- private createResult(success: boolean, response: string, exitReason: ExitReason): LoopResult {
655
- const avgQuality = this.state.qualityScores.length > 0
656
- ? this.state.qualityScores.reduce((a, b) => a + b, 0) / this.state.qualityScores.length
657
- : 0;
658
-
659
- return {
660
- success,
661
- response,
662
- iterations: this.state.iteration,
663
- toolCalls: this.state.toolCallsCount,
664
- qualityScore: avgQuality,
665
- exitReason,
666
- state: { ...this.state }
667
- };
668
- }
669
-
670
- /**
671
- * Determine why loop exited
672
- */
673
- private determineExitReason(config: Required<PivotLoopConfig>): ExitReason {
674
- if (this.state.iteration >= config.maxIterations) {
675
- return 'max_iterations';
676
- }
677
- if (this.state.consecutiveNoProgress >= config.maxConsecutiveNoProgress) {
678
- return 'no_progress_exhausted';
679
- }
680
- if (this.state.pendingToolUses.length === 0 && this.state.iteration >= config.minIterations) {
681
- return 'no_pending_tools';
682
- }
683
- if (this.state.totalTokens > config.maxTokenBudget) {
684
- return 'token_budget_exceeded';
685
- }
686
- return 'max_iterations';
687
- }
688
-
689
- /**
690
- * Emit stream event
691
- */
692
- private emit(event: StreamEvent): void {
693
- if (this.streamCallback) {
694
- this.streamCallback(event);
695
- }
696
- }
697
-
698
- /**
699
- * Get current state
700
- */
701
- getState(): PivotLoopState {
702
- return { ...this.state };
703
- }
704
-
705
- /**
706
- * Reset the loop state
707
- */
708
- reset(): void {
709
- this.state = this.createInitialState();
710
- this.messageHistory = [];
711
- }
712
- }
713
-
714
- /**
715
- * Interface for LLM chat capability
716
- */
717
- export interface LLMInterface {
718
- chat(context: string, systemPrompt: string): Promise<{ reply: string; tokens?: number }>;
719
- }
720
-
721
- /**
722
- * Factory to create a default pivot loop configuration
723
- */
724
- export function createDefaultPivotConfig(complexity?: TaskComplexity): PivotLoopConfig {
725
- const profiles: Record<TaskComplexity, PivotLoopConfig> = {
726
- simple: {
727
- maxIterations: 15,
728
- minIterations: 1,
729
- qualityThreshold: 0.6,
730
- maxConsecutiveNoProgress: 3,
731
- maxTokenBudget: 10000
732
- },
733
- moderate: {
734
- maxIterations: 30,
735
- minIterations: 2,
736
- qualityThreshold: 0.7,
737
- maxConsecutiveNoProgress: 5,
738
- maxTokenBudget: 30000
739
- },
740
- complex: {
741
- maxIterations: 60,
742
- minIterations: 3,
743
- qualityThreshold: 0.75,
744
- maxConsecutiveNoProgress: 8,
745
- maxTokenBudget: 60000
746
- }
747
- };
748
-
749
- return complexity ? profiles[complexity] : profiles.moderate;
750
- }
751
-
752
- /**
753
- * Helper to run a simple prompt through the loop
754
- */
755
- export async function runPivotLoop(
756
- input: string,
757
- llm: LLMInterface,
758
- tools: Tool[],
759
- systemPrompt: string,
760
- config?: PivotLoopConfig,
761
- streamCallback?: StreamCallback
762
- ): Promise<LoopResult> {
763
- const loop = new WorkflowPivotLoop(config || createDefaultPivotConfig());
764
- loop.registerTools(tools);
765
- return loop.execute(input, llm, systemPrompt, streamCallback);
766
- }