@bolloon/bolloon-agent 0.1.35 → 0.1.36

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 (194) hide show
  1. package/.playwright-mcp/page-2026-06-16T07-51-45-706Z.yml +130 -0
  2. package/.playwright-mcp/page-2026-06-16T07-56-44-116Z.yml +131 -0
  3. package/Bolloon.md +45 -4
  4. package/Dive-into/CITATION.cff +17 -0
  5. package/Dive-into/LICENSE +25 -0
  6. package/Dive-into/README.md +598 -0
  7. package/Dive-into/README_zh.md +599 -0
  8. package/Dive-into/assets/context.png +0 -0
  9. package/Dive-into/assets/extensibility.png +0 -0
  10. package/Dive-into/assets/iteration.png +0 -0
  11. package/Dive-into/assets/layered_architecture.png +0 -0
  12. package/Dive-into/assets/main_structure.png +0 -0
  13. package/Dive-into/assets/permission.png +0 -0
  14. package/Dive-into/assets/session_compact.png +0 -0
  15. package/Dive-into/assets/subagent.png +0 -0
  16. package/Dive-into/paper/Dive_into_Claude_Code.pdf +0 -0
  17. package/README.md +1 -1
  18. package/dist/agents/p2p-chat-tools.js +6 -6
  19. package/dist/agents/permission-mode.js +115 -0
  20. package/dist/agents/pi-sdk.js +435 -25
  21. package/dist/agents/pre-tool-validator.js +194 -0
  22. package/dist/agents/workflow-pivot-loop.js +113 -12
  23. package/dist/bollharness/src/scripts/checks/check_doc_freshness.js +1 -1
  24. package/dist/bollharness/src/scripts/checks/check_doc_links.js +1 -1
  25. package/dist/bollharness/src/scripts/context_router.js +1 -1
  26. package/dist/bollharness/src/scripts/deploy-guard.js +1 -1
  27. package/dist/bollharness/src/scripts/guard_router.js +1 -1
  28. package/dist/bollharness/src/scripts/hooks/_hook_output.js +1 -1
  29. package/dist/bollharness/src/scripts/hooks/risk-tracker.js +1 -1
  30. package/dist/bollharness-integration/context-router.js +2 -2
  31. package/dist/bollharness-integration/guard-checker.js +1 -1
  32. package/dist/bootstrap/bootstrap.js +3 -0
  33. package/dist/bootstrap/context-collector.js +17 -1
  34. package/dist/bootstrap/context-hierarchy.js +218 -0
  35. package/dist/bootstrap/lifecycle-hooks.js +86 -24
  36. package/dist/bootstrap/project-context.js +10 -3
  37. package/dist/context-compaction/auto-compact.js +144 -0
  38. package/dist/context-compaction/budget-gate.js +28 -0
  39. package/dist/context-compaction/budget-reduce.js +35 -0
  40. package/dist/context-compaction/context-collapse.js +66 -0
  41. package/dist/context-compaction/index.js +21 -0
  42. package/dist/context-compaction/microcompact.js +51 -0
  43. package/dist/context-compaction/pipeline.js +123 -0
  44. package/dist/context-compaction/snip.js +45 -0
  45. package/dist/context-compaction/token-estimator.js +35 -0
  46. package/dist/context-compaction/types.js +19 -0
  47. package/dist/heartbeat/HealthMonitor.js +3 -2
  48. package/dist/index.js +38 -2
  49. package/dist/llm/llm-judgment-client.js +32 -30
  50. package/dist/llm/pi-ai.js +103 -16
  51. package/dist/llm/system-prompt/health.js +129 -0
  52. package/dist/llm/system-prompt/registry.js +246 -0
  53. package/dist/llm/system-prompt/strip-hibsml.js +51 -0
  54. package/dist/llm/tool-manifest/ask_user_input.js +35 -0
  55. package/dist/llm/tool-manifest/bash.js +23 -0
  56. package/dist/llm/tool-manifest/create_file.js +24 -0
  57. package/dist/llm/tool-manifest/fetch_sports_data.js +26 -0
  58. package/dist/llm/tool-manifest/image_search.js +24 -0
  59. package/dist/llm/tool-manifest/index.js +69 -0
  60. package/dist/llm/tool-manifest/mcp.js +43 -0
  61. package/dist/llm/tool-manifest/message_compose.js +31 -0
  62. package/dist/llm/tool-manifest/places.js +83 -0
  63. package/dist/llm/tool-manifest/present_files.js +21 -0
  64. package/dist/llm/tool-manifest/recipe.js +40 -0
  65. package/dist/llm/tool-manifest/recommend_apps.js +23 -0
  66. package/dist/llm/tool-manifest/str_replace.js +27 -0
  67. package/dist/llm/tool-manifest/types.js +7 -0
  68. package/dist/llm/tool-manifest/view.js +24 -0
  69. package/dist/llm/tool-manifest/weather.js +27 -0
  70. package/dist/llm/tool-manifest/web.js +51 -0
  71. package/dist/network/p2p-direct.js +23 -0
  72. package/dist/network/source-intent-broadcaster.js +203 -0
  73. package/dist/network/source-intent.js +100 -0
  74. package/dist/pi-ecosystem-judgment/adaptive-scan.js +48 -0
  75. package/dist/pi-ecosystem-judgment/injection-gate.js +54 -12
  76. package/dist/pi-ecosystem-judgment/value-injection.js +8 -2
  77. package/dist/security/context-router-tool.js +1 -1
  78. package/dist/security/input-scanner.js +223 -0
  79. package/dist/web/client.js +3677 -4161
  80. package/dist/web/components/p2p/P2PModal.js +188 -0
  81. package/dist/web/components/p2p/index.js +264 -226
  82. package/dist/web/components/p2p/p2p-modal.js +657 -0
  83. package/dist/web/components/p2p/p2p-tools.js +248 -0
  84. package/dist/web/index.html +58 -67
  85. package/dist/web/server.js +299 -117
  86. package/dist/web/style.css +531 -249
  87. package/dist/web/ui/message-renderer.js +463 -0
  88. package/dist/web/ui/step-timeline.js +375 -0
  89. package/lefthook.yml +4 -0
  90. package/package.json +1 -1
  91. package/scripts/auto-evolve-loop.ts +105 -0
  92. package/scripts/build-web.ts +35 -1
  93. package/scripts/validate-system-prompt.ts +142 -0
  94. package/src/agents/p2p-chat-tools.ts +6 -6
  95. package/src/agents/permission-mode.ts +127 -0
  96. package/src/agents/pi-sdk.ts +461 -28
  97. package/src/agents/pre-tool-validator.ts +213 -0
  98. package/src/agents/workflow-pivot-loop.ts +110 -19
  99. package/src/bollharness/CLAUDE.md +1 -1
  100. package/src/bollharness/README.md +2 -2
  101. package/src/bollharness/README.zh-CN.md +2 -2
  102. package/src/bollharness/reference/boll-reference/scripts/hooks/find-boll-root.sh +2 -2
  103. package/src/bollharness/scripts/context-fragments/truth-source-hierarchy.md +2 -2
  104. package/src/bollharness/scripts/context-fragments/version-sources.md +1 -1
  105. package/src/bollharness/scripts/hooks/find-project-root.sh +4 -4
  106. package/src/bollharness/src/scripts/checks/check_doc_freshness.ts +1 -1
  107. package/src/bollharness/src/scripts/checks/check_doc_links.ts +1 -1
  108. package/src/bollharness/src/scripts/context_router.ts +1 -1
  109. package/src/bollharness/src/scripts/deploy-guard.ts +1 -1
  110. package/src/bollharness/src/scripts/guard_router.ts +1 -1
  111. package/src/bollharness/src/scripts/hooks/_hook_output.ts +1 -1
  112. package/src/bollharness/src/scripts/hooks/risk-tracker.ts +1 -1
  113. package/src/bollharness/templates/scaffold/.gitignore.append +1 -1
  114. package/src/bollharness/templates/scaffold/CLAUDE.md +2 -2
  115. package/src/bollharness-integration/context-router.ts +2 -2
  116. package/src/bollharness-integration/guard-checker.ts +1 -1
  117. package/src/bootstrap/bootstrap.ts +3 -0
  118. package/src/bootstrap/context-collector.ts +30 -1
  119. package/src/bootstrap/context-hierarchy.ts +283 -0
  120. package/src/bootstrap/lifecycle-hooks.ts +139 -26
  121. package/src/bootstrap/project-context.ts +11 -3
  122. package/src/context-compaction/auto-compact.ts +153 -0
  123. package/src/context-compaction/budget-gate.ts +32 -0
  124. package/src/context-compaction/budget-reduce.ts +37 -0
  125. package/src/context-compaction/context-collapse.ts +72 -0
  126. package/src/context-compaction/index.ts +24 -0
  127. package/src/context-compaction/microcompact.ts +54 -0
  128. package/src/context-compaction/pipeline.ts +133 -0
  129. package/src/context-compaction/snip.ts +51 -0
  130. package/src/context-compaction/token-estimator.ts +36 -0
  131. package/src/context-compaction/types.ts +99 -0
  132. package/src/heartbeat/HealthMonitor.ts +3 -2
  133. package/src/index.ts +36 -2
  134. package/src/llm/llm-judgment-client.ts +36 -35
  135. package/src/llm/pi-ai.ts +111 -16
  136. package/src/llm/system-prompt/health.ts +159 -0
  137. package/src/llm/system-prompt/layers/channel/local.md +14 -0
  138. package/src/llm/system-prompt/layers/channel/p2p-agent.md +18 -0
  139. package/src/llm/system-prompt/layers/channel/p2p-visitor.md +19 -0
  140. package/src/llm/system-prompt/layers/core/artifacts_storage.md +89 -0
  141. package/src/llm/system-prompt/layers/core/evenhandedness.md +21 -0
  142. package/src/llm/system-prompt/layers/core/hibs_reminders.md +15 -0
  143. package/src/llm/system-prompt/layers/core/identity.md +37 -0
  144. package/src/llm/system-prompt/layers/core/knowledge.md +17 -0
  145. package/src/llm/system-prompt/layers/core/memory_system.md +12 -0
  146. package/src/llm/system-prompt/layers/core/network_filesystem.md +28 -0
  147. package/src/llm/system-prompt/layers/core/refusal.md +37 -0
  148. package/src/llm/system-prompt/layers/core/tone.md +31 -0
  149. package/src/llm/system-prompt/layers/core/tools.thin.md +13 -0
  150. package/src/llm/system-prompt/layers/core/wellbeing.md +41 -0
  151. package/src/llm/system-prompt/layers/role/architect.md +20 -0
  152. package/src/llm/system-prompt/layers/role/expert.md +19 -0
  153. package/src/llm/system-prompt/layers/role/implementer.md +15 -0
  154. package/src/llm/system-prompt/layers/role/security.md +15 -0
  155. package/src/llm/system-prompt/layers/tool/artifacts.md +72 -0
  156. package/src/llm/system-prompt/layers/tool/bash.md +25 -0
  157. package/src/llm/system-prompt/layers/tool/hibs_api.md +171 -0
  158. package/src/llm/system-prompt/layers/tool/image_search.md +70 -0
  159. package/src/llm/system-prompt/layers/tool/manifest.md +89 -0
  160. package/src/llm/system-prompt/layers/tool/mcp_apps.md +53 -0
  161. package/src/llm/system-prompt/layers/tool/web_search.md +83 -0
  162. package/src/llm/system-prompt/registry.ts +325 -0
  163. package/src/llm/system-prompt/strip-hibsml.ts +52 -0
  164. package/src/llm/tool-manifest/ask_user_input.ts +37 -0
  165. package/src/llm/tool-manifest/bash.ts +25 -0
  166. package/src/llm/tool-manifest/create_file.ts +26 -0
  167. package/src/llm/tool-manifest/fetch_sports_data.ts +28 -0
  168. package/src/llm/tool-manifest/image_search.ts +26 -0
  169. package/src/llm/tool-manifest/index.ts +88 -0
  170. package/src/llm/tool-manifest/mcp.ts +46 -0
  171. package/src/llm/tool-manifest/message_compose.ts +33 -0
  172. package/src/llm/tool-manifest/places.ts +86 -0
  173. package/src/llm/tool-manifest/present_files.ts +23 -0
  174. package/src/llm/tool-manifest/recipe.ts +42 -0
  175. package/src/llm/tool-manifest/recommend_apps.ts +25 -0
  176. package/src/llm/tool-manifest/str_replace.ts +29 -0
  177. package/src/llm/tool-manifest/types.ts +52 -0
  178. package/src/llm/tool-manifest/view.ts +26 -0
  179. package/src/llm/tool-manifest/weather.ts +29 -0
  180. package/src/llm/tool-manifest/web.ts +54 -0
  181. package/src/network/p2p-direct.ts +22 -0
  182. package/src/network/source-intent-broadcaster.ts +242 -0
  183. package/src/network/source-intent.ts +167 -0
  184. package/src/security/context-router-tool.ts +1 -1
  185. package/src/security/input-scanner.ts +287 -0
  186. package/src/web/client.js +271 -2817
  187. package/src/web/client.ts +4326 -0
  188. package/src/web/index.html +58 -67
  189. package/src/web/server.ts +301 -141
  190. package/src/web/style.css +531 -249
  191. package/src/web/ui/message-renderer.ts +540 -0
  192. package/src/web/ui/step-timeline.ts +394 -0
  193. package/test-results/.last-run.json +6 -0
  194. 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 +285 -0
@@ -0,0 +1,129 @@
1
+ /**
2
+ * system-prompt health — 每层 lifecycle 状态扫描
3
+ *
4
+ * 严格对齐 deusyu 论文 "Harness Gardening 3-6 月" + walkinglabs Lifecycle 4-stage
5
+ * + 马书 ch05+ch13 systemPromptSection + 89 FF 的版本/owner 治理思想.
6
+ *
7
+ * 设计:
8
+ * - 输入: 完整 layer list (assembleSystemPrompt 返回的 layers[])
9
+ * - 输出: 每层 health 状态 (ok | stale | overdue-review | missing-frontmatter)
10
+ * - 失败静默: 任何 layer 读失败 → 标 'missing-frontmatter' 而非抛错
11
+ *
12
+ * 决策 (cross-repo_caveats 选边):
13
+ * - dynamic layers (function source) → 标 'ok' (last_reviewed_at = now), 视作 runtime-managed
14
+ * - frontmatter author 拒绝 'llm-judge' 之外的不合法值 → 标 'missing-frontmatter'
15
+ */
16
+ const DAY_MS = 24 * 60 * 60 * 1000;
17
+ /** 兼容运行时: dynamic layer 没有 meta, 视作 'dynamic' (last_reviewed = now) */
18
+ function isDynamic(l) {
19
+ return l.source === 'function';
20
+ }
21
+ /** 评估单层 health */
22
+ export function evaluateLayer(l, now = new Date()) {
23
+ if (isDynamic(l)) {
24
+ return {
25
+ id: l.id,
26
+ health: 'dynamic',
27
+ ageDays: 0,
28
+ ttlDays: -1,
29
+ remainingDays: -1,
30
+ author: l.meta?.author ?? 'runtime',
31
+ lastReviewedAt: now.toISOString(),
32
+ active: false, // 由 caller (assembleSystemPrompt) 决定
33
+ };
34
+ }
35
+ if (!l.meta) {
36
+ // frontmatter 解析失败或缺失
37
+ return {
38
+ id: l.id,
39
+ health: 'missing-frontmatter',
40
+ ageDays: -1,
41
+ ttlDays: -1,
42
+ remainingDays: -1,
43
+ author: null,
44
+ lastReviewedAt: null,
45
+ active: false,
46
+ };
47
+ }
48
+ const reviewedAt = new Date(l.meta.lastReviewedAt).getTime();
49
+ if (isNaN(reviewedAt)) {
50
+ return {
51
+ id: l.id,
52
+ health: 'missing-frontmatter',
53
+ ageDays: -1,
54
+ ttlDays: l.meta.ttlDays,
55
+ remainingDays: -1,
56
+ author: l.meta.author,
57
+ lastReviewedAt: l.meta.lastReviewedAt,
58
+ active: false,
59
+ };
60
+ }
61
+ const ageMs = now.getTime() - reviewedAt;
62
+ const ageDays = Math.floor(ageMs / DAY_MS);
63
+ const remainingDays = l.meta.ttlDays - ageDays;
64
+ let health;
65
+ if (remainingDays < 0) {
66
+ health = 'overdue-review';
67
+ }
68
+ else if (remainingDays < l.meta.ttlDays * 0.2) {
69
+ health = 'stale'; // 剩余 < 20% ttl 触发告警
70
+ }
71
+ else {
72
+ health = 'ok';
73
+ }
74
+ return {
75
+ id: l.id,
76
+ health,
77
+ ageDays,
78
+ ttlDays: l.meta.ttlDays,
79
+ remainingDays,
80
+ author: l.meta.author,
81
+ lastReviewedAt: l.meta.lastReviewedAt,
82
+ notes: l.meta.notes,
83
+ active: false, // caller 决定
84
+ };
85
+ }
86
+ /** 评估整组 layer (输入: assembleSystemPrompt 返回的 layers[]) */
87
+ export function evaluateLayers(layers, now = new Date()) {
88
+ const entries = layers.map((l) => evaluateLayer(l, now));
89
+ return summarize(entries, now);
90
+ }
91
+ /** 汇总: 给一批 entries 算 counts */
92
+ function summarize(entries, now) {
93
+ const counts = { ok: 0, stale: 0, overdue: 0, missing: 0, dynamic: 0 };
94
+ for (const e of entries) {
95
+ if (e.health === 'ok')
96
+ counts.ok++;
97
+ else if (e.health === 'stale')
98
+ counts.stale++;
99
+ else if (e.health === 'overdue-review')
100
+ counts.overdue++;
101
+ else if (e.health === 'missing-frontmatter')
102
+ counts.missing++;
103
+ else if (e.health === 'dynamic')
104
+ counts.dynamic++;
105
+ }
106
+ return {
107
+ scannedAt: now.toISOString(),
108
+ total: entries.length,
109
+ okCount: counts.ok,
110
+ staleCount: counts.stale,
111
+ overdueCount: counts.overdue,
112
+ missingCount: counts.missing,
113
+ dynamicCount: counts.dynamic,
114
+ entries,
115
+ };
116
+ }
117
+ /** 标记当前 context 下激活的 layer (在 assembleSystemPrompt 调用后用) */
118
+ export function markActive(report, activeIds) {
119
+ return {
120
+ ...report,
121
+ entries: report.entries.map((e) => ({ ...e, active: activeIds.has(e.id) })),
122
+ };
123
+ }
124
+ // ============================================================
125
+ // 测试钩子
126
+ // ============================================================
127
+ export function _resetHealthForTest() {
128
+ // 无内部状态, 保留 API 一致
129
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * registry.ts — system prompt 层注册 + 装配器
3
+ *
4
+ * 设计原则:
5
+ * - 每个 layer 独立文件, 可单独更新/审查/回滚
6
+ * - 装配器按 channel + role + tool 过滤, 输出最终 system prompt
7
+ * - 字符预算按"层级"硬限, 避免腐烂
8
+ * - 远程 P2P layer (function source) 可被远程智能体覆盖本地 layer
9
+ *
10
+ * 装配顺序 (低 priority 先, 高 priority 后):
11
+ * core/identity < core/knowledge < core/tools < channel/* < role/* < tool/* < dynamic/*
12
+ */
13
+ import * as fs from 'fs/promises';
14
+ import * as path from 'path';
15
+ import { fileURLToPath } from 'url';
16
+ import { stripHibsml } from './strip-hibsml.js';
17
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
+ const LAYERS_DIR = path.join(__dirname, 'layers');
19
+ /** 解析 .md frontmatter (手写 3 行 regex, 不引 yaml 依赖) */
20
+ function parseFrontmatter(raw) {
21
+ const m = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
22
+ if (!m)
23
+ return { meta: null, body: raw };
24
+ const block = m[1];
25
+ const body = m[2];
26
+ const get = (key) => {
27
+ const re = new RegExp(`^${key}:\\s*(.+)$`, 'm');
28
+ const found = block.match(re);
29
+ return found ? found[1].trim() : undefined;
30
+ };
31
+ const addedAt = get('added_at');
32
+ const lastReviewedAt = get('last_reviewed_at');
33
+ const ttlDaysStr = get('ttl_days');
34
+ const author = get('author');
35
+ const notes = get('notes');
36
+ if (!addedAt || !lastReviewedAt || !ttlDaysStr || !author) {
37
+ // frontmatter 不完整 → 视为无 metadata (health 会标 missing-frontmatter)
38
+ return { meta: null, body: raw };
39
+ }
40
+ const ttlDays = parseInt(ttlDaysStr, 10);
41
+ if (isNaN(ttlDays) || ttlDays <= 0) {
42
+ return { meta: null, body: raw };
43
+ }
44
+ return {
45
+ meta: { addedAt, lastReviewedAt, ttlDays, author, notes },
46
+ body,
47
+ };
48
+ }
49
+ /**
50
+ * 静态 layer 注册表 — 一个 layer 一个文件
51
+ * 这里只声明 metadata, 内容从 .md 读
52
+ *
53
+ * P-Action 2: meta 默认值, 跟分层 TTL 决策一致
54
+ * safety (refusal / hibs_reminders / tools.thin) = 90
55
+ * channel (local / p2p-* persona) = 180
56
+ * role (expert / architect / implementer / security) = 180
57
+ * tool (bash / search / artifacts / etc) = 270
58
+ * knowledge (knowledge / tone / wellbeing / etc) = 365
59
+ * author = yuanjie (可被 .md frontmatter 覆盖)
60
+ */
61
+ const DEFAULT_META_AUTHOR = 'yuanjie';
62
+ const DEFAULT_ADDED_AT = '2026-06-15';
63
+ const DEFAULT_REVIEWED_AT = '2026-06-15';
64
+ const TTL_SAFETY = 90;
65
+ const TTL_CHANNEL = 180;
66
+ const TTL_ROLE = 180;
67
+ const TTL_TOOL = 270;
68
+ const TTL_KNOWLEDGE = 365;
69
+ const DEFAULT_META = (ttlDays) => ({
70
+ addedAt: DEFAULT_ADDED_AT,
71
+ lastReviewedAt: DEFAULT_REVIEWED_AT,
72
+ ttlDays,
73
+ author: DEFAULT_META_AUTHOR,
74
+ });
75
+ /**
76
+ * P-Action 4 (2026-06-15): 单 layer maxChars 全面收紧, 6 个 layer 停用.
77
+ * 阶段 0 不再对齐 Claude.ai 完整版 (hibs_api / artifacts / mcp_apps / image_search /
78
+ * hibs_reminders / network_filesystem 全是 Claude.ai 平台 runtime, 本地 bolloon 用不到).
79
+ * 停用方法: appliesTo 加 'never' (matchesContext 永远 false), 文件保留可回滚.
80
+ */
81
+ const STATIC_LAYERS = [
82
+ // ── core/ ──
83
+ { id: 'core.identity', version: '1.0.0', priority: 50, appliesTo: ['all'], source: 'static-md', maxChars: 800, meta: DEFAULT_META(TTL_KNOWLEDGE) },
84
+ { id: 'core.knowledge', version: '1.0.0', priority: 60, appliesTo: ['all'], source: 'static-md', maxChars: 600, meta: DEFAULT_META(TTL_KNOWLEDGE) },
85
+ { id: 'core.tools.thin', version: '1.0.0', priority: 70, appliesTo: ['all'], source: 'static-md', maxChars: 400, meta: DEFAULT_META(TTL_SAFETY) },
86
+ { id: 'core.hibs_reminders', version: '1.0.0', priority: 80, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_SAFETY) },
87
+ { id: 'core.refusal', version: '1.0.0', priority: 100, appliesTo: ['all'], source: 'static-md', maxChars: 800, meta: DEFAULT_META(TTL_SAFETY) },
88
+ { id: 'core.tone', version: '1.0.0', priority: 110, appliesTo: ['all'], source: 'static-md', maxChars: 500, meta: DEFAULT_META(TTL_KNOWLEDGE) },
89
+ { id: 'core.wellbeing', version: '1.0.0', priority: 120, appliesTo: ['all'], source: 'static-md', maxChars: 600, meta: DEFAULT_META(TTL_KNOWLEDGE) },
90
+ { id: 'core.evenhandedness', version: '1.0.0', priority: 130, appliesTo: ['all'], source: 'static-md', maxChars: 300, meta: DEFAULT_META(TTL_KNOWLEDGE) },
91
+ { id: 'core.memory_system', version: '1.0.0', priority: 140, appliesTo: ['all'], source: 'static-md', maxChars: 200, meta: DEFAULT_META(TTL_KNOWLEDGE) },
92
+ { id: 'core.artifacts_storage', version: '1.0.0', priority: 145, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_KNOWLEDGE) },
93
+ { id: 'core.network_filesystem', version: '1.0.0', priority: 148, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_KNOWLEDGE) },
94
+ // ── role/ ── 阶段 0 只用 expert, 其他 3 个停用 (节省 + 阶段 0 不分 role)
95
+ { id: 'role.expert', version: '1.0.0', priority: 200, appliesTo: ['all', 'role:expert'], source: 'static-md', maxChars: 500, meta: DEFAULT_META(TTL_ROLE) },
96
+ { id: 'role.architect', version: '1.0.0', priority: 200, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_ROLE) },
97
+ { id: 'role.implementer', version: '1.0.0', priority: 200, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_ROLE) },
98
+ { id: 'role.security', version: '1.0.0', priority: 200, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_ROLE) },
99
+ // ── channel/ ──
100
+ { id: 'channel.local', version: '1.0.0', priority: 150, appliesTo: ['local'], source: 'static-md', maxChars: 500, meta: DEFAULT_META(TTL_CHANNEL) },
101
+ { id: 'channel.p2p-visitor', version: '1.0.0', priority: 150, appliesTo: ['p2p-visitor'], source: 'static-md', maxChars: 700 },
102
+ { id: 'channel.p2p-agent', version: '1.0.0', priority: 150, appliesTo: ['p2p-agent'], source: 'static-md', maxChars: 700 },
103
+ // ── tool/ (按工具调用嵌对应 layer) ──
104
+ { id: 'tool.bash', version: '1.0.0', priority: 250, appliesTo: ['tool:bash'], source: 'static-md', maxChars: 600, meta: DEFAULT_META(TTL_TOOL) },
105
+ { id: 'tool.web_search', version: '1.0.0', priority: 250, appliesTo: ['tool:web_search'], source: 'static-md', maxChars: 600, meta: DEFAULT_META(TTL_TOOL) },
106
+ { id: 'tool.mcp_apps', version: '1.0.0', priority: 250, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_TOOL) },
107
+ { id: 'tool.hibs_api', version: '1.0.0', priority: 250, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_TOOL) },
108
+ { id: 'tool.image_search', version: '1.0.0', priority: 250, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_TOOL) },
109
+ { id: 'tool.artifacts', version: '1.0.0', priority: 250, appliesTo: ['never'], source: 'static-md', maxChars: 0, meta: DEFAULT_META(TTL_TOOL) },
110
+ { id: 'tool.manifest', version: '1.0.0', priority: 250, appliesTo: ['tool:manifest'], source: 'static-md', maxChars: 500, meta: DEFAULT_META(TTL_TOOL) },
111
+ ];
112
+ /**
113
+ * 动态 layer (运行时计算, 例如 project context, judgment 注入)
114
+ * 接入现有 project-context.ts + value-injection.ts, 不重复实现
115
+ */
116
+ const DYNAMIC_LAYERS = [
117
+ {
118
+ id: 'dynamic.project-context',
119
+ version: '1.0.0',
120
+ priority: 300,
121
+ appliesTo: ['all'],
122
+ source: 'function',
123
+ maxChars: 2000, // 4000 → 2000 (P-Action 4), 跟 4 级层次合并上限对齐
124
+ resolver: async () => {
125
+ try {
126
+ const { getCachedBolloonContext } = await import('../../pi-ecosystem-judgment/human-value-pipeline.js');
127
+ const { formatContextForSystemPrompt } = await import('../../bootstrap/project-context.js');
128
+ const ctx = await getCachedBolloonContext({ cwd: process.cwd() });
129
+ return formatContextForSystemPrompt(ctx, { maxChars: 4000 });
130
+ }
131
+ catch {
132
+ return '';
133
+ }
134
+ },
135
+ },
136
+ ];
137
+ /**
138
+ * P-Action 4 (2026-06-15): 总字符上限 15000 → 4500.
139
+ * 阶段 0 单次 system prompt 控制在 ≤ 4.5KB (≈ 1125 tokens).
140
+ * 配合单 layer maxChars 收紧 + 6 layer 停用, 每轮 chat 节省 ≈ 2625 tokens.
141
+ */
142
+ const TOTAL_BUDGET = 4500;
143
+ export async function assembleSystemPrompt(ctx) {
144
+ // 1. 收集所有 layer
145
+ const allLayers = [];
146
+ for (const meta of STATIC_LAYERS) {
147
+ const { content, meta: sectionMeta } = await loadStaticLayer(meta.id);
148
+ allLayers.push({ ...meta, content, meta: sectionMeta ?? meta.meta });
149
+ }
150
+ for (const dyn of DYNAMIC_LAYERS) {
151
+ allLayers.push({ ...dyn, meta: dyn.meta });
152
+ }
153
+ // 2. 过滤
154
+ const matched = allLayers.filter((l) => matchesContext(l, ctx));
155
+ // 3. 排序 (priority 低 → 高, 同 priority 按 id 字母)
156
+ matched.sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
157
+ // 4. 装配 + 截断
158
+ const parts = [];
159
+ const used = [];
160
+ const truncated = [];
161
+ let usedChars = 0;
162
+ for (const layer of matched) {
163
+ if (usedChars >= TOTAL_BUDGET) {
164
+ truncated.push(layer.id);
165
+ continue;
166
+ }
167
+ let content = '';
168
+ if (layer.source === 'function' && layer.resolver) {
169
+ try {
170
+ content = await layer.resolver();
171
+ }
172
+ catch {
173
+ content = '';
174
+ }
175
+ }
176
+ else {
177
+ content = layer.content || '';
178
+ }
179
+ if (content.length > layer.maxChars) {
180
+ content = content.slice(0, layer.maxChars) + '\n[… 已截断]';
181
+ truncated.push(layer.id);
182
+ }
183
+ if (usedChars + content.length > TOTAL_BUDGET) {
184
+ const remain = TOTAL_BUDGET - usedChars;
185
+ if (remain > 100) {
186
+ content = content.slice(0, remain) + '\n[… 预算截断]';
187
+ }
188
+ else {
189
+ truncated.push(layer.id);
190
+ continue;
191
+ }
192
+ }
193
+ parts.push(`<!-- ${layer.id}@${layer.version} -->\n${content}`);
194
+ used.push(layer.id);
195
+ usedChars += content.length;
196
+ }
197
+ return {
198
+ text: stripHibsml(parts.join('\n\n')),
199
+ layerIds: used,
200
+ totalChars: usedChars,
201
+ truncated,
202
+ layers: matched, // P-Action 2: 把 meta 也带回, 供 health 端点
203
+ };
204
+ }
205
+ function matchesContext(layer, ctx) {
206
+ if (layer.appliesTo.includes('all'))
207
+ return true;
208
+ for (const a of layer.appliesTo) {
209
+ if (a === ctx.channel)
210
+ return true;
211
+ if (a.startsWith('role:') && a.slice(5) === ctx.role)
212
+ return true;
213
+ if (a.startsWith('tool:') && a.slice(5) === ctx.tool)
214
+ return true;
215
+ }
216
+ return false;
217
+ }
218
+ async function loadStaticLayer(id) {
219
+ const path2md = idToPath(id);
220
+ try {
221
+ const raw = await fs.readFile(path2md, 'utf-8');
222
+ const { meta, body } = parseFrontmatter(raw);
223
+ return { content: body, meta };
224
+ }
225
+ catch (err) {
226
+ console.warn(`[system-prompt] layer ${id} 读失败: ${err.message?.slice(0, 100)}`);
227
+ return { content: `<!-- ${id}: 文件丢失 -->`, meta: null };
228
+ }
229
+ }
230
+ function idToPath(id) {
231
+ // core.refusal → layers/core/refusal.md
232
+ // tool.bash → layers/tool/bash.md
233
+ // channel.p2p-visitor → layers/channel/p2p-visitor.md
234
+ // core.tools.thin → layers/core/tools.thin.md (注意: 第一段是 group, 后面整段是文件名)
235
+ const [group, ...rest] = id.split('.');
236
+ return path.join(LAYERS_DIR, group, `${rest.join('.')}.md`);
237
+ }
238
+ /** 列所有 layer, 供调试 / reviewer 看 */
239
+ export function listLayers() {
240
+ return [...STATIC_LAYERS, ...DYNAMIC_LAYERS.map((l) => {
241
+ const { resolver, ...rest } = l;
242
+ return rest;
243
+ })];
244
+ }
245
+ /** 整体版本号 — 跟 hibs 1 对齐 */
246
+ export const SYSTEM_PROMPT_VERSION = 'hibs-1.v1.0.0';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * strip-hibsml.ts — 把 hibsml 协议标签转成 bolloon 标记
3
+ *
4
+ * hibsml 是 hibs 的协议: {hibsml:cite} {hibsml:invoke} {hibsml:thinking_mode}
5
+ * bolloon 不解析这些, 但传给 LLM 之前要"金脱除":
6
+ * - cite → [CITE:index]
7
+ * - invoke → 简化
8
+ * - thinking_mode → 注释形式保留
9
+ * - 其他标签 → 整段脱除
10
+ *
11
+ * 不脱除 hibsml 标签会让 LLM 看到原文标记 (raw XML) 误以为是工具调用.
12
+ */
13
+ const HIBML_REPLACEMENTS = [
14
+ // {hibsml:cite index="0-1,3-5"}...{/hibsml:cite} → [CITE:0-1,3-5] ... [ENDCITE]
15
+ [
16
+ /\{hibsml:cite\s+index="([^"]+)"\}/g,
17
+ (_m, idx) => `[CITE:${idx}]`,
18
+ ],
19
+ [/\{\/hibsml:cite\}/g, '[ENDCITE]'],
20
+ // {hibsml:invoke name="X"} ... {/hibsml:invoke} → [TOOL:X] ... [ENDTOOL]
21
+ [
22
+ /\{hibsml:invoke\s+name="([^"]+)"\}/g,
23
+ (_m, name) => `[TOOL:${name}]`,
24
+ ],
25
+ [/\{\/hibsml:invoke\}/g, '[ENDTOOL]'],
26
+ // {hibsml:parameter name="X"}val{/hibsml:parameter} → [P:X]val[/P]
27
+ [
28
+ /\{hibsml:parameter\s+name="([^"]+)"\}/g,
29
+ (_m, name) => `[P:${name}]`,
30
+ ],
31
+ [/\{\/hibsml:parameter\}/g, '[/P]'],
32
+ // {hibsml:thinking_mode}auto{/hibsml:thinking_mode} → [THINKING:auto] (保留)
33
+ [
34
+ /\{hibsml:thinking_mode\}(\w+)\{\/hibsml:thinking_mode\}/g,
35
+ (_m, mode) => `[THINKING:${mode}]`,
36
+ ],
37
+ // 脱除 voice_note (hibs 1 明确说永远不用)
38
+ [/<details><summary>.*?<\/summary>.*?<\/details>/gs, ''],
39
+ // 任何其他 hibsml:* 标签
40
+ [/\{hibsml:[a-z_]+\}/g, ''],
41
+ [/\{\/hibsml:[a-z_]+\}/g, ''],
42
+ ];
43
+ export function stripHibsml(text) {
44
+ let out = text;
45
+ for (const [re, rep] of HIBML_REPLACEMENTS) {
46
+ out = out.replace(re, rep);
47
+ }
48
+ // 收尾: 多个空行合并
49
+ out = out.replace(/\n{3,}/g, '\n\n');
50
+ return out.trim();
51
+ }
@@ -0,0 +1,35 @@
1
+ export const ask_user_input_v0 = {
2
+ id: 'ask_user_input_v0',
3
+ name: 'ask_user_input_v0',
4
+ oneLine: '在提供建议前展示可点击的选项以收集用户偏好 (移动端友好).',
5
+ description: '此工具显示交互式按钮, 用户可以点击按钮来回答, 在移动端比键入要容易得多. 用于引出信息 (ELICITATION) — 当你需要了解用户的偏好、约束或目标以提供有用建议时.',
6
+ whenToUse: [
7
+ '需要了解用户的偏好/约束/目标以提供有用建议',
8
+ '示例: 帮我制定锻炼计划 → 询问目标(力量/有氧/减重)、可用时间、设备访问',
9
+ '示例: 帮我为朋友挑礼物 → 询问场合、预算、朋友的兴趣',
10
+ ],
11
+ whenNotToUse: [
12
+ '用户问 A 还是 B (想要分析, 不是按钮)',
13
+ '用户在发泄或处理情绪',
14
+ '用户询问观点',
15
+ '事实问题 (直接回答)',
16
+ '用户需要散文形式反馈',
17
+ ],
18
+ parameters: [
19
+ { name: 'questions', type: 'array', required: true, description: '1-3 个问题', items: {
20
+ name: 'question', type: 'object', required: true, description: '单个问题', properties: [
21
+ { name: 'question', type: 'string', required: true, description: '向用户显示的问题' },
22
+ { name: 'type', type: 'enum', required: false, description: 'single_select | multi-select | rank_priorities', enumValues: ['single_select', 'multi_select', 'rank_priorities'], default: 'single_select' },
23
+ { name: 'options', type: 'array', required: true, description: '2-4 个带短标签的选项', minItems: 2, maxItems: 4, items: {
24
+ name: 'option', type: 'object', required: true, description: '选项', properties: [
25
+ { name: 'label', type: 'string', required: true, description: '短标签' },
26
+ { name: 'description', type: 'string', required: false, description: '选项描述' },
27
+ ],
28
+ } },
29
+ ],
30
+ } },
31
+ ],
32
+ callExample: `[TOOL:ask_user_input_v0]
33
+ [P:questions]${'${'}JSON.stringify([{"question":"你的预算?","options":[{"label":"<500"},{"label":"500-2000"}]}])[ENDTOOL]`,
34
+ layerId: 'tool.manifest',
35
+ };
@@ -0,0 +1,23 @@
1
+ export const bash_tool = {
2
+ id: 'bash_tool',
3
+ name: 'bash_tool',
4
+ oneLine: '在容器中运行 bash 命令.',
5
+ description: '在容器中运行 bash 命令. 必须用 description 参数说明为什么跑.',
6
+ whenToUse: [
7
+ '需要执行 shell 命令 (ls, mkdir, npm, git 等)',
8
+ '需要跑构建/测试/脚本',
9
+ ],
10
+ whenNotToUse: [
11
+ '读取文件 (用 view)',
12
+ '编辑文件 (用 str_replace 或 create_file)',
13
+ ],
14
+ parameters: [
15
+ { name: 'command', type: 'string', required: true, description: '要运行的 bash 命令' },
16
+ { name: 'description', type: 'string', required: true, description: '为什么我要运行此命令' },
17
+ ],
18
+ callExample: `[TOOL:bash_tool]
19
+ [P:command]ls -la /tmp
20
+ [P:description]列出 /tmp 目录内容
21
+ [ENDTOOL]`,
22
+ layerId: 'tool.bash',
23
+ };
@@ -0,0 +1,24 @@
1
+ export const create_file = {
2
+ id: 'create_file',
3
+ name: 'create_file',
4
+ oneLine: '在容器中创建带有内容的新文件.',
5
+ description: '如果路径已存在则失败 — 使用 str_replace 编辑现有文件, 或使用 bash_tool (cat > path << EOF) 覆盖.',
6
+ whenToUse: [
7
+ '创建新文件',
8
+ '需要写完整的文件内容',
9
+ ],
10
+ whenNotToUse: [
11
+ '编辑已有文件 (用 str_replace)',
12
+ ],
13
+ parameters: [
14
+ { name: 'description', type: 'string', required: true, description: '为什么我要创建此文件' },
15
+ { name: 'file_text', type: 'string', required: true, description: '要写入的文件内容' },
16
+ { name: 'path', type: 'string', required: true, description: '要创建的文件路径' },
17
+ ],
18
+ callExample: `[TOOL:create_file]
19
+ [P:description]新建 README
20
+ [P:file_text]# Project\n\nHello world
21
+ [P:path]/home/bolloon/README.md
22
+ [ENDTOOL]`,
23
+ layerId: 'tool.manifest',
24
+ };
@@ -0,0 +1,26 @@
1
+ export const fetch_sports_data = {
2
+ id: 'fetch_sports_data',
3
+ name: 'fetch_sports_data',
4
+ oneLine: '获取当前/即将进行/最近的体育数据 (比分/积分榜/比赛统计).',
5
+ description: '对于最近和即将进行的比赛的数据、比分、统计, 优先使用此工具而非 Web 搜索. 工作流: 1) 获取比分 2) 根据比赛 ID 获取统计 3) 然后才回复用户.',
6
+ whenToUse: [
7
+ '用户对某场比赛的比分感兴趣',
8
+ '广泛查询 (最近的 NBA 结果等)',
9
+ '需要详细比赛统计',
10
+ ],
11
+ whenNotToUse: [
12
+ '历史比赛 (很久以前)',
13
+ '非体育数据',
14
+ ],
15
+ parameters: [
16
+ { name: 'data_type', type: 'enum', required: true, description: 'scores | standings | game_stats', enumValues: ['scores', 'standings', 'game_stats'] },
17
+ { name: 'game_id', type: 'string', required: false, description: 'SportRadar 比赛 ID (data_type=game_stats 时必需)' },
18
+ { name: 'league', type: 'enum', required: true, description: 'nfl/nba/nhl/mlb/wnba/ncaafb/ncaamb/ncaawb/epl/la_liga/serie_a/bundesliga/ligue_1/mls/champions_league/tennis/golf/nascar/cricket/mma', enumValues: ['nfl', 'nba', 'nhl', 'mlb', 'wnba', 'ncaafb', 'ncaamb', 'ncaawb', 'epl', 'la_liga', 'serie_a', 'bundesliga', 'ligue_1', 'mls', 'champions_league', 'tennis', 'golf', 'nascar', 'cricket', 'mma'] },
19
+ { name: 'team', type: 'string', required: false, description: '可选的球队名称' },
20
+ ],
21
+ callExample: `[TOOL:fetch_sports_data]
22
+ [P:data_type]scores
23
+ [P:league]nba
24
+ [ENDTOOL]`,
25
+ layerId: 'tool.manifest',
26
+ };
@@ -0,0 +1,24 @@
1
+ export const image_search = {
2
+ id: 'image_search',
3
+ name: 'image_search',
4
+ oneLine: '在 Web 上查找图像并连同尺寸返回 (3-4 张/次).',
5
+ description: '对于视觉内容可增强用户理解的任何查询, 默认使用图像搜索. 当交付物主要是文本时跳过.',
6
+ whenToUse: [
7
+ '地点、动物、食物、人物、产品、风格、图表、历史照片、练习',
8
+ '关于视觉事物的简单事实 ("埃菲尔铁塔是哪一年造的?" → 展示它)',
9
+ '多项目内容 (指南、列表、比较、时间线、步骤) — 交错图像',
10
+ ],
11
+ whenNotToUse: [
12
+ '文本输出 (撰写邮件、代码、文章)',
13
+ '数字/数据、编码查询、技术支持、分步说明',
14
+ '关于非视觉主题的分析',
15
+ ],
16
+ parameters: [
17
+ { name: 'max_results', type: 'integer', required: false, description: '返回图片数 (默认 3, 最少 3, 最多 5)', minimum: 3, maximum: 5, default: 3 },
18
+ { name: 'query', type: 'string', required: true, description: '搜索查询 (3-6 词具体)' },
19
+ ],
20
+ callExample: `[TOOL:image_search]
21
+ [P:query]Eiffel Tower Paris
22
+ [ENDTOOL]`,
23
+ layerId: 'tool.image_search',
24
+ };
@@ -0,0 +1,69 @@
1
+ import { ask_user_input_v0 } from './ask_user_input.js';
2
+ import { bash_tool } from './bash.js';
3
+ import { create_file } from './create_file.js';
4
+ import { fetch_sports_data } from './fetch_sports_data.js';
5
+ import { image_search } from './image_search.js';
6
+ import { message_compose_v1 } from './message_compose.js';
7
+ import { places_search, places_map_display_v0 } from './places.js';
8
+ import { present_files } from './present_files.js';
9
+ import { recipe_display_v0 } from './recipe.js';
10
+ import { recommend_bolloon_apps } from './recommend_apps.js';
11
+ import { search_mcp_registry, suggest_connectors } from './mcp.js';
12
+ import { str_replace } from './str_replace.js';
13
+ import { view } from './view.js';
14
+ import { web_search, web_fetch } from './web.js';
15
+ import { weather_fetch } from './weather.js';
16
+ const ALL = [
17
+ ask_user_input_v0,
18
+ bash_tool,
19
+ create_file,
20
+ fetch_sports_data,
21
+ image_search,
22
+ message_compose_v1,
23
+ places_search,
24
+ places_map_display_v0,
25
+ present_files,
26
+ recipe_display_v0,
27
+ recommend_bolloon_apps,
28
+ search_mcp_registry,
29
+ suggest_connectors,
30
+ str_replace,
31
+ view,
32
+ web_search,
33
+ web_fetch,
34
+ weather_fetch,
35
+ ];
36
+ export function listTools() {
37
+ return ALL;
38
+ }
39
+ export function getToolManifest(id) {
40
+ return ALL.find((t) => t.id === id);
41
+ }
42
+ export function getToolsByLayer(layerId) {
43
+ return ALL.filter((t) => t.layerId === layerId);
44
+ }
45
+ /**
46
+ * 缩到 1-3KB 装进 system prompt
47
+ * 包含: 名字 + 一句话 + whenToUse(2) + whenNotToUse(1) + 1 行示例
48
+ *
49
+ * 不包含: 完整 parameters schema (那是 PiAI 客户端在调用时读)
50
+ */
51
+ export function formatForPrompt(tools) {
52
+ const list = tools ?? ALL;
53
+ const lines = [
54
+ `## 工具清单 (${list.length} 个, 详细 schema 在 src/llm/tool-manifest/, 调用时由 PiAI 客户端解析)`,
55
+ '',
56
+ ];
57
+ for (const t of list) {
58
+ lines.push(`### ${t.id}`);
59
+ lines.push(`- **用途**: ${t.oneLine}`);
60
+ lines.push(`- **何时用**: ${t.whenToUse[0] ?? ''}`);
61
+ if (t.whenToUse.length > 1) {
62
+ lines.push(` - 也: ${t.whenToUse.slice(1, 3).join(' / ')}`);
63
+ }
64
+ lines.push(`- **何时不用**: ${t.whenNotToUse[0] ?? ''}`);
65
+ lines.push(`- **示例**: ${t.callExample.replace(/\n/g, ' ')}`);
66
+ lines.push('');
67
+ }
68
+ return lines.join('\n');
69
+ }