@bolloon/bolloon-agent 0.1.1 → 0.1.3

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 (200) hide show
  1. package/bin/bolloon-cli.cjs +165 -0
  2. package/bin/bolloon-daemon.sh +207 -0
  3. package/bin/bolloon.cmd +11 -0
  4. package/dist/agents/constraint-layer.js +10 -15
  5. package/dist/agents/pi-sdk.js +433 -106
  6. package/dist/agents/protocol.js +82 -1
  7. package/dist/agents/subagent-manager.js +2 -2
  8. package/dist/agents/workflow-engine.js +15 -20
  9. package/dist/agents/workflow-pivot-loop.js +541 -0
  10. package/dist/bollharness/src/index.js +5 -0
  11. package/dist/bollharness/src/scripts/checks/check_adr_plan_numbering.js +6 -0
  12. package/dist/bollharness/src/scripts/checks/check_api_types.js +45 -0
  13. package/dist/bollharness/src/scripts/checks/check_artifact_link.js +146 -0
  14. package/dist/bollharness/src/scripts/checks/check_bridge_deps.js +6 -0
  15. package/dist/bollharness/src/scripts/checks/check_bugfix_binding.js +6 -0
  16. package/dist/bollharness/src/scripts/checks/check_bugfix_binding_ci.js +6 -0
  17. package/dist/bollharness/src/scripts/checks/check_doc_file_references.js +6 -0
  18. package/dist/bollharness/src/scripts/checks/check_doc_freshness.js +135 -0
  19. package/dist/bollharness/src/scripts/checks/check_doc_links.js +31 -0
  20. package/dist/bollharness/src/scripts/checks/check_file_existence_claims.js +6 -0
  21. package/dist/bollharness/src/scripts/checks/check_fragment_integrity.js +34 -0
  22. package/dist/bollharness/src/scripts/checks/check_hook_installed.js +63 -0
  23. package/dist/bollharness/src/scripts/checks/check_issue_closure.js +41 -0
  24. package/dist/bollharness/src/scripts/checks/check_mcp_parity.js +6 -0
  25. package/dist/bollharness/src/scripts/checks/check_security.js +48 -0
  26. package/dist/bollharness/src/scripts/checks/check_skill_parity.js +6 -0
  27. package/dist/bollharness/src/scripts/checks/check_versions.js +6 -0
  28. package/dist/bollharness/src/scripts/checks/finding.js +13 -0
  29. package/dist/bollharness/src/scripts/checks/next_decision_number.js +20 -0
  30. package/dist/bollharness/src/scripts/checks/regenerate_magic_docs.js +6 -0
  31. package/dist/bollharness/src/scripts/ci/detect_rebaseline_triggers.js +8 -0
  32. package/dist/bollharness/src/scripts/ci/scan_subprocess_cfg.js +8 -0
  33. package/dist/bollharness/src/scripts/ci/scan_verify_artifacts.js +8 -0
  34. package/dist/bollharness/src/scripts/ci/scan_yaml_schema.js +8 -0
  35. package/dist/bollharness/src/scripts/context_router.js +67 -0
  36. package/dist/bollharness/src/scripts/deploy-guard.js +157 -0
  37. package/dist/bollharness/src/scripts/guard-feedback.js +192 -0
  38. package/dist/bollharness/src/scripts/guard_router.js +158 -0
  39. package/dist/bollharness/src/scripts/hooks/_hook_output.js +6 -0
  40. package/dist/bollharness/src/scripts/hooks/auto-python3.js +6 -0
  41. package/dist/bollharness/src/scripts/hooks/deploy-progress-on-session-end.js +6 -0
  42. package/dist/bollharness/src/scripts/hooks/failure-analyzer.js +6 -0
  43. package/dist/bollharness/src/scripts/hooks/gate-judgment-inject.js +92 -0
  44. package/dist/bollharness/src/scripts/hooks/gate-transition-judgment.js +63 -0
  45. package/dist/bollharness/src/scripts/hooks/inbox-ack.js +6 -0
  46. package/dist/bollharness/src/scripts/hooks/inbox-inject-on-start.js +6 -0
  47. package/dist/bollharness/src/scripts/hooks/inbox-validate.js +6 -0
  48. package/dist/bollharness/src/scripts/hooks/inbox-write-ledger.js +6 -0
  49. package/dist/bollharness/src/scripts/hooks/initializer-agent.js +6 -0
  50. package/dist/bollharness/src/scripts/hooks/loop-detection.js +73 -0
  51. package/dist/bollharness/src/scripts/hooks/owner-guard.js +6 -0
  52. package/dist/bollharness/src/scripts/hooks/precompact.js +6 -0
  53. package/dist/bollharness/src/scripts/hooks/review-agent-gatekeeper.js +6 -0
  54. package/dist/bollharness/src/scripts/hooks/risk-tracker.js +108 -0
  55. package/dist/bollharness/src/scripts/hooks/sanitize-on-read.js +6 -0
  56. package/dist/bollharness/src/scripts/hooks/session-reflection.js +7 -0
  57. package/dist/bollharness/src/scripts/hooks/session-start-magic-docs.js +7 -0
  58. package/dist/bollharness/src/scripts/hooks/session-start-reset-risk.js +7 -0
  59. package/dist/bollharness/src/scripts/hooks/session-start-toolkit-reminder.js +7 -0
  60. package/dist/bollharness/src/scripts/hooks/stop-evaluator.js +157 -0
  61. package/dist/bollharness/src/scripts/hooks/tool-call-counter.js +6 -0
  62. package/dist/bollharness/src/scripts/hooks/trace-analyzer.js +10 -0
  63. package/dist/bollharness/src/scripts/install/install-trust-token.js +7 -0
  64. package/dist/bollharness/src/scripts/install/multi_project_registry.js +9 -0
  65. package/dist/bollharness/src/scripts/install/phase2_auto.js +21 -0
  66. package/dist/bollharness/src/scripts/install/pre_commit_installer.js +6 -0
  67. package/dist/bollharness/src/scripts/install/tier_selector.js +7 -0
  68. package/dist/bollharness/src/scripts/install/transcript_miner.js +7 -0
  69. package/dist/bollharness/src/scripts/lib/claim_patterns.js +10 -0
  70. package/dist/bollharness/src/scripts/lib/sanitize_patterns.js +12 -0
  71. package/dist/bollharness/src/scripts/sanitize.js +6 -0
  72. package/dist/bollharness-integration/channel-judgment-engine.js +530 -0
  73. package/dist/bollharness-integration/context-chain-router.js +383 -0
  74. package/dist/bollharness-integration/context-router-judgment.js +13 -21
  75. package/dist/bollharness-integration/context-router.js +22 -64
  76. package/dist/bollharness-integration/gate-state-machine.js +14 -19
  77. package/dist/bollharness-integration/gate-transition-hooks.js +16 -61
  78. package/dist/bollharness-integration/guard-checker.js +21 -68
  79. package/dist/bollharness-integration/index.js +14 -124
  80. package/dist/bollharness-integration/integration.js +13 -20
  81. package/dist/bollharness-integration/llm-judgment-engine.js +569 -0
  82. package/dist/bollharness-integration/skill-adapter.js +18 -64
  83. package/dist/cli-entry.js +261 -0
  84. package/dist/constraint-runtime/src/commands.js +17 -7
  85. package/dist/constraint-runtime/src/constraint/budget.js +1 -6
  86. package/dist/constraint-runtime/src/constraint/permission.js +1 -6
  87. package/dist/constraint-runtime/src/models.js +1 -3
  88. package/dist/constraint-runtime/src/tools.js +17 -7
  89. package/dist/constraints/index.js +1 -7
  90. package/dist/documents/reader.js +8 -49
  91. package/dist/heartbeat/DaemonManager.js +242 -0
  92. package/dist/heartbeat/HealthMonitor.js +285 -0
  93. package/dist/heartbeat/StartupVerifier.js +205 -0
  94. package/dist/heartbeat/Watchdog.js +168 -0
  95. package/dist/heartbeat/index.js +84 -0
  96. package/dist/heartbeat/types.js +5 -0
  97. package/dist/index.js +381 -28
  98. package/dist/llm/config-store.js +31 -57
  99. package/dist/llm/llm-judgment-client.js +389 -0
  100. package/dist/llm/pi-ai.js +9 -52
  101. package/dist/network/agent-network.js +46 -90
  102. package/dist/network/hybrid-messenger.js +125 -0
  103. package/dist/network/iroh-bootstrap.js +38 -0
  104. package/dist/network/iroh-discovery.js +145 -0
  105. package/dist/network/iroh-integration.js +9 -16
  106. package/dist/network/iroh-transport.js +10 -48
  107. package/dist/network/p2p.js +23 -62
  108. package/dist/network/storage/adapters/json-adapter.js +4 -42
  109. package/dist/network/storage/index.js +147 -0
  110. package/dist/network/storage/types.js +14 -0
  111. package/dist/pi-ecosystem/index.js +233 -0
  112. package/dist/pi-ecosystem-colony/index.js +29 -90
  113. package/dist/pi-ecosystem-goals/index.js +20 -74
  114. package/dist/pi-ecosystem-judgment/decision.js +29 -47
  115. package/dist/pi-ecosystem-judgment/distillation.js +16 -29
  116. package/dist/pi-ecosystem-judgment/human-value-store.js +13 -60
  117. package/dist/pi-ecosystem-judgment/index.js +21 -74
  118. package/dist/pi-ecosystem-judgment/value-injection.js +26 -72
  119. package/dist/pi-ecosystem-mcp/index.js +24 -78
  120. package/dist/pi-ecosystem-subagents/index.js +20 -69
  121. package/dist/social/ant-colony/AdaptiveHeartbeat.js +3 -8
  122. package/dist/social/ant-colony/PheromoneEngine.js +11 -49
  123. package/dist/social/ant-colony/index.js +6 -0
  124. package/dist/social/ant-colony/types.js +4 -8
  125. package/dist/social/channels/ChannelManager.js +8 -46
  126. package/dist/social/channels/DiapChannelBridge.js +9 -47
  127. package/dist/social/channels/InterestMatcher.js +2 -7
  128. package/dist/social/channels/channel-agent-session.js +309 -0
  129. package/dist/social/channels/channel-heartbeat-agent.js +494 -0
  130. package/dist/social/channels/diap-doc-parser.js +204 -0
  131. package/dist/social/channels/harness-workflow-integrator.js +446 -0
  132. package/dist/social/channels/index.js +9 -0
  133. package/dist/social/channels/types.js +3 -7
  134. package/dist/social/global-shared-context.js +6 -47
  135. package/dist/social/heartbeat.js +29 -72
  136. package/dist/social/persona/enhanced-persona.js +299 -0
  137. package/dist/web/client.js +302 -136
  138. package/dist/web/components/p2p/index.js +159 -9
  139. package/dist/web/components/p2p/p2p-connection.js +136 -0
  140. package/dist/web/components/p2p/p2p-manager.js +24 -0
  141. package/dist/web/components/p2p/p2p-store-memory.js +1 -1
  142. package/dist/web/components/p2p/types.js +7 -0
  143. package/dist/web/index.html +5 -0
  144. package/dist/web/style.css +118 -0
  145. package/package.json +12 -6
  146. package/scripts/build-cli.js +206 -0
  147. package/scripts/postinstall.js +153 -0
  148. package/src/agents/pi-sdk.ts +347 -28
  149. package/src/agents/protocol.ts +95 -1
  150. package/src/agents/workflow-pivot-loop.ts +674 -0
  151. package/src/bollharness/CLAUDE.md +73 -0
  152. package/src/bollharness/README.md +143 -0
  153. package/src/bollharness/README.zh-CN.md +131 -0
  154. package/src/bollharness/reference/boll-reference/scripts/hooks/stop-evaluator.md +57 -0
  155. package/src/bollharness/scripts/context-fragments/artifact-linkage.md +14 -0
  156. package/src/bollharness/scripts/context-fragments/auth-consumers.md +17 -0
  157. package/src/bollharness/scripts/context-fragments/bridge-constitution.md +13 -0
  158. package/src/bollharness/scripts/context-fragments/catalyst-distributed.md +18 -0
  159. package/src/bollharness/scripts/context-fragments/closure-checklist.md +13 -0
  160. package/src/bollharness/scripts/context-fragments/contract-consumers.md +15 -0
  161. package/src/bollharness/scripts/context-fragments/db-shared-structures.md +15 -0
  162. package/src/bollharness/scripts/context-fragments/fixed-three-layers.md +19 -0
  163. package/src/bollharness/scripts/context-fragments/general-dev-principles.md +11 -0
  164. package/src/bollharness/scripts/context-fragments/issue-first.md +8 -0
  165. package/src/bollharness/scripts/context-fragments/mcp-parity.md +16 -0
  166. package/src/bollharness/scripts/context-fragments/pi-agent-operations.md +108 -0
  167. package/src/bollharness/scripts/context-fragments/protocol-consumers.md +15 -0
  168. package/src/bollharness/scripts/context-fragments/run-events-consumers.md +15 -0
  169. package/src/bollharness/scripts/context-fragments/scene-fidelity.md +13 -0
  170. package/src/bollharness/scripts/context-fragments/truth-source-hierarchy.md +15 -0
  171. package/src/bollharness/scripts/context-fragments/two-language.md +15 -0
  172. package/src/bollharness/scripts/context-fragments/version-sources.md +14 -0
  173. package/src/bollharness/scripts/hooks/stop-evaluator.md +83 -0
  174. package/src/bollharness/templates/scaffold/CLAUDE.md +89 -0
  175. package/src/cli-entry.ts +304 -0
  176. package/src/heartbeat/DaemonManager.ts +283 -0
  177. package/src/heartbeat/HealthMonitor.ts +316 -0
  178. package/src/heartbeat/StartupVerifier.ts +223 -0
  179. package/src/heartbeat/Watchdog.ts +198 -0
  180. package/src/heartbeat/index.ts +108 -0
  181. package/src/heartbeat/types.ts +82 -0
  182. package/src/llm/config-store.ts +23 -5
  183. package/src/network/iroh-transport.ts +3 -3
  184. package/src/web/client.js +302 -136
  185. package/src/web/components/p2p/P2PModal.tsx +91 -3
  186. package/src/web/components/p2p/index.ts +171 -9
  187. package/src/web/components/p2p/p2p-connection.ts +153 -1
  188. package/src/web/components/p2p/p2p-manager.ts +39 -1
  189. package/src/web/components/p2p/p2p-store-memory.ts +1 -1
  190. package/src/web/components/p2p/p2p-tools.ts +315 -0
  191. package/src/web/components/p2p/types.ts +58 -0
  192. package/src/web/design.md +99 -0
  193. package/src/web/index.html +5 -0
  194. package/src/web/server.ts +353 -36
  195. package/src/web/style.css +118 -0
  196. package/tsconfig.cli.json +16 -0
  197. package/tsconfig.electron.json +1 -1
  198. package/tsconfig.json +1 -2
  199. package/dist/web/server.js +0 -1647
  200. package/dist/web/server.js.map +0 -1
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  /**
3
2
  * Bollharness Integration for Bolloon
4
3
  *
@@ -8,17 +7,14 @@
8
7
  * - Context Router (automatic context injection)
9
8
  * - Skill Adapter (bollharness skills in Bolloon)
10
9
  */
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.BollharnessHooks = exports.BollharnessIntegration = void 0;
13
- exports.createBollharnessIntegration = createBollharnessIntegration;
14
- const gate_state_machine_js_1 = require("./gate-state-machine.js");
15
- const guard_checker_js_1 = require("./guard-checker.js");
16
- const context_router_js_1 = require("./context-router.js");
17
- const skill_adapter_js_1 = require("./skill-adapter.js");
10
+ import { GateStateMachine } from './gate-state-machine.js';
11
+ import { GuardChecker, runGuards } from './guard-checker.js';
12
+ import { ContextRouter } from './context-router.js';
13
+ import { createSkillAdapter } from './skill-adapter.js';
18
14
  /**
19
15
  * Main integration class
20
16
  */
21
- class BollharnessIntegration {
17
+ export class BollharnessIntegration {
22
18
  config;
23
19
  gateMachine;
24
20
  guardChecker;
@@ -34,10 +30,10 @@ class BollharnessIntegration {
34
30
  skillsEnabled: config.skillsEnabled ?? true,
35
31
  gatesEnabled: config.gatesEnabled ?? true,
36
32
  };
37
- this.gateMachine = new gate_state_machine_js_1.GateStateMachine();
38
- this.guardChecker = new guard_checker_js_1.GuardChecker();
39
- this.contextRouter = new context_router_js_1.ContextRouter();
40
- this.skillAdapter = (0, skill_adapter_js_1.createSkillAdapter)();
33
+ this.gateMachine = new GateStateMachine();
34
+ this.guardChecker = new GuardChecker();
35
+ this.contextRouter = new ContextRouter();
36
+ this.skillAdapter = createSkillAdapter();
41
37
  }
42
38
  /**
43
39
  * Process a file edit with all enabled checks
@@ -49,7 +45,7 @@ class BollharnessIntegration {
49
45
  // Run guards if enabled
50
46
  if (this.config.guardsEnabled) {
51
47
  try {
52
- guards = await (0, guard_checker_js_1.runGuards)(filePath);
48
+ guards = await runGuards(filePath);
53
49
  if (!guards.passed) {
54
50
  errors.push(...guards.findings.map(f => f.message));
55
51
  }
@@ -82,7 +78,7 @@ class BollharnessIntegration {
82
78
  let guards;
83
79
  if (this.config.guardsEnabled) {
84
80
  try {
85
- guards = await (0, guard_checker_js_1.runGuards)(filePath);
81
+ guards = await runGuards(filePath);
86
82
  if (!guards.passed && guards.blockingCount > 0) {
87
83
  errors.push(...guards.findings
88
84
  .filter(f => f.blocking)
@@ -346,17 +342,16 @@ class BollharnessIntegration {
346
342
  this.currentSessionId = sessionId;
347
343
  }
348
344
  }
349
- exports.BollharnessIntegration = BollharnessIntegration;
350
345
  /**
351
346
  * Create a default integration instance
352
347
  */
353
- function createBollharnessIntegration(config) {
348
+ export function createBollharnessIntegration(config) {
354
349
  return new BollharnessIntegration(config);
355
350
  }
356
351
  /**
357
352
  * Integration hooks for Bolloon's execution pipeline
358
353
  */
359
- class BollharnessHooks {
354
+ export class BollharnessHooks {
360
355
  integration;
361
356
  constructor(integration) {
362
357
  this.integration = integration || new BollharnessIntegration();
@@ -423,5 +418,3 @@ class BollharnessHooks {
423
418
  console.log('[Bollharness] Session ended', JSON.stringify(metrics, null, 2));
424
419
  }
425
420
  }
426
- exports.BollharnessHooks = BollharnessHooks;
427
- //# sourceMappingURL=integration.js.map
@@ -0,0 +1,569 @@
1
+ /**
2
+ * LLM-native Judgment Engine
3
+ *
4
+ * 核心理念:
5
+ * - 不使用关键词匹配,而是让 LLM 理解用户意图
6
+ * - 价值观注入:学习人类判断价值观,注入到 Prompt 中
7
+ * - Skills 可以被动态调用
8
+ *
9
+ * 架构:
10
+ * 1. LLM-as-Judge: 使用 LLM 执行真正的理解
11
+ * 2. Value Injection: 从 human-value-store 获取价值观注入
12
+ * 3. Dynamic-Skill-Routing: 根据判断结果动态调用 Skills
13
+ */
14
+ import { createBollharnessIntegration } from './integration.js';
15
+ import { generateJudgmentPromptWithValues } from '../pi-ecosystem-judgment/value-injection.js';
16
+ import { learnFromFeedback, learnFromCorrection } from '../pi-ecosystem-judgment/human-value-store.js';
17
+ import { initPiAI, getModel, isModelAvailable } from '../llm/pi-ai.js';
18
+ import { getPiSDKConfig } from '../llm/config-store.js';
19
+ /**
20
+ * 判断用的 Prompt 模板(可以从 YAML 加载)
21
+ */
22
+ export const JUDGMENT_PROMPT_TEMPLATE = `你是一个专业的 AI 任务分析专家。你的职责是深入理解用户的问题,并给出精准的判断。
23
+
24
+ 【输入】
25
+ {user_input}
26
+
27
+ 【历史上下文】
28
+ {history_context}
29
+
30
+ 请分析以上输入,回答以下问题:
31
+
32
+ ## 1. 问题理解
33
+
34
+ **问题本质**:用户真正想要什么?这是什么类型的问题?
35
+ - how-to: 寻求操作指导
36
+ - why: 寻求解释
37
+ - what: 寻求定义
38
+ - should: 寻求建议
39
+ - feasibility: 寻求可行性评估
40
+
41
+ **核心需求**:用户最想要的结果是什么?
42
+
43
+ **隐含信息**:有什么用户没有明确说但需要考虑的因素?
44
+ - 时间压力?
45
+ - 质量要求?
46
+ - 风险限制?
47
+ - 团队协作?
48
+
49
+ ## 2. 复杂性评估
50
+
51
+ **复杂性等级**:这个问题有多复杂?
52
+ - simple: 简单任务,直接可答
53
+ - moderate: 中等复杂,需要一定思考
54
+ - complex: 复杂问题,需要深入分析
55
+ - profound: 深刻问题,需要本质性思考
56
+
57
+ **评估理由**:为什么认为这是这个复杂性等级?
58
+
59
+ **深度**:需要多深的理解?
60
+ - surface: 表面理解即可
61
+ - deeper: 需要分析
62
+ - fundamental: 需要本质性思考
63
+
64
+ ## 3. 处理决策
65
+
66
+ **推荐方式**:
67
+ - answer: 直接回答
68
+ - analyze: 深入分析
69
+ - design: 设计方案
70
+ - implement: 实现代码
71
+ - coordinate: 协调多智能体
72
+
73
+ **决策理由**:为什么推荐这个处理方式?
74
+
75
+ ## 4. 路由决策
76
+
77
+ **应该调用的 Skills**(可选多个):
78
+ - arch: 架构设计
79
+ - harness-dev: 开发实现
80
+ - guardian-fixer: 代码审查
81
+ - harness-eng: 工程协调
82
+ - harness-eng-test: 测试工程
83
+ - task-arch: 任务分解
84
+ - crystal-learn: 反思学习
85
+
86
+ **参与智能体**(可选):
87
+ - architect: 架构师
88
+ - developer: 开发者
89
+ - reviewer: 审查员
90
+ - coordinator: 协调者
91
+
92
+ **协作模式**:
93
+ - solo: 单独处理
94
+ - pair: 配对协作
95
+ - team: 团队协作
96
+
97
+ ## 5. 产出要求
98
+
99
+ **需要的产物**:
100
+ - 问题分析
101
+ - 方案设计
102
+ - 代码实现
103
+ - 测试用例
104
+ - 其他
105
+
106
+ **Gate 建议**(如果有):
107
+ - Gate 0: 问题锁定
108
+ - Gate 1: 架构设计
109
+ - Gate 2: 架构审查
110
+ - Gate 3: 计划制定
111
+ - Gate 4: 计划审查
112
+ - Gate 5: 任务分解
113
+ - Gate 6: 任务审查
114
+ - Gate 7: 代码实现
115
+ - Gate 8: 测试验证
116
+
117
+ 请用 JSON 格式输出分析结果。`;
118
+ /**
119
+ * LLM-native Judgment Engine
120
+ */
121
+ export class LLMJudgmentEngine {
122
+ harness;
123
+ promptTemplate;
124
+ useLLM;
125
+ valueInjectionConfig;
126
+ recentJudgments = [];
127
+ constructor(options) {
128
+ this.harness = createBollharnessIntegration();
129
+ this.promptTemplate = options?.promptTemplate || JUDGMENT_PROMPT_TEMPLATE;
130
+ this.useLLM = options?.useLLM ?? true;
131
+ this.valueInjectionConfig = options?.valueInjectionConfig || {};
132
+ }
133
+ /**
134
+ * 设置判断用的 Prompt 模板
135
+ */
136
+ setPromptTemplate(template) {
137
+ this.promptTemplate = template;
138
+ }
139
+ /**
140
+ * 设置价值观注入配置
141
+ */
142
+ setValueInjectionConfig(config) {
143
+ this.valueInjectionConfig = config;
144
+ }
145
+ /**
146
+ * 从配置文件加载 Prompt
147
+ */
148
+ async loadPromptFromConfig(configPath) {
149
+ // TODO: 从 YAML/JSON 加载 prompt 模板
150
+ // 这个配置可以包含更复杂的 prompt 变体
151
+ }
152
+ /**
153
+ * 执行 LLM 判断(集成价值观注入)
154
+ */
155
+ async judge(userInput, options) {
156
+ // 如果强制不使用 LLM 或未配置,使用简化判断
157
+ if (!this.useLLM && !options?.forceLLM) {
158
+ return this.quickJudge(userInput);
159
+ }
160
+ // 构建 prompt(带价值观注入)
161
+ const historyContext = options?.history
162
+ ? options.history.slice(-5).join('\n')
163
+ : '无历史上下文';
164
+ const context = options?.context || userInput;
165
+ // 生成带价值观的 prompt
166
+ let prompt;
167
+ try {
168
+ prompt = await generateJudgmentPromptWithValues(userInput, context, options?.history || [], this.valueInjectionConfig);
169
+ }
170
+ catch (error) {
171
+ // 价值观注入失败,使用基础 prompt
172
+ console.warn('[LLMJudgment] Value injection failed, using base prompt:', error);
173
+ prompt = this.promptTemplate
174
+ .replace('{user_input}', userInput)
175
+ .replace('{history_context}', historyContext);
176
+ }
177
+ try {
178
+ // 调用 LLM(这里需要集成 LLMConfigStore)
179
+ const result = await this.callLLM(prompt);
180
+ // 解析 LLM 输出
181
+ const judgmentResult = this.parseLLMOutput(result, userInput);
182
+ // 记录判断结果(用于学习)
183
+ this.recordJudgment(userInput, judgmentResult);
184
+ return judgmentResult;
185
+ }
186
+ catch (error) {
187
+ console.warn('[LLMJudgment] LLM call failed, falling back to quick judgment:', error);
188
+ return this.quickJudge(userInput);
189
+ }
190
+ }
191
+ /**
192
+ * 记录判断结果(支持后续学习)
193
+ */
194
+ recordJudgment(input, result) {
195
+ this.recentJudgments.push({
196
+ input,
197
+ result,
198
+ timestamp: Date.now()
199
+ });
200
+ // 保留最近 50 条判断
201
+ if (this.recentJudgments.length > 50) {
202
+ this.recentJudgments.shift();
203
+ }
204
+ }
205
+ /**
206
+ * 学习人类反馈(集成到判断引擎)
207
+ */
208
+ async learnFromHumanFeedback(originalInput, approved, reason) {
209
+ // 从反馈中学习
210
+ await learnFromFeedback(originalInput, approved, reason);
211
+ // 重新评估相关判断的置信度
212
+ const relatedJudgment = this.recentJudgments.find(j => j.input.includes(originalInput.substring(0, 20)));
213
+ if (relatedJudgment && !approved) {
214
+ // 如果被拒绝,降低置信度
215
+ console.log('[LLMJudgment] Learning from rejection, will adjust future judgments');
216
+ }
217
+ }
218
+ /**
219
+ * 学习修正(从错误中学习)
220
+ */
221
+ async learnFromCorrection(original, corrected, reason) {
222
+ await learnFromCorrection(original, corrected, reason);
223
+ }
224
+ /**
225
+ * 调用 LLM
226
+ */
227
+ async callLLM(prompt) {
228
+ if (!isModelAvailable()) {
229
+ const config = getPiSDKConfig();
230
+ initPiAI(config);
231
+ }
232
+ const model = getModel();
233
+ const result = await model.chat(prompt, process.cwd());
234
+ return result.reply;
235
+ }
236
+ /**
237
+ * 解析 LLM 输出
238
+ */
239
+ parseLLMOutput(output, originalInput) {
240
+ try {
241
+ // 尝试解析 JSON
242
+ const parsed = JSON.parse(output);
243
+ return {
244
+ understanding: {
245
+ essence: parsed.essence || parsed.问题本质 || 'unknown',
246
+ coreNeed: parsed.coreNeed || parsed.核心需求 || 'unknown',
247
+ implicit: parsed.implicit || parsed.隐含信息 || []
248
+ },
249
+ assessment: {
250
+ complexity: this.normalizeComplexity(parsed.complexity || parsed.复杂性等级),
251
+ complexityReason: parsed.complexityReason || parsed.评估理由 || '',
252
+ depth: this.normalizeDepth(parsed.depth || parsed.深度),
253
+ urgency: this.normalizeUrgency(parsed.urgency || 'medium')
254
+ },
255
+ decision: {
256
+ approach: this.normalizeApproach(parsed.approach || parsed.推荐方式),
257
+ reasoning: parsed.reasoning || parsed.决策理由 || ''
258
+ },
259
+ routing: {
260
+ skills: parsed.skills || parsed.应该调用的Skills || [],
261
+ agents: parsed.agents || parsed.参与智能体 || [],
262
+ collaboration: this.normalizeCollaboration(parsed.collaboration || parsed.协作模式)
263
+ },
264
+ artifacts: {
265
+ required: parsed.artifacts || parsed.需要的产物 || [],
266
+ gate: parsed.gate || parsed.Gate建议
267
+ },
268
+ raw: output
269
+ };
270
+ }
271
+ catch {
272
+ // JSON 解析失败,返回默认结果
273
+ return this.quickJudge(originalInput);
274
+ }
275
+ }
276
+ /**
277
+ * 快速判断(不调用 LLM)
278
+ */
279
+ quickJudge(userInput) {
280
+ const input = userInput.toLowerCase();
281
+ const words = userInput.length;
282
+ // 复杂性评估
283
+ let complexity = 'moderate';
284
+ let complexityReason = '';
285
+ const hasDesignKeywords = input.includes('设计') || input.includes('架构');
286
+ const hasReviewKeywords = input.includes('review') || input.includes('审查');
287
+ const hasMultiSystem = input.includes('和') || input.includes('以及');
288
+ const hasFundamental = input.includes('为什么') || input.includes('本质') || input.includes('根本');
289
+ if (hasDesignKeywords || hasMultiSystem || words > 200) {
290
+ complexity = 'complex';
291
+ complexityReason = '涉及设计或多系统';
292
+ }
293
+ if (hasFundamental || (words > 500 && hasDesignKeywords)) {
294
+ complexity = 'profound';
295
+ complexityReason = '需要本质性思考';
296
+ }
297
+ if (words < 50 && !hasDesignKeywords) {
298
+ complexity = 'simple';
299
+ complexityReason = '简短输入,意图明确';
300
+ }
301
+ // 处理方式
302
+ let approach = 'answer';
303
+ if (hasDesignKeywords)
304
+ approach = 'design';
305
+ else if (hasReviewKeywords || input.includes('分析'))
306
+ approach = 'analyze';
307
+ else if (input.includes('实现') || input.includes('写'))
308
+ approach = 'implement';
309
+ // Skills
310
+ const skills = [];
311
+ if (hasDesignKeywords)
312
+ skills.push('arch');
313
+ if (hasReviewKeywords)
314
+ skills.push('guardian-fixer');
315
+ if (approach === 'implement')
316
+ skills.push('harness-dev');
317
+ if (complexity === 'complex' || complexity === 'profound') {
318
+ skills.push('harness-eng');
319
+ }
320
+ // 协作模式
321
+ const collaboration = complexity === 'profound' ? 'team' :
322
+ complexity === 'complex' ? 'pair' : 'solo';
323
+ return {
324
+ understanding: {
325
+ essence: this.extractEssence(input),
326
+ coreNeed: this.extractCoreNeed(input),
327
+ implicit: []
328
+ },
329
+ assessment: {
330
+ complexity,
331
+ complexityReason,
332
+ depth: hasFundamental ? 'fundamental' : 'surface',
333
+ urgency: input.includes('紧急') ? 'high' : 'medium'
334
+ },
335
+ decision: {
336
+ approach,
337
+ reasoning: '基于快速模式判断'
338
+ },
339
+ routing: {
340
+ skills,
341
+ agents: [],
342
+ collaboration
343
+ },
344
+ artifacts: {
345
+ required: approach === 'design' ? ['架构文档'] : ['回答']
346
+ }
347
+ };
348
+ }
349
+ normalizeComplexity(c) {
350
+ const lower = c.toLowerCase();
351
+ if (lower.includes('simple') || lower.includes('简单'))
352
+ return 'simple';
353
+ if (lower.includes('moderate') || lower.includes('中等'))
354
+ return 'moderate';
355
+ if (lower.includes('complex') || lower.includes('复杂'))
356
+ return 'complex';
357
+ return 'profound';
358
+ }
359
+ normalizeDepth(d) {
360
+ const lower = d.toLowerCase();
361
+ if (lower.includes('surface') || lower.includes('表面'))
362
+ return 'surface';
363
+ if (lower.includes('deeper') || lower.includes('深入'))
364
+ return 'deeper';
365
+ return 'fundamental';
366
+ }
367
+ normalizeUrgency(u) {
368
+ const lower = u.toLowerCase();
369
+ if (lower.includes('low') || lower.includes('低'))
370
+ return 'low';
371
+ if (lower.includes('high') || lower.includes('高') || lower.includes('紧急'))
372
+ return 'high';
373
+ if (lower.includes('critical') || lower.includes('关键'))
374
+ return 'critical';
375
+ return 'medium';
376
+ }
377
+ normalizeApproach(a) {
378
+ const lower = a.toLowerCase();
379
+ if (lower.includes('answer') || lower.includes('回答'))
380
+ return 'answer';
381
+ if (lower.includes('analyze') || lower.includes('分析'))
382
+ return 'analyze';
383
+ if (lower.includes('design') || lower.includes('设计'))
384
+ return 'design';
385
+ if (lower.includes('implement') || lower.includes('实现'))
386
+ return 'implement';
387
+ return 'coordinate';
388
+ }
389
+ normalizeCollaboration(c) {
390
+ const lower = c.toLowerCase();
391
+ if (lower.includes('solo') || lower.includes('单独'))
392
+ return 'solo';
393
+ if (lower.includes('pair') || lower.includes('配对'))
394
+ return 'pair';
395
+ return 'team';
396
+ }
397
+ extractEssence(input) {
398
+ if (input.includes('为什么'))
399
+ return 'why: 寻求解释';
400
+ if (input.includes('怎么') || input.includes('如何'))
401
+ return 'how-to: 寻求指导';
402
+ if (input.includes('应该'))
403
+ return 'should: 寻求建议';
404
+ return 'general: 一般性讨论';
405
+ }
406
+ extractCoreNeed(input) {
407
+ const lower = input.toLowerCase();
408
+ if (lower.includes('设计') || lower.includes('架构'))
409
+ return '设计方案';
410
+ if (lower.includes('实现') || lower.includes('写'))
411
+ return '实现代码';
412
+ if (lower.includes('修复') || lower.includes('解决'))
413
+ return '修复问题';
414
+ if (lower.includes('review') || lower.includes('审查'))
415
+ return '审查代码';
416
+ return '获得帮助';
417
+ }
418
+ }
419
+ // 单例
420
+ let engineInstance = null;
421
+ export function createLLMJudgmentEngine(options) {
422
+ return new LLMJudgmentEngine(options);
423
+ }
424
+ export function getLLMJudgmentEngine() {
425
+ if (!engineInstance) {
426
+ engineInstance = new LLMJudgmentEngine();
427
+ }
428
+ return engineInstance;
429
+ }
430
+ /**
431
+ * Skills 的 Prompt 配置
432
+ */
433
+ export const SKILL_PROMPTS = {
434
+ arch: {
435
+ name: 'arch',
436
+ description: '架构设计专家',
437
+ systemPrompt: `你是一个经验丰富的系统架构师。你擅长:
438
+ - 从需求中提取本质问题
439
+ - 设计可扩展的系统架构
440
+ - 权衡技术方案
441
+ - 识别架构风险
442
+
443
+ 你相信:
444
+ - 本质和实现必须分离
445
+ - 好的架构从简单规则中生长
446
+ - 复杂性应该被控制而非消除`,
447
+ userPromptTemplate: `用户需求:{user_input}
448
+
449
+ {context}
450
+
451
+ 请进行架构分析:`,
452
+ examples: [
453
+ {
454
+ input: '设计一个电商系统',
455
+ output: '我将首先分析电商系统的核心本质:交易撮合...'
456
+ }
457
+ ],
458
+ outputFormat: 'markdown'
459
+ },
460
+ 'harness-dev': {
461
+ name: 'harness-dev',
462
+ description: '开发实现专家',
463
+ systemPrompt: `你是一个高效的代码实现专家。你擅长:
464
+ - 快速理解和实现需求
465
+ - 编写清晰、可维护的代码
466
+ - 遵循最佳实践
467
+ - 处理边界情况
468
+
469
+ 你相信:
470
+ - 代码即文档
471
+ - 测试是代码的一部分
472
+ - 简单优于复杂`,
473
+ userPromptTemplate: `任务:{user_input}
474
+
475
+ 技术栈:{tech_stack}
476
+
477
+ 请实现代码:`,
478
+ outputFormat: 'code'
479
+ },
480
+ 'guardian-fixer': {
481
+ name: 'guardian-fixer',
482
+ description: '代码审查专家',
483
+ systemPrompt: `你是一个严格的代码审查专家。你擅长:
484
+ - 发现潜在问题
485
+ - 提出改进建议
486
+ - 确保代码质量
487
+ - 平衡效率和安全性
488
+
489
+ 你相信:
490
+ - 细节决定成败
491
+ - 代码审查是质量保障的最后防线
492
+ - 建设性批评比否定更有价值`,
493
+ userPromptTemplate: `代码:\n{code}
494
+
495
+ 审查范围:{scope}
496
+
497
+ 请进行审查:`,
498
+ outputFormat: 'structured'
499
+ }
500
+ };
501
+ /**
502
+ * 动态 Skill 调用器
503
+ */
504
+ export class DynamicSkillRouter {
505
+ skillPrompts;
506
+ judgmentEngine;
507
+ constructor(options) {
508
+ this.skillPrompts = SKILL_PROMPTS;
509
+ this.judgmentEngine = createLLMJudgmentEngine({ useLLM: options?.useLLM ?? true });
510
+ }
511
+ /**
512
+ * 根据判断结果动态调用 Skills
513
+ */
514
+ async routeAndExecute(userInput, judgment, context) {
515
+ const results = {};
516
+ // 并行执行多个 Skills
517
+ const skillPromises = judgment.routing.skills.map(async (skillName) => {
518
+ const skillConfig = this.skillPrompts[skillName];
519
+ if (!skillConfig) {
520
+ console.warn(`[SkillRouter] Unknown skill: ${skillName}`);
521
+ return { skill: skillName, result: null };
522
+ }
523
+ try {
524
+ const result = await this.executeSkill(skillConfig, userInput, context);
525
+ return { skill: skillName, result };
526
+ }
527
+ catch (error) {
528
+ console.error(`[SkillRouter] Skill ${skillName} failed:`, error);
529
+ return { skill: skillName, result: null, error };
530
+ }
531
+ });
532
+ const skillResults = await Promise.all(skillPromises);
533
+ for (const { skill, result, error } of skillResults) {
534
+ results[skill] = result || { error: String(error) };
535
+ }
536
+ return results;
537
+ }
538
+ /**
539
+ * 执行单个 Skill
540
+ */
541
+ async executeSkill(skillConfig, userInput, context) {
542
+ // 构建 prompt
543
+ let prompt = skillConfig.userPromptTemplate.replace('{user_input}', userInput);
544
+ if (context) {
545
+ for (const [key, value] of Object.entries(context)) {
546
+ prompt = prompt.replace(`{${key}}`, String(value));
547
+ }
548
+ }
549
+ // TODO: 调用 LLM 执行 Skill
550
+ // 这里需要集成实际的 LLM 调用
551
+ return `Skill ${skillConfig.name} executed with prompt:\n${prompt}`;
552
+ }
553
+ /**
554
+ * 添加自定义 Skill
555
+ */
556
+ registerSkill(name, config) {
557
+ this.skillPrompts[name] = config;
558
+ }
559
+ /**
560
+ * 获取可用的 Skills
561
+ */
562
+ listSkills() {
563
+ return Object.keys(this.skillPrompts);
564
+ }
565
+ }
566
+ // 导出工厂函数
567
+ export function createDynamicSkillRouter(options) {
568
+ return new DynamicSkillRouter(options);
569
+ }