@octopi-agent/engine 0.98.4 → 0.102.10

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 (301) hide show
  1. package/dist/config-schema/agent.d.ts +35 -5
  2. package/dist/config-schema/agent.js +24 -4
  3. package/dist/config-schema/context.d.ts +6 -36
  4. package/dist/config-schema/context.js +4 -28
  5. package/dist/config-schema/engine.d.ts +57 -160
  6. package/dist/config-schema/engine.js +1 -5
  7. package/dist/config-schema/governance.d.ts +8 -1
  8. package/dist/config-schema/governance.js +8 -1
  9. package/dist/config-schema/models.d.ts +2 -8
  10. package/dist/config-schema/models.js +0 -2
  11. package/dist/config-schema/run.d.ts +2 -2
  12. package/dist/config-schema/run.js +2 -2
  13. package/dist/config-schema/shared.d.ts +0 -3
  14. package/dist/config-schema/shared.js +0 -2
  15. package/dist/config-schema/substrate.d.ts +14 -88
  16. package/dist/config-schema/substrate.js +22 -107
  17. package/dist/config.d.ts +45 -113
  18. package/dist/config.js +8 -2
  19. package/dist/harness/activation/dispatcher.js +7 -0
  20. package/dist/harness/activation/inbox.d.ts +3 -3
  21. package/dist/harness/activation/inbox.js +3 -3
  22. package/dist/harness/activation/runtime.js +13 -5
  23. package/dist/harness/activation/types.d.ts +2 -2
  24. package/dist/harness/agent/builder.d.ts +24 -3
  25. package/dist/harness/agent/builder.js +131 -27
  26. package/dist/harness/agent/config-bridge.js +9 -2
  27. package/dist/harness/agent/config-integrity.js +19 -2
  28. package/dist/harness/agent/wire-agent-builder.d.ts +11 -3
  29. package/dist/harness/agent/wire-agent-builder.js +26 -7
  30. package/dist/harness/capabilities/document/factory.d.ts +5 -0
  31. package/dist/harness/capabilities/document/factory.js +1 -0
  32. package/dist/harness/capabilities/document/port.js +6 -3
  33. package/dist/harness/capabilities/document/types.d.ts +5 -0
  34. package/dist/harness/collaboration/autonomous-subsystem/loader.js +1 -1
  35. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.d.ts +1 -1
  36. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +2 -2
  37. package/dist/harness/collaboration/autonomous-subsystem/sense/input-builder.js +4 -4
  38. package/dist/harness/collaboration/autonomous-subsystem/sense/metrics.d.ts +2 -2
  39. package/dist/harness/collaboration/autonomous-subsystem/sense/metrics.js +2 -2
  40. package/dist/harness/collaboration/autonomous-subsystem/signal/bus.d.ts +6 -0
  41. package/dist/harness/collaboration/autonomous-subsystem/signal/bus.js +25 -4
  42. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +1 -1
  43. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +3 -3
  44. package/dist/harness/collaboration/delegation/child-run.d.ts +1 -1
  45. package/dist/harness/collaboration/delegation/child-run.js +4 -4
  46. package/dist/harness/collaboration/delegation/index.d.ts +1 -1
  47. package/dist/harness/collaboration/delegation/index.js +1 -1
  48. package/dist/harness/collaboration/delegation/notifier.d.ts +6 -1
  49. package/dist/harness/collaboration/delegation/notifier.js +8 -1
  50. package/dist/harness/collaboration/delegation/service.d.ts +2 -0
  51. package/dist/harness/collaboration/delegation/service.js +2 -1
  52. package/dist/harness/collaboration/delegation/store.d.ts +2 -0
  53. package/dist/harness/collaboration/delegation/store.js +2 -1
  54. package/dist/harness/collaboration/delegation/types.d.ts +23 -2
  55. package/dist/harness/collaboration/delegation/types.js +22 -0
  56. package/dist/harness/collaboration/delegation/wiring.js +11 -1
  57. package/dist/harness/context/budget-allocator.d.ts +26 -18
  58. package/dist/harness/context/budget-allocator.js +67 -32
  59. package/dist/harness/context/capabilities/compact/engine.d.ts +0 -6
  60. package/dist/harness/context/capabilities/compact/engine.js +169 -121
  61. package/dist/harness/context/capabilities/compact/handover.d.ts +5 -3
  62. package/dist/harness/context/capabilities/compact/handover.js +7 -5
  63. package/dist/harness/context/capabilities/compact/index.d.ts +5 -1
  64. package/dist/harness/context/capabilities/compact/index.js +4 -0
  65. package/dist/harness/context/capabilities/compact/mechanical.d.ts +130 -0
  66. package/dist/harness/context/capabilities/compact/mechanical.js +268 -0
  67. package/dist/harness/context/capabilities/compact/messages.d.ts +60 -0
  68. package/dist/harness/context/capabilities/compact/messages.js +91 -0
  69. package/dist/harness/context/capabilities/compact/types.d.ts +76 -11
  70. package/dist/harness/context/capabilities/compact/types.js +11 -1
  71. package/dist/harness/context/capabilities/compact/view-split.d.ts +36 -0
  72. package/dist/harness/context/capabilities/compact/view-split.js +72 -0
  73. package/dist/harness/context/capabilities/summary/port.js +0 -1
  74. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  75. package/dist/harness/context/capabilities/summary/resolver.js +1 -6
  76. package/dist/harness/context/capabilities/summary/tool-binding.d.ts +1 -1
  77. package/dist/harness/context/capabilities/summary/types.d.ts +3 -6
  78. package/dist/harness/context/context-size-ledger.d.ts +143 -0
  79. package/dist/harness/context/context-size-ledger.js +236 -0
  80. package/dist/harness/context/default-context-engine.d.ts +195 -119
  81. package/dist/harness/context/default-context-engine.js +1241 -743
  82. package/dist/harness/context/index.d.ts +2 -2
  83. package/dist/harness/context/index.js +1 -1
  84. package/dist/harness/context/layer-types.d.ts +15 -0
  85. package/dist/harness/context/layer-types.js +14 -1
  86. package/dist/harness/context/layers.d.ts +14 -15
  87. package/dist/harness/context/layers.js +41 -11
  88. package/dist/harness/context/message-selector.d.ts +10 -8
  89. package/dist/harness/context/message-selector.js +49 -27
  90. package/dist/harness/context/summarize.d.ts +2 -2
  91. package/dist/harness/context/summarize.js +9 -2
  92. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  93. package/dist/harness/context/system-prompt-assembler.js +2 -1
  94. package/dist/harness/context/token-constants.d.ts +8 -6
  95. package/dist/harness/context/token-constants.js +8 -7
  96. package/dist/harness/context/token-estimate-fns.d.ts +37 -27
  97. package/dist/harness/context/token-estimate-fns.js +85 -66
  98. package/dist/harness/context/token-estimator.d.ts +27 -12
  99. package/dist/harness/context/token-estimator.js +120 -66
  100. package/dist/harness/context/token-segments.d.ts +88 -0
  101. package/dist/harness/context/token-segments.js +103 -0
  102. package/dist/harness/context/tool-result-aging.d.ts +6 -1
  103. package/dist/harness/context/tool-result-aging.js +16 -5
  104. package/dist/harness/context/tool-result-body.js +2 -0
  105. package/dist/harness/context/transform/anchors.d.ts +66 -0
  106. package/dist/harness/context/transform/anchors.js +125 -0
  107. package/dist/harness/context/transform/fold.d.ts +56 -0
  108. package/dist/harness/context/transform/fold.js +135 -0
  109. package/dist/harness/context/transform/migrate.d.ts +41 -0
  110. package/dist/harness/context/transform/migrate.js +69 -0
  111. package/dist/harness/context/transform/types.d.ts +129 -0
  112. package/dist/harness/context/transform/types.js +19 -0
  113. package/dist/harness/context/turn-envelope.d.ts +6 -3
  114. package/dist/harness/context/types.d.ts +127 -117
  115. package/dist/harness/extension/execution-environment/ops-audit.d.ts +1 -1
  116. package/dist/harness/extension/execution-environment/resource-limits.d.ts +1 -1
  117. package/dist/harness/extension/execution-environment/resource-limits.js +1 -1
  118. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +1 -1
  119. package/dist/harness/extension/plugin-ecosystem/commands/index.d.ts +3 -1
  120. package/dist/harness/extension/plugin-ecosystem/commands/index.js +1 -0
  121. package/dist/harness/extension/plugin-ecosystem/commands/plugin-bridge.d.ts +12 -1
  122. package/dist/harness/extension/plugin-ecosystem/commands/plugin-bridge.js +14 -4
  123. package/dist/harness/extension/plugin-ecosystem/commands/router.d.ts +5 -4
  124. package/dist/harness/extension/plugin-ecosystem/commands/router.js +23 -14
  125. package/dist/harness/extension/plugin-ecosystem/commands/types.d.ts +8 -1
  126. package/dist/harness/extension/plugin-ecosystem/commands/types.js +2 -1
  127. package/dist/harness/extension/plugin-ecosystem/hooks/adapter.d.ts +54 -0
  128. package/dist/harness/extension/plugin-ecosystem/hooks/adapter.js +397 -0
  129. package/dist/harness/extension/plugin-ecosystem/hooks/compaction-integration.d.ts +16 -0
  130. package/dist/harness/extension/plugin-ecosystem/hooks/compaction-integration.js +66 -0
  131. package/dist/harness/extension/plugin-ecosystem/hooks/index.d.ts +4 -0
  132. package/dist/harness/extension/plugin-ecosystem/hooks/index.js +2 -0
  133. package/dist/harness/extension/plugin-ecosystem/hooks/iteration-snapshot.d.ts +11 -0
  134. package/dist/harness/extension/plugin-ecosystem/hooks/iteration-snapshot.js +54 -0
  135. package/dist/harness/extension/plugin-ecosystem/hooks/journal.d.ts +9 -0
  136. package/dist/harness/extension/plugin-ecosystem/hooks/journal.js +22 -0
  137. package/dist/harness/extension/plugin-ecosystem/hooks/policy-error.d.ts +12 -0
  138. package/dist/harness/extension/plugin-ecosystem/hooks/policy-error.js +19 -0
  139. package/dist/harness/extension/plugin-ecosystem/hooks/run-integration.d.ts +36 -0
  140. package/dist/harness/extension/plugin-ecosystem/hooks/run-integration.js +338 -0
  141. package/dist/harness/extension/plugin-ecosystem/hooks/services.d.ts +24 -0
  142. package/dist/harness/extension/plugin-ecosystem/hooks/services.js +139 -0
  143. package/dist/harness/extension/plugin-ecosystem/hooks/types.d.ts +229 -0
  144. package/dist/harness/extension/plugin-ecosystem/hooks/types.js +1 -0
  145. package/dist/harness/extension/plugin-ecosystem/plugins/api.d.ts +83 -249
  146. package/dist/harness/extension/plugin-ecosystem/plugins/api.js +88 -214
  147. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.d.ts +43 -0
  148. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.js +61 -0
  149. package/dist/harness/extension/plugin-ecosystem/plugins/engine-compatibility.d.ts +4 -0
  150. package/dist/harness/extension/plugin-ecosystem/plugins/engine-compatibility.js +18 -0
  151. package/dist/harness/extension/plugin-ecosystem/plugins/entry.d.ts +7 -85
  152. package/dist/harness/extension/plugin-ecosystem/plugins/entry.js +8 -50
  153. package/dist/harness/extension/plugin-ecosystem/plugins/index.d.ts +6 -23
  154. package/dist/harness/extension/plugin-ecosystem/plugins/index.js +3 -23
  155. package/dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts +50 -117
  156. package/dist/harness/extension/plugin-ecosystem/plugins/loader.js +316 -285
  157. package/dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts +23 -490
  158. package/dist/harness/extension/plugin-ecosystem/plugins/manager.js +85 -353
  159. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts +41 -223
  160. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.js +138 -19
  161. package/dist/harness/extension/plugin-ecosystem/plugins/staging.d.ts +15 -0
  162. package/dist/harness/extension/plugin-ecosystem/plugins/staging.js +15 -0
  163. package/dist/harness/extension/plugin-ecosystem/skills/manager.d.ts +6 -1
  164. package/dist/harness/extension/plugin-ecosystem/skills/manager.js +17 -1
  165. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +3 -0
  166. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +46 -21
  167. package/dist/harness/extension/plugin-ecosystem/tools/delegation.js +18 -8
  168. package/dist/harness/extension/plugin-ecosystem/tools/plugin-tool.d.ts +11 -0
  169. package/dist/harness/extension/plugin-ecosystem/tools/plugin-tool.js +39 -0
  170. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.d.ts +1 -1
  171. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.js +11 -2
  172. package/dist/harness/governance/accounting/usage-ledger.d.ts +13 -1
  173. package/dist/harness/governance/accounting/usage-ledger.js +23 -1
  174. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +3 -3
  175. package/dist/harness/governance/human-in-the-loop/decision-cache.js +2 -2
  176. package/dist/harness/governance/security/capability-enforcer.js +1 -2
  177. package/dist/harness/index.d.ts +12 -12
  178. package/dist/harness/index.js +7 -7
  179. package/dist/harness/knowledge/boot-config.d.ts +55 -0
  180. package/dist/harness/knowledge/boot-config.js +50 -0
  181. package/dist/harness/knowledge/catalog-types.d.ts +2 -0
  182. package/dist/harness/knowledge/client.d.ts +24 -2
  183. package/dist/harness/knowledge/client.js +19 -5
  184. package/dist/harness/knowledge/db.js +5 -0
  185. package/dist/harness/knowledge/describe-sample.d.ts +23 -0
  186. package/dist/harness/knowledge/describe-sample.js +58 -0
  187. package/dist/harness/knowledge/describe.d.ts +8 -0
  188. package/dist/harness/knowledge/describe.js +18 -2
  189. package/dist/harness/knowledge/engine-thread.js +6 -0
  190. package/dist/harness/knowledge/grounding.js +3 -1
  191. package/dist/harness/knowledge/http-app.js +35 -4
  192. package/dist/harness/knowledge/http-params.d.ts +18 -0
  193. package/dist/harness/knowledge/http-params.js +24 -0
  194. package/dist/harness/knowledge/index.d.ts +2 -0
  195. package/dist/harness/knowledge/index.js +1 -0
  196. package/dist/harness/knowledge/knowledge-serve-child.js +3 -0
  197. package/dist/harness/knowledge/purge.js +5 -2
  198. package/dist/harness/knowledge/query-service.d.ts +13 -2
  199. package/dist/harness/knowledge/query-service.js +4 -2
  200. package/dist/harness/knowledge/query-worker-client.d.ts +9 -1
  201. package/dist/harness/knowledge/query-worker-client.js +4 -2
  202. package/dist/harness/knowledge/query-worker.js +4 -2
  203. package/dist/harness/knowledge/read-http.js +5 -1
  204. package/dist/harness/knowledge/serve.d.ts +8 -7
  205. package/dist/harness/knowledge/serve.js +9 -0
  206. package/dist/harness/knowledge/source-store.js +26 -3
  207. package/dist/harness/knowledge/start-service-process.d.ts +15 -7
  208. package/dist/harness/knowledge/start-service-process.js +21 -9
  209. package/dist/harness/knowledge/types.d.ts +7 -0
  210. package/dist/harness/knowledge/writer-service.d.ts +37 -9
  211. package/dist/harness/knowledge/writer-service.js +120 -14
  212. package/dist/harness/knowledge/writer-worker-client.d.ts +10 -9
  213. package/dist/harness/knowledge/writer-worker-client.js +20 -2
  214. package/dist/harness/knowledge/writer-worker.js +9 -1
  215. package/dist/harness/memory/sqlite/wisdom-store.js +35 -10
  216. package/dist/harness/memory/types.d.ts +6 -4
  217. package/dist/harness/memory/wisdom-formation.d.ts +14 -3
  218. package/dist/harness/memory/wisdom-formation.js +85 -22
  219. package/dist/harness/memory/wisdom-gates.d.ts +14 -0
  220. package/dist/harness/memory/wisdom-gates.js +59 -19
  221. package/dist/harness/memory/wisdom.js +9 -0
  222. package/dist/harness/observability/observer/hub.js +25 -15
  223. package/dist/harness/observability/observer/types.d.ts +10 -6
  224. package/dist/harness/run/agent/agent.d.ts +40 -21
  225. package/dist/harness/run/agent/agent.js +66 -13
  226. package/dist/harness/run/agent/index.d.ts +1 -1
  227. package/dist/harness/run/budget/budget.d.ts +28 -10
  228. package/dist/harness/run/budget/budget.js +38 -15
  229. package/dist/harness/run/model/index.d.ts +3 -1
  230. package/dist/harness/run/model/index.js +2 -1
  231. package/dist/harness/run/model/resolver.d.ts +4 -1
  232. package/dist/harness/run/model/resolver.js +36 -2
  233. package/dist/harness/run/model/run-scope.d.ts +2 -0
  234. package/dist/harness/run/model/run-scope.js +7 -0
  235. package/dist/harness/run/model/types.d.ts +22 -5
  236. package/dist/harness/run/model/types.js +3 -2
  237. package/dist/harness/run/model/window-truth.d.ts +37 -0
  238. package/dist/harness/run/model/window-truth.js +39 -0
  239. package/dist/harness/run/reliability/context-length-feedback.d.ts +77 -0
  240. package/dist/harness/run/reliability/context-length-feedback.js +128 -0
  241. package/dist/harness/run/reliability/harness-events.d.ts +3 -3
  242. package/dist/harness/run/reliability/model-error-policy.js +4 -0
  243. package/dist/harness/run/reliability/run-agent.d.ts +10 -4
  244. package/dist/harness/run/reliability/run-agent.js +137 -53
  245. package/dist/harness/run/reliability/run-metrics-collector.d.ts +19 -8
  246. package/dist/harness/run/reliability/run-metrics-collector.js +38 -23
  247. package/dist/harness/run/run-guard/default-run-guard.js +8 -8
  248. package/dist/harness/run/run-scope.d.ts +37 -4
  249. package/dist/harness/run/runner.d.ts +44 -29
  250. package/dist/harness/run/runner.js +320 -102
  251. package/dist/harness/session/attachments/index.d.ts +1 -0
  252. package/dist/harness/session/attachments/index.js +1 -0
  253. package/dist/harness/session/attachments/inject.d.ts +21 -10
  254. package/dist/harness/session/attachments/inject.js +76 -24
  255. package/dist/harness/session/attachments/recall-index.d.ts +70 -0
  256. package/dist/harness/session/attachments/recall-index.js +219 -0
  257. package/dist/harness/session/attachments/service.d.ts +21 -0
  258. package/dist/harness/session/attachments/service.js +258 -139
  259. package/dist/harness/session/attachments/types.d.ts +6 -0
  260. package/dist/harness/session/transform-store.d.ts +136 -0
  261. package/dist/harness/session/transform-store.js +302 -0
  262. package/dist/harness/session/types.d.ts +2 -2
  263. package/dist/harness/shared/events/agent-event-map.d.ts +46 -13
  264. package/dist/harness/shared/events/agent-event-map.js +3 -2
  265. package/dist/harness/shared/events/scenario-events.d.ts +6 -6
  266. package/dist/harness/shared/types/agent-definition.d.ts +1 -2
  267. package/dist/index.d.ts +14 -17
  268. package/dist/index.js +7 -9
  269. package/dist/integration/observability/metrics.d.ts +6 -6
  270. package/dist/integration/observability/metrics.js +13 -13
  271. package/dist/integration/observability/observer-bridge.js +2 -2
  272. package/dist/integration/observability/trace-collector.d.ts +5 -5
  273. package/dist/integration/observability/trace-collector.js +34 -35
  274. package/dist/integration/observability/trace-events.d.ts +3 -3
  275. package/dist/integration/observability/trace-events.js +3 -3
  276. package/dist/integration/providers/anthropic.js +14 -1
  277. package/dist/integration/providers/openai.js +7 -1
  278. package/dist/integration/providers/usage.d.ts +1 -1
  279. package/dist/integration/providers/wire-dump.d.ts +1 -1
  280. package/dist/integration/storage/archive-manager.d.ts +6 -0
  281. package/dist/integration/storage/archive-manager.js +10 -0
  282. package/dist/integration/storage/jsonl.d.ts +1 -1
  283. package/dist/integration/storage/jsonl.js +18 -16
  284. package/dist/subsystems/wisdom-steward/formation/SUBSYSTEM.md +8 -1
  285. package/dist/subsystems/wisdom-steward/formation/config.yaml +1 -0
  286. package/dist/subsystems/wisdom-steward/formation/handler.js +27 -5
  287. package/package.json +11 -14
  288. package/dist/harness/context/hybrid-compressor.d.ts +0 -41
  289. package/dist/harness/context/hybrid-compressor.js +0 -159
  290. package/dist/harness/context/llm-summarizer.d.ts +0 -46
  291. package/dist/harness/context/llm-summarizer.js +0 -249
  292. package/dist/harness/context/smart-router.d.ts +0 -75
  293. package/dist/harness/context/smart-router.js +0 -118
  294. package/dist/harness/context/truncate-compressor.d.ts +0 -28
  295. package/dist/harness/context/truncate-compressor.js +0 -107
  296. package/dist/harness/extension/plugin-ecosystem/plugins/capability.d.ts +0 -97
  297. package/dist/harness/extension/plugin-ecosystem/plugins/capability.js +0 -155
  298. package/dist/harness/extension/plugin-ecosystem/plugins/hooks.d.ts +0 -7
  299. package/dist/harness/extension/plugin-ecosystem/plugins/hooks.js +0 -7
  300. package/dist/harness/extension/plugin-ecosystem/plugins/lifecycle.d.ts +0 -86
  301. package/dist/harness/extension/plugin-ecosystem/plugins/lifecycle.js +0 -139
@@ -40,16 +40,29 @@ function failOutput(message, reason) {
40
40
  };
41
41
  }
42
42
  /**
43
- * 聚合炼制原料:promotion 候选 + 同型 method/norm 簇。
43
+ * 聚合炼制原料:promotion 候选 + 同型 method/norm 簇 + 库内已有范式清单。
44
44
  *
45
45
  * @param memoryStore - MemoryStore
46
+ * @param wisdomStore - WisdomStore(库内范式清单 + 已覆盖语料过滤)
46
47
  * @param minCluster - 触发阈值
47
- * @param maxChars - 证据包字符上限
48
+ * @param maxChars - 证据段字符上限
49
+ * @param maxDigestItems - 库内范式清单条数上限(独立预算)
48
50
  * @returns 证据包文本与 memoryIds
49
51
  */
50
- async function buildEvidencePack(memoryStore, minCluster, maxChars) {
52
+ async function buildEvidencePack(memoryStore, wisdomStore, minCluster, maxChars, maxDigestItems) {
51
53
  const all = await memoryStore.listForGovern({ includeDeleted: false });
52
- const alive = all.filter((e) => !e.deleted && (e.status ?? 'active') !== 'shadow');
54
+ const livingWisdom = (await wisdomStore.listForGovern()).filter((w) => w.status !== 'retired' && w.status !== 'superseded');
55
+ // 语料去覆盖:只统计 trial/active/strengthened 范式的 derivedFrom——
56
+ // candidate/contested 不锁语料(contested 可能被修反,同批证据要能炼出修正版)。
57
+ // 同源材料反复炼制是重复条目的燃料,已消化材料由下方「库内已有范式」清单代表
58
+ const covered = new Set();
59
+ for (const w of livingWisdom) {
60
+ if (w.status !== 'trial' && w.status !== 'active' && w.status !== 'strengthened')
61
+ continue;
62
+ for (const id of w.derivedFrom?.memoryIds ?? [])
63
+ covered.add(id);
64
+ }
65
+ const alive = all.filter((e) => !e.deleted && (e.status ?? 'active') !== 'shadow' && !covered.has(e.id));
53
66
  const promotions = planPromotionCandidates(alive, 20);
54
67
  // 按 type+首 tag 聚簇(代码侧选择;语义归 LLM)
55
68
  const clusters = new Map();
@@ -86,6 +99,14 @@ async function buildEvidencePack(memoryStore, minCluster, maxChars) {
86
99
  let text = parts.join('\n');
87
100
  if (text.length > maxChars)
88
101
  text = text.slice(0, maxChars);
102
+ // 库内已有范式清单:LLM 级语义去重的输入(同主题勿重复炼制;实质改进走 supersedesId 取代)。
103
+ // 受 maxDigestItems 单独约束(maxChars 只管证据段,两者共同构成有界提示);截断如实上报
104
+ if (livingWisdom.length) {
105
+ const shown = livingWisdom.slice(0, maxDigestItems);
106
+ const hidden = livingWisdom.length - shown.length;
107
+ const digestLines = shown.map((w) => `- (${w.id}) ${w.statement.slice(0, 80)}`).join('\n');
108
+ text += `\n## 库内已有范式(同主题勿重复炼制;确有实质改进则输出 supersedesId 取代,不要新增${hidden ? `;另有 ${hidden} 条未列出` : ''})\n${digestLines}`;
109
+ }
89
110
  return {
90
111
  text,
91
112
  memoryIds: [...ids],
@@ -103,10 +124,11 @@ async function handler(_input, deps) {
103
124
  const config = deps?.[DEP_CONFIG] ?? {};
104
125
  const minCluster = config.minClusterSize ?? 5;
105
126
  const maxChars = config.maxEvidenceChars ?? 6000;
127
+ const maxDigestItems = config.maxDigestItems ?? 30;
106
128
  const maxItems = config.maxItemsPerRun ?? 2;
107
129
  const dryRun = config.dryRun ?? false;
108
130
  const minPromotionStack = config.minPromotionStack ?? 3;
109
- const pack = await buildEvidencePack(memoryStore, minCluster, maxChars);
131
+ const pack = await buildEvidencePack(memoryStore, wisdomStore, minCluster, maxChars, maxDigestItems);
110
132
  // 触发器(防「见者有份」):真实簇 或 晋升候选堆叠;仅有零散材料不打 LLM
111
133
  const hasCluster = pack.clusterHits > 0;
112
134
  const hasStackedPromotions = pack.promotionCount >= minPromotionStack;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octopi-agent/engine",
3
- "version": "0.98.4",
3
+ "version": "0.102.10",
4
4
  "description": "Octopi Engine — Harness product domains, library integrations, and embeddable Agent.run()",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -35,17 +35,9 @@
35
35
  "types": "./dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts",
36
36
  "import": "./dist/harness/extension/plugin-ecosystem/plugins/manifest.js"
37
37
  },
38
- "./plugin-sdk/capability": {
39
- "types": "./dist/harness/extension/plugin-ecosystem/plugins/capability.d.ts",
40
- "import": "./dist/harness/extension/plugin-ecosystem/plugins/capability.js"
41
- },
42
- "./plugin-sdk/loader": {
43
- "types": "./dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts",
44
- "import": "./dist/harness/extension/plugin-ecosystem/plugins/loader.js"
45
- },
46
- "./plugin-sdk/manager": {
47
- "types": "./dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts",
48
- "import": "./dist/harness/extension/plugin-ecosystem/plugins/manager.js"
38
+ "./plugin-sdk": {
39
+ "types": "./dist/harness/extension/plugin-ecosystem/plugins/index.d.ts",
40
+ "import": "./dist/harness/extension/plugin-ecosystem/plugins/index.js"
49
41
  },
50
42
  "./package.json": "./package.json",
51
43
  "./harness/*": {
@@ -84,8 +76,10 @@
84
76
  },
85
77
  "dependencies": {
86
78
  "@modelcontextprotocol/sdk": "^1.29.0",
87
- "@octopi-agent/core": "0.98.4",
79
+ "@octopi-agent/core": "0.102.10",
80
+ "ajv": "^8.20.0",
88
81
  "js-yaml": "^4.3.2",
82
+ "semver": "^7.8.6",
89
83
  "undici": "^8.12.3",
90
84
  "web-tree-sitter": "^0.27.1",
91
85
  "zod": "^4.4.3"
@@ -117,5 +111,8 @@
117
111
  "llm",
118
112
  "octopi",
119
113
  "harness"
120
- ]
114
+ ],
115
+ "devDependencies": {
116
+ "@types/semver": "^7.8.0"
117
+ }
121
118
  }
@@ -1,41 +0,0 @@
1
- /**
2
- * HybridCompressor — 混合压缩器
3
- *
4
- * 三级压缩策略:
5
- * 1. 清除旧工具结果(>200 字符 → 占位符)- 无 LLM
6
- * 2. LLM 摘要(如果可用)
7
- * 3. 截断(兜底)
8
- *
9
- * 智能路由 + 四阶段压缩算法。
10
- */
11
- import type { Compressor, CompressParams, CompressResult } from './types.js';
12
- export declare class HybridCompressor implements Compressor {
13
- private llmCompressor;
14
- private truncateCompressor;
15
- constructor();
16
- /**
17
- * 压缩消息
18
- *
19
- * 策略:
20
- * 1. 机械预处理(截断旧工具结果)——只作用于**丢弃体/机械路径**,不进 LLM 摘要输入
21
- * 2. 如果有摘要函数,对**原文**做 LLM 摘要(F-b:禁止先打码再摘要)
22
- * 3. 否则使用截断
23
- */
24
- compress(params: CompressParams): Promise<CompressResult>;
25
- /**
26
- * 预处理工具结果
27
- *
28
- * 清除旧的、冗长的工具输出:
29
- * - 超过阈值的工具结果 → 占位符
30
- * - 保留最近的工具结果(不截断)
31
- */
32
- private preprocessToolResults;
33
- /**
34
- * 检查消息是否包含工具调用
35
- */
36
- private hasToolCall;
37
- /**
38
- * 检查消息是否是工具结果
39
- */
40
- private isToolResult;
41
- }
@@ -1,159 +0,0 @@
1
- /**
2
- * HybridCompressor — 混合压缩器
3
- *
4
- * 三级压缩策略:
5
- * 1. 清除旧工具结果(>200 字符 → 占位符)- 无 LLM
6
- * 2. LLM 摘要(如果可用)
7
- * 3. 截断(兜底)
8
- *
9
- * 智能路由 + 四阶段压缩算法。
10
- */
11
- import { HeuristicTokenEstimator } from './token-estimator.js';
12
- import { LLMSummaryCompressor } from './llm-summarizer.js';
13
- import { toolResultBody } from './tool-result-body.js';
14
- import { TruncateCompressor } from './truncate-compressor.js';
15
- /**
16
- * 工具结果截断阈值(字符数)
17
- */
18
- const TOOL_RESULT_TRUNCATE_THRESHOLD = 200;
19
- /**
20
- * 工具结果截断后的占位符(中性归档措辞——禁止诱导重跑)
21
- */
22
- const TOOL_RESULT_PLACEHOLDER = '[Tool output archived in session log — do NOT re-run unless the output is needed again.]';
23
- export class HybridCompressor {
24
- llmCompressor;
25
- truncateCompressor;
26
- constructor() {
27
- this.llmCompressor = new LLMSummaryCompressor();
28
- this.truncateCompressor = new TruncateCompressor();
29
- }
30
- /**
31
- * 压缩消息
32
- *
33
- * 策略:
34
- * 1. 机械预处理(截断旧工具结果)——只作用于**丢弃体/机械路径**,不进 LLM 摘要输入
35
- * 2. 如果有摘要函数,对**原文**做 LLM 摘要(F-b:禁止先打码再摘要)
36
- * 3. 否则使用截断
37
- */
38
- async compress(params) {
39
- const { messages, targetTokens, tokenEstimator } = params;
40
- const estimator = tokenEstimator ?? new HeuristicTokenEstimator();
41
- // 如果没有消息需要压缩
42
- if (messages.length === 0) {
43
- return {
44
- result: [],
45
- estimatedTokens: 0,
46
- fresh: false,
47
- summarizeAttempted: false,
48
- };
49
- }
50
- // 计算当前 token 数
51
- const currentTokens = estimator.estimateMessages(messages);
52
- // 如果已经在预算内,不需要压缩。
53
- // requireSummary 除外:主动摘要路径的主交付是语义摘要,达标也必须继续到摘要级。
54
- if (currentTokens <= targetTokens && !params.requireSummary) {
55
- return {
56
- result: [...messages],
57
- estimatedTokens: currentTokens,
58
- fresh: false,
59
- summarizeAttempted: false,
60
- };
61
- }
62
- // 机械预处理:仅给机械截断/残差用(F-b:不进摘要输入)
63
- const preprocessed = this.preprocessToolResults(messages);
64
- const preprocessedTokens = estimator.estimateMessages(preprocessed);
65
- // 如果预处理后已在预算内(requireSummary 时同样继续:机械截断不产出语义摘要)
66
- if (preprocessedTokens <= targetTokens && !params.requireSummary) {
67
- return {
68
- result: preprocessed,
69
- estimatedTokens: preprocessedTokens,
70
- droppedSummary: 'Old tool outputs truncated',
71
- fresh: false,
72
- summarizeAttempted: false,
73
- };
74
- }
75
- // 第二级:LLM 摘要 —— 输入为原文(F-b)
76
- if (params.summarize) {
77
- try {
78
- const result = await this.llmCompressor.compress({
79
- ...params,
80
- messages,
81
- });
82
- return result;
83
- }
84
- catch (err) {
85
- // LLM 摘要失败,继续到截断
86
- console.warn('LLM summarization failed, falling back to truncation:', err);
87
- }
88
- }
89
- // 第三级:截断(兜底)——机械预处理后的丢弃体
90
- return this.truncateCompressor.compress({
91
- ...params,
92
- messages: preprocessed,
93
- });
94
- }
95
- /**
96
- * 预处理工具结果
97
- *
98
- * 清除旧的、冗长的工具输出:
99
- * - 超过阈值的工具结果 → 占位符
100
- * - 保留最近的工具结果(不截断)
101
- */
102
- preprocessToolResults(messages) {
103
- const result = [];
104
- let lastToolCallIndex = -1;
105
- // 找到最后一个 tool_call 的位置
106
- for (let i = messages.length - 1; i >= 0; i--) {
107
- if (this.hasToolCall(messages[i])) {
108
- lastToolCallIndex = i;
109
- break;
110
- }
111
- }
112
- for (let i = 0; i < messages.length; i++) {
113
- const msg = messages[i];
114
- // 工具结果消息
115
- if (this.isToolResult(msg) && msg.toolResults) {
116
- // 最近的工具结果不截断
117
- const isRecent = i > lastToolCallIndex;
118
- if (isRecent) {
119
- result.push(msg);
120
- continue;
121
- }
122
- // 旧的工具结果:截断冗长的输出
123
- const truncatedResults = msg.toolResults.map(tr => {
124
- const body = toolResultBody(tr);
125
- if (body.length > TOOL_RESULT_TRUNCATE_THRESHOLD) {
126
- // error 永不打码(错误可追溯性优先,与 B2 同红线);只截断成功结果
127
- if (tr.error !== undefined) {
128
- return tr;
129
- }
130
- return {
131
- ...tr,
132
- result: TOOL_RESULT_PLACEHOLDER,
133
- };
134
- }
135
- return tr;
136
- });
137
- result.push({
138
- ...msg,
139
- toolResults: truncatedResults,
140
- });
141
- continue;
142
- }
143
- result.push(msg);
144
- }
145
- return result;
146
- }
147
- /**
148
- * 检查消息是否包含工具调用
149
- */
150
- hasToolCall(msg) {
151
- return msg.role === 'assistant' && msg.toolCalls !== undefined && msg.toolCalls.length > 0;
152
- }
153
- /**
154
- * 检查消息是否是工具结果
155
- */
156
- isToolResult(msg) {
157
- return msg.role === 'tool' || (msg.toolResults !== undefined && msg.toolResults.length > 0);
158
- }
159
- }
@@ -1,46 +0,0 @@
1
- /**
2
- * LLMSummaryCompressor — LLM 摘要压缩器
3
- *
4
- * 使用 LLM 生成结构化摘要,保留关键信息。
5
- * 支持迭代式更新:传入上次摘要,LLM 更新而非重建。
6
- *
7
- * 摘要策略:
8
- * 1. 将消息格式化为上下文
9
- * 2. 调用 LLM 生成结构化摘要
10
- * 3. 摘要预算(P1c/F8):clamp(2%, 2k, 8k) 软目标写指令 + 4× 保险丝硬顶——与 compact 引擎同语义
11
- */
12
- import type { Message } from '@octopi-agent/core/types.js';
13
- import type { Compressor, CompressParams, CompressResult } from './types.js';
14
- /**
15
- * 工具调用账本(name+args 紧凑清单)——降级时的「做过什么」无损索引
16
- *
17
- * @param messages - 被降级丢弃的消息
18
- * @returns 账本文本(可为空串)
19
- */
20
- export declare function buildToolCallLedger(messages: Message[]): string;
21
- /** 模板/指令/合并语义已单源化到 capabilities/compact/handover.ts(F8 模板统一:四段式交接书)。 */
22
- export declare class LLMSummaryCompressor implements Compressor {
23
- /**
24
- * 压缩消息
25
- *
26
- * 策略:
27
- * 1. 将消息格式化为 LLM 可读的上下文
28
- * 2. 调用 LLM 生成摘要
29
- * 3. 返回摘要作为压缩结果
30
- */
31
- compress(params: CompressParams): Promise<CompressResult>;
32
- /**
33
- * 格式化消息为 LLM 可读的上下文
34
- *
35
- * 归因保留(模型 2):多 agent 共线的摘要不得张冠李戴
36
- * (惯例出处 session/history/port.ts renderMessage 的 role(agentId);此处大写仅排版差异)。
37
- */
38
- private formatMessagesForSummary;
39
- /**
40
- * 回退截断(当 LLM 摘要不可用时)——保守降级
41
- *
42
- * 作为 **middle 替换体**:账本说明 + 近尾若干条。
43
- * 外层 head/tail 由调用方(applyProactiveCompact)拼接,此处不得重复携带。
44
- */
45
- private fallbackTruncate;
46
- }
@@ -1,249 +0,0 @@
1
- /**
2
- * LLMSummaryCompressor — LLM 摘要压缩器
3
- *
4
- * 使用 LLM 生成结构化摘要,保留关键信息。
5
- * 支持迭代式更新:传入上次摘要,LLM 更新而非重建。
6
- *
7
- * 摘要策略:
8
- * 1. 将消息格式化为上下文
9
- * 2. 调用 LLM 生成结构化摘要
10
- * 3. 摘要预算(P1c/F8):clamp(2%, 2k, 8k) 软目标写指令 + 4× 保险丝硬顶——与 compact 引擎同语义
11
- */
12
- import { getTextContent } from '@octopi-agent/core/types.js';
13
- import { buildHandoverPrompt, buildHandoverUserContent, clampSummaryProviderCap, detectSummaryContamination, summarySoftTargetTokens, } from './capabilities/compact/index.js';
14
- import { estimateLLMMessages } from './token-estimator.js';
15
- import { HeuristicTokenEstimator } from './token-estimator.js';
16
- import { toolResultBody } from './tool-result-body.js';
17
- /**
18
- * 工具调用账本(name+args 紧凑清单)——降级时的「做过什么」无损索引
19
- *
20
- * @param messages - 被降级丢弃的消息
21
- * @returns 账本文本(可为空串)
22
- */
23
- export function buildToolCallLedger(messages) {
24
- const lines = [];
25
- for (const msg of messages) {
26
- for (const tc of msg.toolCalls ?? []) {
27
- let args;
28
- try {
29
- args = JSON.stringify(tc.arguments ?? {});
30
- }
31
- catch {
32
- args = '[unserializable]';
33
- }
34
- if (args.length > 160)
35
- args = `${args.slice(0, 160)}…`;
36
- lines.push(`- ${tc.name}(${args})`);
37
- }
38
- for (const tr of msg.toolResults ?? []) {
39
- if (tr.error !== undefined) {
40
- const err = tr.error.length > 120 ? `${tr.error.slice(0, 120)}…` : tr.error;
41
- lines.push(` ! ${tr.name ?? tr.toolCallId}: ${err}`);
42
- }
43
- }
44
- }
45
- return lines.join('\n');
46
- }
47
- /** 模板/指令/合并语义已单源化到 capabilities/compact/handover.ts(F8 模板统一:四段式交接书)。 */
48
- export class LLMSummaryCompressor {
49
- /**
50
- * 压缩消息
51
- *
52
- * 策略:
53
- * 1. 将消息格式化为 LLM 可读的上下文
54
- * 2. 调用 LLM 生成摘要
55
- * 3. 返回摘要作为压缩结果
56
- */
57
- async compress(params) {
58
- const { messages, targetTokens, previousSummary, summarize, tokenEstimator } = params;
59
- const estimator = tokenEstimator ?? new HeuristicTokenEstimator();
60
- // 如果没有摘要函数,返回截断结果
61
- if (!summarize) {
62
- return this.fallbackTruncate(messages, targetTokens, estimator, false);
63
- }
64
- // 如果没有消息需要压缩
65
- if (messages.length === 0) {
66
- return {
67
- result: [],
68
- estimatedTokens: 0,
69
- fresh: false,
70
- summarizeAttempted: false,
71
- };
72
- }
73
- // 计算当前 token 数
74
- const currentTokens = estimator.estimateMessages(messages);
75
- // 如果已经在预算内,不需要压缩。
76
- // requireSummary 除外:调用方要求语义摘要,不能以机械返回冒充已摘要。
77
- if (currentTokens <= targetTokens && !params.requireSummary) {
78
- return {
79
- result: [...messages],
80
- estimatedTokens: currentTokens,
81
- fresh: false,
82
- summarizeAttempted: false,
83
- };
84
- }
85
- // F8 单一预算语义:P1c clamp(2%, 2k, 8k) 软目标写指令;provider 硬顶 = 4× 保险丝 + 窗口钳制
86
- const softTarget = summarySoftTargetTokens(currentTokens, params.summaryBudget);
87
- const prompt = buildHandoverPrompt({
88
- maxTokens: softTarget,
89
- previousSummary,
90
- foldRange: params.foldRange,
91
- taskSnapshot: params.taskSnapshot,
92
- });
93
- // 格式化消息为 LLM 可读的上下文(仅无 llmPrefix 时的旁路)
94
- const formattedContext = this.formatMessagesForSummary(messages);
95
- // 构建 LLM 消息
96
- // 缓存优先:llmPrefix(会话 system+history 同形)+ 尾部 user 指令。
97
- // 禁止改写 system / 重排历史——否则打穿 provider 前缀缓存。
98
- const buildPrefixed = () => [
99
- ...params.llmPrefix,
100
- { role: 'user', content: prompt.tailUser },
101
- ];
102
- const buildTextify = () => [
103
- { role: 'system', content: prompt.instruction },
104
- { role: 'user', content: buildHandoverUserContent(params, formattedContext) },
105
- ];
106
- let usePrefix = Boolean(params.llmPrefix?.length);
107
- let llmMessages = usePrefix ? buildPrefixed() : buildTextify();
108
- // 回声比对源 = 模型实际可见文本投影(评审 F8):前缀模式只比前缀内容——formattedContext 是
109
- // 文本化重渲染,模型并未看见,算进比对源只增误伤面;与 compact 引擎同判据
110
- let echoSource = usePrefix
111
- ? (params.llmPrefix ?? []).map((m) => String(m.content ?? '')).join('\n')
112
- : formattedContext;
113
- const hardCap = softTarget * 4;
114
- const capOf = (msgs) => clampSummaryProviderCap({
115
- hardCap,
116
- // estimateLLMMessages 口径含 tool_calls/content block/消息开销——摘要恰在工具密集
117
- // 会话触发,String(content) 口径会把 tool_calls 全漏掉、多模态块变 [object Object]
118
- inputTokens: estimateLLMMessages(msgs),
119
- contextWindow: params.contextWindow,
120
- maxOutputTokens: params.maxOutputTokens,
121
- });
122
- let providerMaxTokens = capOf(llmMessages);
123
- // F22 可观测:无前缀/被迫旁路 = cache-miss,如实上报,不静默换请求形状
124
- if (!usePrefix) {
125
- params.emit?.({ type: 'compact.summarize_fallback', reason: 'no_prefix', cached: false });
126
- }
127
- if (providerMaxTokens < 256 && usePrefix) {
128
- usePrefix = false;
129
- llmMessages = buildTextify();
130
- echoSource = formattedContext;
131
- providerMaxTokens = capOf(llmMessages);
132
- params.emit?.({ type: 'compact.summarize_fallback', reason: 'window_guard', cached: false });
133
- }
134
- if (providerMaxTokens < 256) {
135
- // F12 可观测:窗口穷尽是最终失败,事件如实上报(不止于换旁路时)
136
- params.emit?.({ type: 'compact.summarize_fallback', reason: 'window_exhausted', cached: false });
137
- return this.fallbackTruncate(messages, targetTokens, estimator, false);
138
- }
139
- try {
140
- // 调用 LLM 生成摘要
141
- const summary = await summarize(llmMessages, {
142
- previousSummary,
143
- maxTokens: providerMaxTokens,
144
- });
145
- // 空摘要(拒答/内容过滤)按失败处理:不得用空正文替换中间段、更不得冒充语义摘要
146
- if (!summary || !summary.trim()) {
147
- return this.fallbackTruncate(messages, targetTokens, estimator);
148
- }
149
- // 输出闸门(评审 F8):proactive/overflow 与手动路径同一污染判据——续写污染
150
- //(对话体/工具调用形状、成段回声)按失败处理,走截断降级(诚实降级,不落坏摘要)。
151
- if (detectSummaryContamination(summary, echoSource)) {
152
- return this.fallbackTruncate(messages, targetTokens, estimator);
153
- }
154
- // 摘要用 user 角色:中段 system 会被部分网关拒绝
155
- const summaryMessage = {
156
- role: 'user',
157
- content: `[Conversation Summary]\n\n${summary}`,
158
- timestamp: Date.now(),
159
- metadata: { source: 'contextSummary' },
160
- };
161
- // 估算摘要 token 数
162
- const summaryMessageTokens = estimator.estimateMessage(summaryMessage);
163
- return {
164
- result: [summaryMessage],
165
- estimatedTokens: summaryMessageTokens,
166
- droppedSummary: `Conversation compressed from ${currentTokens} to ~${summaryMessageTokens} tokens`,
167
- fresh: true,
168
- summarizeAttempted: true,
169
- };
170
- }
171
- catch (err) {
172
- // LLM 摘要失败,回退到截断
173
- console.warn('LLM summarization failed, falling back to truncation:', err);
174
- return this.fallbackTruncate(messages, targetTokens, estimator);
175
- }
176
- }
177
- /**
178
- * 格式化消息为 LLM 可读的上下文
179
- *
180
- * 归因保留(模型 2):多 agent 共线的摘要不得张冠李戴
181
- * (惯例出处 session/history/port.ts renderMessage 的 role(agentId);此处大写仅排版差异)。
182
- */
183
- formatMessagesForSummary(messages) {
184
- const parts = [];
185
- for (const msg of messages) {
186
- const role = msg.agentId ? `${msg.role.toUpperCase()}(${msg.agentId})` : msg.role.toUpperCase();
187
- const content = getTextContent(msg.content ?? '');
188
- if (msg.role === 'assistant' && msg.toolCalls?.length) {
189
- // 带工具调用的 assistant 消息
190
- const toolCallsStr = msg.toolCalls
191
- .map(tc => ` - ${tc.name}(${JSON.stringify(tc.arguments)})`)
192
- .join('\n');
193
- parts.push(`[${role}]\n${content}\nTool Calls:\n${toolCallsStr}`);
194
- }
195
- else if (msg.role === 'tool' && msg.toolResults?.length) {
196
- // 工具结果消息(含 error,避免摘要丢失失败信息)
197
- const resultsStr = msg.toolResults
198
- .map(tr => ` - ${tr.name}: ${toolResultBody(tr)}`)
199
- .join('\n');
200
- parts.push(`[${role}]\nTool Results:\n${resultsStr}`);
201
- }
202
- else if (content) {
203
- parts.push(`[${role}]\n${content}`);
204
- }
205
- }
206
- return parts.join('\n\n---\n\n');
207
- }
208
- /**
209
- * 回退截断(当 LLM 摘要不可用时)——保守降级
210
- *
211
- * 作为 **middle 替换体**:账本说明 + 近尾若干条。
212
- * 外层 head/tail 由调用方(applyProactiveCompact)拼接,此处不得重复携带。
213
- */
214
- fallbackTruncate(messages, _targetTokens, estimator, summarizeAttempted = true) {
215
- // 近尾保留工具步上下文;更早的换成「账本」——禁止只留 4 条且无索引
216
- const keepCount = Math.min(Math.max(6, Math.ceil(messages.length * 0.15)), messages.length);
217
- const kept = messages.slice(-keepCount);
218
- const dropped = messages.slice(0, messages.length - keepCount);
219
- // 无可丢弃:原样返回(禁止用「0 removed」假通知撑长视图)
220
- if (dropped.length === 0) {
221
- return {
222
- result: [...messages],
223
- estimatedTokens: estimator.estimateMessages(messages),
224
- fresh: false,
225
- summarizeAttempted,
226
- };
227
- }
228
- const ledger = buildToolCallLedger(dropped);
229
- const notice = ledger
230
- ? `[Context truncated: ${dropped.length} earlier messages removed to fit context window]\n[Tool call ledger — do NOT redo these unless explicitly asked]\n${ledger}\n[Check session task list via task_* before continuing]`
231
- : `[Context truncated: ${dropped.length} earlier messages removed to fit context window]\n[Check session task list via task_* before continuing]`;
232
- // 插入截断说明(user 角色,避免中段 system)
233
- const summaryMessage = {
234
- role: 'user',
235
- content: notice,
236
- timestamp: Date.now(),
237
- metadata: { source: 'contextSummary' },
238
- };
239
- const result = [summaryMessage, ...kept];
240
- const estimatedTokens = estimator.estimateMessages(result);
241
- return {
242
- result,
243
- estimatedTokens,
244
- droppedSummary: `${dropped.length} messages truncated`,
245
- fresh: false,
246
- summarizeAttempted,
247
- };
248
- }
249
- }