dsh-memu-memory 1.4.2 → 1.4.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 (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +169 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +79 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1015 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1586 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +124 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,979 +1,1015 @@
1
- // T1 构件 2(设计文档 §4/§5/§15.1 构件 2):持久整理 worker 的生命周期管理。
2
- //
3
- // 定位:worker 与 turn-log 一样是缓存,账本才算数(§0 铁律 1)。本模块只负责
4
- // 「谁来写」与「喂什么」:三级试活(agents.get → agents.resume 能力探测 → 初生,
5
- // §4.6)、epoch 记账与退役条件(只在 acquire 时检查,§4.5)、增量包/交接包组装
6
- // (§4.2/§5.1)、超时计数与退役(§4.4)。每窗结算仍走 private.js 现有的
7
- // decideCompletion/completeJob/lastSleepSeq/carry 链路,一行语义不改。
8
- //
9
- // 默认 consolidationRunner: 'fork'——本模块的全部路径只在设置显式切到 'worker'
10
- // 时被 private.js 调用;'fork'(现状每窗新 fork)行为逐字节不变。
11
- import { getSessionBinding, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex } from './state.js'
12
- import fs from 'node:fs'
13
- import { warn, shortHash, dataDir } from './paths.js'
14
- import { estTokens } from './budget.js'
15
- import { record } from './activity-log.js'
16
- import { loadLedger, scopeGenerationOf } from './consolidation-ledger.js'
17
- import { buildWorkerBrief, CORE_WRITE_TOOLS, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW } from './consolidation-worker.js'
18
- import { registerTools } from './tools.js'
19
- import { tailSlice, readIncrement, rebuildRange, buildTurnRecords, turnLogLimits } from './turn-log.js'
20
- import { condenseEvents, condenseLimitsFor } from './curator.js'
21
-
22
- // —— epoch 预算分档(§4.5 条件 2/3)————————————————————————————————
23
- // 按模型 maxContext 自动取档:≤128k 输入窗 → 120k 字符/8 窗;其余(含 ≥1M 旗舰)→ 200k/16。
24
- // 大上下文模型不再放到 400k/32:P14 实测 32 窗会把 worker 上下文堆到 174k token,
25
- // 而 96.9% 的整理 token 是历史重读;压到 200k 字符/16 窗可省约七成整理 token
26
- // (§9.0:每窗含思考约 13-21k)。模型 maxContext 尽力从宿主模型发现取
27
- // (probeModelMaxContext);取不到按最保守的第一档。显式设置
28
- // (workerEpochCharLimit / workerEpochMaxWindows(正整数,未来经 DEFAULT_SETTINGS
29
- // 放开)覆盖自动档;本阶段这两个键不在设置面里,属于前向兼容钩子。
30
- export const WORKER_EPOCH_TIERS = Object.freeze([
31
- Object.freeze({ maxContext: 131_072, charLimit: 120_000, maxWindows: 8 }),
32
- Object.freeze({ maxContext: 262_144, charLimit: 200_000, maxWindows: 16 }),
33
- Object.freeze({ maxContext: Number.MAX_SAFE_INTEGER, charLimit: 200_000, maxWindows: 16 }),
34
- ])
35
- // 产出系数(§4.5 条件 2):触发时「epoch 已累计 + 本窗增量 × 3 ≤ LIMIT」的粗估,
36
- // 3 倍覆盖 worker 产出与思考;窗口跑完后按实际观测替换估算(recordEpochProgress)。
37
- export const WORKER_OUTPUT_FACTOR = 3
38
- // 条件 4(§4.5):距上一窗 whenIdle 完成超过缓存 TTL 即换新。只在 acquire 时检查,
39
- // 不做后台定时退役;TTL 是保守方向的启发式——早换新永不吃亏。
40
- export const WORKER_EPOCH_IDLE_TTL_MS = 30 * 60_000
41
- // 交接包尾部预算(§5.2):min(20k, 连续回合),tailSlice 保证整回合。
42
- export const WORKER_HANDOFF_TAIL_CHARS = 20_000
43
- // §4.4:超时不算失败;同一 worker 连续 2 次超时升级为退役。
44
- export const WORKER_TIMEOUT_LIMIT = 2
45
- // 退役时等 whenIdle 的上限:卡死的 worker 不能挂住下一次整理。
46
- export const WORKER_RETIRE_IDLE_WAIT_MS = 5_000
47
- // §3.3 回退路径的现场压缩预算(与 requestRemoteConsolidation 同款)。
48
- export const WORKER_INCREMENT_FALLBACK_CHARS = 60_000
49
-
50
- /** 按模型 maxContext 取档;未知模型回最保守的第一档;显式设置覆盖自动档。 */
51
- export function epochBudget(binding, settings = null) {
52
- const explicitChars = Number(settings?.workerEpochCharLimit)
53
- const explicitWindows = Number(settings?.workerEpochMaxWindows)
54
- const maxContext = Number(binding?.workerEpoch?.modelMaxContext)
55
- const tier = WORKER_EPOCH_TIERS.find((row) => Number.isSafeInteger(maxContext) && maxContext > 0 && maxContext <= row.maxContext) || WORKER_EPOCH_TIERS[0]
56
- return {
57
- charLimit: Number.isSafeInteger(explicitChars) && explicitChars > 0 ? explicitChars : tier.charLimit,
58
- maxWindows: Number.isSafeInteger(explicitWindows) && explicitWindows > 0 ? explicitWindows : tier.maxWindows,
59
- }
60
- }
61
-
62
- /**
63
- * 预算合格制(§4.5 条件 2):epoch 已累计 + 本窗增量 × 产出系数 ≤ 字符上限。
64
- * 触发时检查,粗估、宁可早换新;不做事件级精确记账(宿主 compaction 是溢出安全网)。
65
- */
66
- export function budgetFit(epoch, incrementChars, settings = null) {
67
- const chars = Number(epoch?.chars) || 0
68
- const increment = Math.max(0, Number(incrementChars) || 0)
69
- return chars + increment * WORKER_OUTPUT_FACTOR <= epochBudget({ workerEpoch: epoch }, settings).charLimit
70
- }
71
-
72
- /** Never repair a user's path or change host permissions; only select a usable cwd. */
73
- export function resolveConsolidationCwd(headerCwd, fallback = dataDir()) {
74
- try {
75
- if (typeof headerCwd === 'string' && headerCwd && fs.statSync(headerCwd).isDirectory()) return headerCwd
76
- } catch { /* Deleted/inaccessible cwd: use the plugin data directory. */ }
77
- return fallback
78
- }
79
-
80
- export function measurePacket(text, kind = 'increment') {
81
- const value = String(text ?? '')
82
- return { kind, inputChars: value.length, estimatedTokens: estTokens(value) }
83
- }
84
-
85
- export function packetBudgetFit(epoch, packet, settings = null) {
86
- return budgetFit(epoch, packet?.inputChars, settings)
87
- }
88
-
89
- const USAGE_FIELDS = ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'outputTokens', 'reasoningTokens']
90
-
91
- /** Per-window counters only. Event/call identities stay in closure, never bodies. */
92
- export function createConsolidationMeasurement(runner, { sessionId = '', afterSeq = null } = {}) {
93
- const measurement = {
94
- schemaVersion: 2, measurementVersion: 2, runner,
95
- packet: null,
96
- dispatched: { inputChars: 0, estimatedTokens: 0, followups: 0, wrapupChars: 0 },
97
- observed: { outputTextChars: 0, toolArgumentsChars: 0, toolResultsChars: 0, reasoningChars: null, estimatedTokens: 0 },
98
- usage: { ...Object.fromEntries(USAGE_FIELDS.map(key => [key, null])), source: 'unavailable', requests: 0 },
99
- serializationErrors: 0,
100
- toolEvents: 0, logicalToolCalls: 0,
101
- lastEventSeq: Number.isSafeInteger(afterSeq) ? afterSeq : null,
102
- }
103
- const events = new Set()
104
- const calls = new Set()
105
- const requests = new Map()
106
- const objects = new WeakSet()
107
- let anonymousEvent = 0
108
- const serialized = (value) => {
109
- if (typeof value === 'string') return value
110
- if (value == null) return ''
111
- try { return JSON.stringify(value) ?? '' } catch {
112
- measurement.serializationErrors += 1
113
- warn('consolidation measurement: tool payload could not be serialized; size is unknown')
114
- return null
115
- }
116
- }
117
- const add = (key, text, retained = true) => {
118
- if (text === null) {
119
- measurement.observed[key] = null
120
- if (retained) measurement.observed.estimatedTokens = null
121
- return
122
- }
123
- if (measurement.observed[key] !== null || key === 'reasoningChars') {
124
- // reasoning is unknown until a real reasoning block is observed.
125
- measurement.observed[key] = (measurement.observed[key] ?? 0) + text.length
126
- }
127
- if (retained && measurement.observed.estimatedTokens !== null) measurement.observed.estimatedTokens += estTokens(text)
128
- }
129
- const tool = (phase, id, payload, fallback) => {
130
- const callId = typeof id === 'string' || Number.isSafeInteger(id) ? id : fallback
131
- const key = JSON.stringify([phase, callId])
132
- if (calls.has(key)) return
133
- if (payload === undefined) return
134
- calls.add(key)
135
- if (phase === 'arguments') measurement.logicalToolCalls += 1
136
- add(phase === 'arguments' ? 'toolArgumentsChars' : 'toolResultsChars', serialized(payload))
137
- }
138
- const observe = (event) => {
139
- if (!event || typeof event !== 'object') return false
140
- const seq = event.seq
141
- const eventId = typeof event.id === 'string' || Number.isSafeInteger(event.id) ? event.id : null
142
- const key = Number.isSafeInteger(seq) ? JSON.stringify([sessionId, seq]) : (eventId !== null ? JSON.stringify([sessionId, eventId]) : null)
143
- if (Number.isSafeInteger(seq) && Number.isSafeInteger(afterSeq) && seq <= afterSeq) return false
144
- if (key ? events.has(key) : objects.has(event)) return false
145
- if (key) events.add(key)
146
- else objects.add(event)
147
- if (Number.isSafeInteger(seq)) measurement.lastEventSeq = Math.max(measurement.lastEventSeq ?? -1, seq)
148
- const fallback = key || 'anonymous-' + (++anonymousEvent)
149
- const data = event.data || {}
150
- if (['tool/call', 'tool/result', 'tool/ptc-dispatch-start', 'tool/ptc-dispatch'].includes(event.type)) measurement.toolEvents += 1
151
- if (event.type === 'assistant/message') {
152
- for (const [index, block] of (Array.isArray(data.message?.content) ? data.message.content : []).entries()) {
153
- if (block?.type === 'text' && typeof block.text === 'string') add('outputTextChars', block.text)
154
- if (block?.type === 'reasoning' && typeof block.text === 'string') add('reasoningChars', block.text, false)
155
- if (block?.type === 'tool-call') tool('arguments', block.id, block.arguments, fallback + ':' + index)
156
- }
157
- // Verified public assistant/message.data.usage only: input is non-cached;
158
- // output includes reasoning when supplied. Never sum reasoning into output.
159
- const requestId = typeof data.requestId === 'string' || Number.isSafeInteger(data.requestId) ? data.requestId : null
160
- const requestKey = requestId !== null ? JSON.stringify([sessionId, requestId]) : key || fallback
161
- const previous = requests.get(requestKey) || {}
162
- let known = false
163
- for (const field of USAGE_FIELDS) {
164
- const value = data.usage?.[field]
165
- if (!Number.isSafeInteger(value) || value < 0 || previous[field] !== undefined) continue
166
- previous[field] = value
167
- known = true
168
- }
169
- requests.set(requestKey, previous)
170
- for (const field of USAGE_FIELDS) {
171
- const rows = [...requests.values()]
172
- measurement.usage[field] = rows.every(row => row[field] !== undefined)
173
- ? rows.reduce((sum, row) => sum + row[field], 0) : null
174
- }
175
- measurement.usage.requests = requests.size
176
- if (known) measurement.usage.source = 'assistant/message.data.usage'
177
- }
178
- if (event.type === 'tool/call' || event.type === 'tool/ptc-dispatch-start') {
179
- tool('arguments', data.subCallId ?? data.callId, data.arguments, fallback)
180
- }
181
- if (event.type === 'tool/ptc-dispatch') {
182
- if (data.arguments !== undefined) tool('arguments', data.subCallId ?? data.callId, data.arguments, fallback)
183
- tool('results', data.subCallId ?? data.callId, data.content ?? event.content ?? data.message?.content, fallback)
184
- }
185
- if (event.type === 'tool/result') {
186
- tool('results', data.message?.callId ?? data.callId, data.message?.content ?? data.content ?? event.content, fallback)
187
- }
188
- return true
189
- }
190
- const dispatch = (text, kind) => {
191
- const packet = measurePacket(text, kind)
192
- if (!measurement.packet) measurement.packet = packet
193
- measurement.dispatched.inputChars += packet.inputChars
194
- measurement.dispatched.estimatedTokens += packet.estimatedTokens
195
- measurement.dispatched.followups += 1
196
- if (kind === 'wrapup') measurement.dispatched.wrapupChars += packet.inputChars
197
- return packet
198
- }
199
- return { measurement, observe, dispatch }
200
- }
201
-
202
- /** 宿主模型发现的 maxContext 尽力获取;拿不到返回 null(epochBudget 落第一档)。 */
203
- export async function probeModelMaxContext(ctx, agentOptions) {
204
- const provider = typeof agentOptions?.provider === 'string' ? agentOptions.provider : ''
205
- const model = typeof agentOptions?.model === 'string' ? agentOptions.model : ''
206
- if (!provider || !model) return null
207
- const llm = (() => { try { return ctx?.get?.('llm') || null } catch { return null } })()
208
- if (!llm) return null
209
- // 首选 resolveModelInfo:宿主唯一的容量口径在 resolved.context.contextWindow。
210
- // listModels 的目录条目(LlmModelInfo)不带容量字段,读它永远落空(A4)。
211
- try {
212
- const resolved = await llm.resolveModelInfo?.(provider, model)
213
- const contextWindow = Number(resolved?.context?.contextWindow)
214
- if (Number.isSafeInteger(contextWindow) && contextWindow > 0) return contextWindow
215
- } catch { /* 探测失败降级,绝不阻断整理 */ }
216
- // 兜底:个别宿主/测试可能把容量直接挂在目录条目上。
217
- try {
218
- const models = await llm.listModels?.(provider)
219
- if (Array.isArray(models)) {
220
- const entry = models.find((item) => item && (item.id === model || item.name === model)) || null
221
- for (const key of ['maxContext', 'contextLength', 'contextWindow', 'maxInputTokens', 'maxContextTokens']) {
222
- const value = Number(entry?.[key])
223
- if (Number.isSafeInteger(value) && value > 0) return value
224
- }
225
- }
226
- } catch { /* 同上 */ }
227
- return null
228
- }
229
-
230
- // —— 工具面(自 private.js 迁入;'fork' 路径调用同一份实现,行为逐字节一致)—————
231
-
232
- // PTC 兼容(2026-10-31 现场 worker-tools-ptc-only):PTC 会话的 header 工具表只有
233
- // run_code,其余工具走 run_code 程序里的 SDK 绑定(宿主 ptc.ts 用
234
- // tools.schemas(agent, toolSet) 枚举"调用 agent 的可见面")。preset 组合没列出本插件
235
- // 时,fork 的注册表里根本没有 memu_*,worker 既不能原生调用也没有 SDK 绑定,回执只能
236
- // 是 tools-unavailable。修法与 preset-scope.js 的注入挂载同构:把 worker 读写面挂进 fork
237
- // 自己的 ctx scope —— 注册表按 scope 链取可见面,所以只对这个 worker 可见,不扩散到
238
- // 其它会话;挂载点必须在 followup 之前(宿主在 step 开始时 resolve 一次 admitted set,
239
- // 之后注册的工具不进本步)。失败不阻断整理:worker 会按任务书如实回执 tools-unavailable。
240
- export async function attachWorkerTools(agents, childId, parentId) {
241
- const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
242
- const ctxOf = (record) => {
243
- try { return record?.ctx || record?.agent?.ctx || null } catch { return null }
244
- }
245
- let parentHasCtx = null
246
- for (let attempt = 0; attempt < 6; attempt += 1) {
247
- let record = null
248
- try { record = agents.get?.(childId) || null } catch { record = null }
249
- if (record) {
250
- const actx = ctxOf(record)
251
- // 有记录但没有 ctx:这版宿主不暴露 agent context(preset-scope.js 的同款限制),
252
- // 重试不会变出来。ctx 在但没有 tools 服务:组合里就没有。两者都直接放弃。
253
- if (!actx || !(actx.tools && typeof actx.tools.register === 'function')) break
254
- try {
255
- const dispose = registerTools(actx, { only: wanted })
256
- // tools.js 在 disposer 上附挂实际注册成功的名单(编译 + register 都过的那部分)。
257
- // 读它,不再把 wanted 全量当成"已挂载"——部分挂载必须结构化可见。
258
- const attached = Array.isArray(dispose?.attached) ? [...dispose.attached] : null
259
- return {
260
- dispose,
261
- attached,
262
- requested: wanted,
263
- // 名单缺失 = 无法证明挂全:partial 照实标 true,attached 落 null(与失败同口径)。
264
- partial: attached ? attached.length < wanted.length : true,
265
- }
266
- } catch (error) {
267
- warn('consolidation worker tool attach failed: ' + String(error?.message || error))
268
- return null
269
- }
270
- }
271
- // 子记录还没出现:只在这个宿主确实会暴露 ctx(父记录带 ctx)时才值得短退避等它。
272
- if (parentHasCtx === null) parentHasCtx = Boolean(ctxOf(agents.get?.(parentId)))
273
- if (!parentHasCtx) break
274
- await new Promise(resolve => setTimeout(resolve, 100))
275
- }
276
- warn('consolidation worker has no tools service on its own context; the worker may be unable to write memories')
277
- return null
278
- }
279
-
280
- // 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件,见 private.js workerToolsMeta):
281
- // workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认。
282
- // workerToolsRequested 请求挂载的完整 wanted 名单;与 attached 全等才是全量挂载。
283
- // workerToolsPartial true = 未证明 worker 拿到完整 wanted 集。
284
- // A fork inherits the parent preset's plugin tools. `tools.restrict()` is scoped
285
- // to the child agent, so this removes every plugin tool the worker never uses
286
- // without touching the parent session. Restrict before followup: the host
287
- // resolves the admitted set at step start.
288
- export async function restrictWorkerTools(agents, childId, parentId) {
289
- for (let attempt = 0; attempt < 6; attempt += 1) {
290
- let record = null
291
- try { record = agents.get?.(childId) || null } catch { record = null }
292
- const actx = record?.ctx || record?.agent?.ctx || null
293
- if (actx && actx.tools && typeof actx.tools.restrict === 'function') {
294
- try {
295
- const dispose = actx.tools.restrict({ allow: WORKER_TOOL_ALLOW })
296
- return { dispose, allowed: [...WORKER_TOOL_ALLOW] }
297
- } catch (error) {
298
- // A host missing one of the optional tools must not lose consolidation;
299
- // retry with the write/read core and let the brief tell the truth.
300
- const core = [...CORE_WRITE_TOOLS]
301
- try {
302
- return { dispose: actx.tools.restrict({ allow: core }), allowed: core }
303
- } catch (inner) {
304
- warn('consolidation worker tool restriction failed: ' + String(inner?.message || inner))
305
- return null
306
- }
307
- }
308
- }
309
- if (record || !(agents.get?.(parentId))) return null
310
- await new Promise(resolve => setTimeout(resolve, 100))
311
- }
312
- return null
313
- }
314
-
315
- // —— epoch 句柄注册表 ————————————————————————————————————————————
316
- // attach/restrict 的 disposer 是插件侧闭包,必须活过整个 epoch(跨窗复用、退役时统一
317
- // dispose)。进程内 Map:重启后注册表随进程消失,resume 回来的 worker 由 acquireWorker
318
- // 重新挂一次工具面(宿主的工具注册也是进程内的,本来就非重挂不可)。
319
- const epochDisposables = new Map()
320
-
321
- function disposablesOf(forkId) {
322
- return epochDisposables.get(forkId) || null
323
- }
324
-
325
- // 有界等 whenIdle:返回是否真的落到 idle(true=可安全复用/已收敛;false=时限内仍忙)。
326
- // whenIdle 缺失视为 idle(老宿主/mock 无此能力时不阻塞);reject 也视为 idle(多半已 dispose)。
327
- async function waitWorkerIdle(handle, idleWaitMs) {
328
- if (!handle?.agent || typeof handle.agent.whenIdle !== 'function') return true
329
- let idle = false
330
- let timer = null
331
- try {
332
- await Promise.race([
333
- Promise.resolve(handle.agent.whenIdle()).then(() => { idle = true }, () => { idle = true }),
334
- new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Number(idleWaitMs) || 0)) }),
335
- ])
336
- } catch {} finally { if (timer) clearTimeout(timer) }
337
- return idle
338
- }
339
-
340
- // Read the public child's cursor AFTER idle, before subscribing to a new window.
341
- // Catch up output that landed with the old listener detached, charging its epoch
342
- // without adding a window. Fence its replay off from the next job's counters.
343
- async function workerEventCursor(ctx, forkId, previous = null, measureTail = false) {
344
- let lease = null
345
- try {
346
- const query = ctx?.get?.('sessionQuery')
347
- if (typeof query?.observeSession === 'function') lease = await query.observeSession(forkId, { projectionMode: 'none' })
348
- else if (typeof query?.readSession === 'function') lease = await query.readSession(forkId)
349
- let cursor = Number.isSafeInteger(previous) ? previous : null
350
- if (Number.isSafeInteger(lease?.cursor)) cursor = Math.max(cursor ?? -1, lease.cursor)
351
- const rows = Array.isArray(lease?.events) ? lease.events : []
352
- for (const event of rows) {
353
- if (Number.isSafeInteger(event?.seq)) cursor = Math.max(cursor ?? -1, event.seq)
354
- }
355
- let tail = null
356
- if (measureTail && cursor !== null && cursor > (previous ?? -1)) {
357
- // Seed identities from the old prefix, then take only the new counters.
358
- // PTC start/result and repeated request usage can straddle the timeout.
359
- const tracker = createConsolidationMeasurement('worker', { sessionId: forkId })
360
- const prefix = rows.filter(event => Number.isSafeInteger(event?.seq) && event.seq <= (previous ?? -1))
361
- const added = rows.filter(event => Number.isSafeInteger(event?.seq) && event.seq > (previous ?? -1))
362
- if (added.length === 0) return { cursor, tail: null, unavailable: true }
363
- for (const event of prefix) tracker.observe(event)
364
- const before = { ...tracker.measurement.observed }
365
- for (const event of added) tracker.observe(event)
366
- tail = tracker.measurement
367
- for (const key of ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars', 'estimatedTokens']) {
368
- if (tail.observed[key] !== null) tail.observed[key] -= before[key] ?? 0
369
- }
370
- }
371
- return { cursor, tail }
372
- } catch {
373
- warn('consolidation worker event cursor unavailable; using the last measured cursor')
374
- return { cursor: previous, tail: null, unavailable: true }
375
- } finally {
376
- try { lease?.[Symbol.dispose]?.() } catch {}
377
- }
378
- }
379
-
380
- // —— 退役(§4.5 退役动作)———————————————————————————————————————
381
- // 先 abort epoch 控制器(取消在跑回合)→ 等 idle(有上限)→ dispose 工具 restriction/handle
382
- // → dispose agent → 删子绑定 → 清父绑定 workerEpoch → 活动日志记 epoch 结束。
383
- // reason ∈ 'scope-change' | 'char-limit' | 'window-limit' | 'idle-ttl' | 'failure' | 'timeout-x2';
384
- // scope-change / failure 不做交接(不带病工作),其余默认交接——交接包由下一窗初生时组装。
385
- export async function retireWorker(ctx, forkId, reason, { handoff, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS } = {}) {
386
- const agents = (() => { try { return ctx?.get?.('agents') || null } catch { return null } })()
387
- const binding = (() => { try { return getSessionBinding(forkId) } catch { return null } })()
388
- const epoch = binding?.workerEpoch && typeof binding.workerEpoch === 'object' ? binding.workerEpoch : null
389
- const parentSessionId = epoch?.parentSession || binding?.parentSessionId || null
390
- const disposables = disposablesOf(forkId)
391
- // 0. 先取消在跑回合:epoch 控制器绑定在 agent 生命周期上(A2),abort 才能让卡住的
392
- // 回合尽快收敛,下面的有界 whenIdle 才不会白等满时限。
393
- try { disposables?.abort?.abort() } catch {}
394
- // 1. 等 whenIdle(有上限):超时退役后 worker 可能还在跑上一回合的工具。
395
- let handle = null
396
- try { handle = agents?.get?.(forkId) || null } catch { handle = null }
397
- await waitWorkerIdle(handle, idleWaitMs)
398
- // 2. dispose 工具面(本模块注册表)+ agent 本体。找不到 handle(已死/已重启)就跳过,
399
- // 剩下的清理照做——「视为已死,冷启动」(§4.5 非条件项)。
400
- epochDisposables.delete(forkId)
401
- try { disposables?.restriction?.dispose?.() } catch {}
402
- try { disposables?.tools?.dispose?.() } catch {}
403
- try { await ((handle?.agent) || handle)?.dispose?.() } catch {}
404
- // 3. 删子绑定;turn-log 不删(§3.4:日志比 worker 活得长)。
405
- try { deleteSessionBinding(forkId) } catch {}
406
- // 4. 父绑定 epoch 清零(binding.workerEpoch 清零 → 下窗走初生路径)。
407
- if (parentSessionId) {
408
- try {
409
- const parent = getSessionBinding(parentSessionId)
410
- if (parent?.workerEpoch?.forkSessionId === forkId) setSessionBinding(parentSessionId, { workerEpoch: null })
411
- } catch {}
412
- }
413
- // 5. 活动日志记 epoch 结束(退役是常规操作而非故障:qq-bridge 类长会话周期性到点换新,§6)。
414
- try {
415
- record({
416
- kind: 'check',
417
- scope: 'private',
418
- sessionId: parentSessionId || forkId,
419
- libraryId: binding?.libraryId || null,
420
- ok: true,
421
- message: '整理 worker 退役 · ' + String(reason || 'unknown')
422
- + (handoff === true ? ' · 交接(下窗交接包冷启动)' : ' · 不交接')
423
- + ' · epoch ' + (Number(epoch?.index) || '?') + ' · ' + (Number(epoch?.windows) || 0) + ' 窗 / ' + (Number(epoch?.chars) || 0) + ' 字符',
424
- detail: { forkId, reason: reason || null, handoff: handoff === true, epoch: epoch ? { index: epoch.index, chars: epoch.chars, windows: epoch.windows } : null },
425
- })
426
- } catch {}
427
- return { ok: true, forkId, reason, handoff: handoff === true, hadHandle: Boolean(handle) }
428
- }
429
-
430
- // —— epoch 记账 ——————————————————————————————————————————————————————
431
- // 每窗一次:chars += 增量 + 观测到的 worker 产出(监听器顺手累计的 assistant/tool 体积);
432
- // windows += 1;结算成功清超时计数;超时 +1(连续 2 次 → 退役,§4.4);idleAt 记
433
- // whenIdle 完成时刻(条件 4 的 TTL 起算点)。binding 传父会话的(内部重读最新值再写,
434
- // 避免覆盖并发的绑定补丁);子绑定里的 epoch 副本同步刷新。
435
- export function recordEpochProgress(binding, { measurement = null, incrementChars = 0, workerOutputChars = 0, idleAt = null, settled = false, timeout = false, progress = true, countWindow = true, usageTotals = false, now = Date.now() } = {}) {
436
- const sessionId = binding?.sessionId
437
- if (!sessionId) return null
438
- const current = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
439
- const epoch = current?.workerEpoch
440
- if (!epoch || typeof epoch !== 'object' || !epoch.forkSessionId) return null
441
- const timeouts = Number(epoch.timeouts) || 0
442
- const inputChars = measurement ? measurement.dispatched.inputChars : incrementChars
443
- const outputChars = measurement
444
- ? ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars'].reduce((sum, key) => sum + (measurement.observed[key] ?? 0), 0)
445
- : workerOutputChars
446
- const usage = { ...(epoch.usage || Object.fromEntries(USAGE_FIELDS.map(key => [key, null]))) }
447
- if (progress && measurement) {
448
- for (const key of USAGE_FIELDS) {
449
- usage[key] = usageTotals ? measurement.usage[key]
450
- : measurement.usage[key] === null || ((Number(epoch.windows) || 0) > 0 && usage[key] === null)
451
- ? null : (usage[key] ?? 0) + measurement.usage[key]
452
- }
453
- }
454
- const next = {
455
- ...epoch,
456
- chars: Math.max(0, Number(epoch.chars) || 0)
457
- + (progress ? Math.max(0, Number(inputChars) || 0) + Math.max(0, Number(outputChars) || 0) : 0),
458
- // Legacy callers/unknown serialization must never certify a partially measured epoch.
459
- measurementVersion: progress ? (measurement && measurement.serializationErrors === 0 ? 2 : null) : epoch.measurementVersion,
460
- estimatedTokens: progress
461
- ? (!measurement || epoch.estimatedTokens === null || measurement.observed.estimatedTokens === null ? null
462
- : (Number(epoch.estimatedTokens) || 0) + measurement.dispatched.estimatedTokens + measurement.observed.estimatedTokens)
463
- : epoch.estimatedTokens ?? null,
464
- usage,
465
- lastEventSeq: measurement?.lastEventSeq ?? epoch.lastEventSeq ?? null,
466
- lateOutputChars: (Number(epoch.lateOutputChars) || 0) + (progress && !countWindow ? outputChars : 0),
467
- windows: (Number(epoch.windows) || 0) + (progress && countWindow ? 1 : 0),
468
- timeouts: timeout ? timeouts + 1 : (settled ? 0 : timeouts),
469
- lastIdleAt: idleAt ? new Date(Number(idleAt) || now).toISOString() : (epoch.lastIdleAt || null),
470
- }
471
- try { setSessionBinding(sessionId, { workerEpoch: next }) } catch (error) {
472
- try { warn('worker epoch progress write failed: ' + String(error?.message || error)) } catch {}
473
- return null
474
- }
475
- try {
476
- const child = getSessionBinding(epoch.forkSessionId)
477
- if (child) setSessionBinding(epoch.forkSessionId, { workerEpoch: next })
478
- } catch {}
479
- return next
480
- }
481
-
482
- // —— 三级试活(§4.6)———————————————————————————————————————————————
483
- /**
484
- * 获取或初生持久 worker。退役条件全部只在 acquire 时检查(执行中不误杀,§4.5):
485
- * 1. scope/库/域变化 → 立即退役,无交接(上下文已污染)
486
- * 2. 预算合格制(budgetFit)→ 换新,交接
487
- * 3. epoch 窗口数超限 → 换新,交接
488
- * 4. 距上一窗 idle 超 TTL → 换新,交接
489
- * 条件 5(失败)与超时×2 是反应式退役,由 private.js 在结算失败/超时路径调用 retireWorker。
490
- *
491
- * 返回:
492
- * { ok:true, forkId, handle, birth, reused, resumed, epoch, tools, restriction, epochAbort, retired, handoff }
493
- * | { ok:false, reasonCode, error, retired? }
494
- * handoff = 本 次 获 取 是否允许交接包语义(退役原因决定;无退役的复用窗口为 false)。
495
- * epochAbort = 绑在 worker 生命周期上的控制器,供调用方硬停/重验时真正停住持久 worker(A2)。
496
- */
497
- export async function acquireWorker(ctx, binding, {
498
- incrementChars = 0, settings = null, probe = null,
499
- agentOptions = null, header = null, afterEpochIndex = 0, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS,
500
- } = {}) {
501
- const sessionId = binding?.sessionId
502
- if (!sessionId) return { ok: false, reasonCode: 'no-binding', error: 'acquireWorker requires a session binding' }
503
- const agents = ctx?.get?.('agents')
504
- if (!agents || typeof agents.create !== 'function') {
505
- return { ok: false, reasonCode: 'no-agents-service', error: 'host has no agents.create; the consolidation worker cannot start' }
506
- }
507
- settings = settings || getSettings()
508
- const liveBinding = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
509
- const retired = []
510
- let epoch = liveBinding?.workerEpoch && typeof liveBinding.workerEpoch === 'object' ? liveBinding.workerEpoch : null
511
- const prevIndex = Math.max(Number(epoch?.index) || 0, Number(afterEpochIndex) || 0)
512
- let handoff = true // 初生包默认带交接上下文(§5.1:初生包与 handoff 包是同一个东西)
513
-
514
- // —— Stage A:退役条件(只在这里查)———————————————————————————————
515
- if (epoch?.forkSessionId) {
516
- const generation = scopeGenerationOf(liveBinding)
517
- const budget = epochBudget(liveBinding, settings)
518
- let reason = null
519
- if (!epoch.scopeGeneration || epoch.scopeGeneration !== generation) reason = 'scope-change'
520
- else if (epoch.measurementVersion !== 2) reason = 'measurement-upgrade'
521
- else if (epoch.lastIdleAt && now - (Date.parse(epoch.lastIdleAt) || 0) > WORKER_EPOCH_IDLE_TTL_MS) reason = 'idle-ttl'
522
- else if (!budgetFit(epoch, incrementChars, settings)) reason = 'char-limit'
523
- else if ((Number(epoch.windows) || 0) >= budget.maxWindows) reason = 'window-limit'
524
- if (reason) {
525
- // scope-change 不交接(§4.5 条件 1);其余三个都交接(§5.2:上下文活在文件和账本里)。
526
- const withHandoff = reason !== 'scope-change'
527
- const result = await retireWorker(ctx, epoch.forkSessionId, reason, { handoff: withHandoff, now, idleWaitMs })
528
- retired.push({ forkId: epoch.forkSessionId, reason, handoff: withHandoff, ok: result?.ok === true })
529
- handoff = withHandoff
530
- epoch = null
531
- }
532
- }
533
-
534
- // —— Stage B:试活(get 进程内 → resume 跨重启 → 都失败视为已死)—————————————————
535
- // 句柄归一化(bench 实测 bug #1):宿主 create 返回 handle 包装({agent,...}),而
536
- // agents.get 返回**裸 Agent**——复用分支若把裸 Agent 当 handle 返回,派发处的
537
- // `handle.agent.followup` 会读 undefined 崩溃(bench arm B 实录:窗口 2 复用后
538
- // exception,后续窗口全部 already-exists)。归一成 create 同形状,三种来源统一。
539
- const toHandle = (raw) => (raw ? (raw.agent != null ? raw : { agent: raw }) : null)
540
- if (epoch?.forkSessionId) {
541
- let handle = null
542
- try { handle = (typeof agents.get === 'function' && toHandle(agents.get(epoch.forkSessionId))) || null } catch { handle = null }
543
- let resumed = false
544
- let resumeAbort = null
545
- if (!handle && typeof agents?.resume === 'function') {
546
- // 能力探测(任务约束):resume 不可用/抛错都跳过此级,绝不抛错。
547
- // resume 的 signal 同样被宿主绑到 agent 生命周期(initializeAgent),作为新 epoch 的 abort。
548
- resumeAbort = new AbortController()
549
- try { handle = toHandle(await agents.resume({ resumeSessionId: epoch.forkSessionId, signal: resumeAbort.signal })) || null } catch { handle = null }
550
- resumed = Boolean(handle)
551
- }
552
- // A persisted header cannot be repaired through create.meta on resume. Retire
553
- // instead of changing the user's filesystem or keeping an unusable cwd.
554
- const workerCwd = handle?.agent?.session?.header?.cwd
555
- if (handle && typeof workerCwd === 'string' && resolveConsolidationCwd(workerCwd, null) !== workerCwd) {
556
- try { resumeAbort?.abort() } catch {}
557
- const result = await retireWorker(ctx, epoch.forkSessionId, 'cwd-invalid', { handoff: true, now, idleWaitMs })
558
- retired.push({ forkId: epoch.forkSessionId, reason: 'cwd-invalid', handoff: true, ok: result?.ok === true })
559
- handoff = true
560
- epoch = null
561
- handle = null
562
- }
563
- if (handle) {
564
- let disposables = disposablesOf(epoch.forkSessionId)
565
- if (resumed) {
566
- // 崩溃恢复(§4.6):工具注册是进程内的,resume 回来的 worker 必须重挂读写面。
567
- const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, epoch.forkSessionId, sessionId)
568
- const restriction = await restrictWorkerTools(agents, epoch.forkSessionId, sessionId)
569
- disposables = { tools, restriction, abort: resumeAbort }
570
- epochDisposables.set(epoch.forkSessionId, disposables)
571
- }
572
- // A1(设计 §4.4):复用前必须等上一回合落地(有界)。超时废回合后 worker 可能还在跑,
573
- // 直接发下一窗会把上一回合的 turn/end/回执/工具轮灌进本窗监听器。等到 idle 才安全;
574
- // 等不到就是卡死——退役冷启动(宁可早换新),绝不把新回合塞进一个还在忙的 worker。
575
- const idle = await waitWorkerIdle(handle, idleWaitMs)
576
- if (idle) {
577
- const eventState = await workerEventCursor(ctx, epoch.forkSessionId, epoch.lastEventSeq, (Number(epoch.windows) || 0) > 0)
578
- if ((eventState.unavailable && (Number(epoch.timeouts) || 0) > 0) || eventState.tail?.serializationErrors > 0) {
579
- await retireWorker(ctx, epoch.forkSessionId, 'measurement-unavailable', { handoff: true, now, idleWaitMs })
580
- return { ok: false, reasonCode: 'worker-measurement-unavailable', retired, error: 'the late worker output could not be measured; the range stays pending for a fresh worker' }
581
- }
582
- if (eventState.tail) {
583
- const measured = recordEpochProgress({ sessionId }, { measurement: eventState.tail, countWindow: false, usageTotals: true, now })
584
- if (!measured) return { ok: false, reasonCode: 'worker-epoch-unavailable', retired, error: 'the late worker output measurement could not be persisted' }
585
- epoch = measured
586
- }
587
- const optionsChanged = agentOptions && handle.agent.options && ['provider', 'model', 'reasoningEffort', 'maxTokens']
588
- .some(key => (agentOptions[key] ?? null) !== (handle.agent.options[key] ?? null))
589
- if (!optionsChanged) {
590
- return {
591
- ok: true, forkId: epoch.forkSessionId, handle,
592
- birth: false, reused: true, resumed, epoch,
593
- eventCursor: eventState.cursor,
594
- tools: disposables?.tools || null, restriction: disposables?.restriction || null,
595
- epochAbort: disposables?.abort || null,
596
- retired, handoff: false,
597
- }
598
- }
599
- const result = await retireWorker(ctx, epoch.forkSessionId, 'model-options-change', { handoff: true, now, idleWaitMs })
600
- retired.push({ forkId: epoch.forkSessionId, reason: 'model-options-change', handoff: true, ok: result?.ok === true })
601
- handoff = true
602
- epoch = null
603
- } else {
604
- const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
605
- retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, stuck: true, ok: result?.ok === true })
606
- handoff = true
607
- epoch = null
608
- }
609
- } else if (epoch?.forkSessionId) {
610
- // 死亡(重启后 resume 不可用/会话被删):冷启动 + 交接包(§8);worker 会话本身没有
611
- // 可等的回合,retire 只做清理与记账。
612
- const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
613
- retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, gone: true, ok: result?.ok === true })
614
- handoff = true
615
- epoch = null
616
- }
617
- }
618
-
619
- // —— Stage C:初生(§4.1)———————————————————————————————————————————
620
- let index = prevIndex + 1
621
- let forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
622
- const modelMaxContext = await probeModelMaxContext(ctx, agentOptions)
623
- // A2:epoch 级 abort 控制器,绑到 agent 生命周期(宿主把 create.signal 永久接到 lifetime)。
624
- // 续窗的硬停/重验 abort 它才能真正停住持久 worker——窗口级 signal 只在出生那次被宿主接线。
625
- const epochAbort = new AbortController()
626
- // 无种子创建(宿主 0.2.2-rc.3 已核实 seed 可选):初生包改为第一条 followup 消息,
627
- // worker 路径完全解除 buildForkSeed 依赖(§4.1)。
628
- // 同 id 撞车(bench 实测 bug):窗口 2 派发崩溃 → retireWorker('failure') 清 epoch,
629
- // 但 dispose 只关句柄不删会话文件 → 下一窗初生用同一 forkId 被宿主拒绝
630
- // (worker-create-failed: already exists,bench 实测连挂 10 次)→ 增量永远整理不进库。
631
- // 撞车处理:无法证明旧上下文尺寸的孤儿保守退役,index 顺延换新 id
632
- // (≤6 次,逐个跳过已占用的持久 id),绝不把既有上下文记成零。
633
- let handle = null
634
- for (let createAttempt = 0; createAttempt < 6; createAttempt += 1) {
635
- let collided = false
636
- try {
637
- handle = await agents.create({
638
- sessionId: forkId,
639
- meta: {
640
- cwd: resolveConsolidationCwd(header?.cwd),
641
- parentSession: sessionId,
642
- // Without this the worker is treated as an ordinary user conversation by
643
- // the injection path and the sidebar session lists(与 fork 同款隔离)。
644
- origin: 'subagent',
645
- agentPreset: header?.agentPreset,
646
- },
647
- agentOptions: agentOptions || undefined,
648
- signal: epochAbort.signal,
649
- })
650
- } catch (error) {
651
- const message = String(error?.message || error)
652
- if (!/already exist/i.test(message)) {
653
- return {
654
- ok: false, reasonCode: 'worker-create-failed', forkId, retired,
655
- error: 'the host rejected the consolidation worker: ' + message,
656
- }
657
- }
658
- collided = true
659
- }
660
- if (!collided) break
661
- // An orphan's existing context is not zero-sized. Retire it conservatively;
662
- // never adopt it with freshly reset counters or reuse its persisted id.
663
- const result = await retireWorker(ctx, forkId, 'orphan-unmeasured', { handoff: true, now, idleWaitMs })
664
- retired.push({ forkId, reason: 'orphan-unmeasured', handoff: true, ok: result?.ok === true })
665
- index += 1
666
- forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
667
- }
668
- if (!handle?.agent && !handle?.followup) {
669
- return { ok: false, reasonCode: 'worker-create-failed', forkId, retired, error: 'no worker handle after bounded create attempts' }
670
- }
671
- handle = toHandle(handle)
672
- // 工具面只在初生挂一次(§15.2 改动点 2);标准 preset 的名单里已有 memu_* 时不重复挂。
673
- const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, forkId, sessionId)
674
- const restriction = await restrictWorkerTools(agents, forkId, sessionId)
675
- epochDisposables.set(forkId, { tools, restriction, abort: epochAbort })
676
- const epochRecord = {
677
- forkSessionId: forkId,
678
- index,
679
- birthAt: new Date(Number(now) || Date.now()).toISOString(),
680
- chars: 0,
681
- schemaVersion: 2,
682
- measurementVersion: 2,
683
- estimatedTokens: 0,
684
- usage: Object.fromEntries(USAGE_FIELDS.map(key => [key, null])),
685
- lastEventSeq: null,
686
- windows: 0,
687
- timeouts: 0,
688
- scopeGeneration: scopeGenerationOf(liveBinding),
689
- parentSession: sessionId,
690
- modelMaxContext: modelMaxContext || null,
691
- lastIdleAt: null,
692
- }
693
- try {
694
- setSessionBinding(forkId, { consolidationFork: true, origin: 'subagent', workerEpoch: epochRecord })
695
- setSessionBinding(sessionId, { workerEpoch: epochRecord })
696
- } catch (error) {
697
- // epoch 记账写不进去就不该继续用持久 worker:这次整理按失败回 pending,下窗重试。
698
- try { epochAbort.abort() } catch {}
699
- try { await ((handle?.agent) || handle)?.dispose?.() } catch {}
700
- epochDisposables.delete(forkId)
701
- return {
702
- ok: false, reasonCode: 'worker-epoch-unavailable', forkId, retired,
703
- error: 'the worker epoch could not be persisted: ' + String(error?.message || error),
704
- }
705
- }
706
- return {
707
- ok: true, forkId, handle,
708
- birth: true, reused: false, resumed: false, epoch: epochRecord, tools, restriction,
709
- epochAbort,
710
- retired, handoff,
711
- }
712
- }
713
-
714
- // —— 增量读取与缺口重建(§3.3)———————————————————————————————————————
715
- /**
716
- * 本窗增量的唯一入口:turn-log 优先,缺口 rebuildRange 补,重建失败退回现场
717
- * condenseEvents(不写日志,本窗结算语义不变)。回合是不可分单位:返回整回合记录。
718
- *
719
- * 缺口按"可记录回合"判定(A3):期望记录 = 宿主事件经 buildTurnRecords 能产出的整回合;
720
- * 心跳/纯注入回合本就不落行,它们的 seq 区间不是洞,不能拿裸 seq 全覆盖去卡——否则
721
- * 带心跳的会话每窗都误判缺口、永远退回现场压缩。consolidationTurnLog=off 时不读不写
722
- * 日志,直接现场压缩(A7,设计 §10.1)。
723
- */
724
- export function loadWorkerIncrement({ sessionId, binding = null, window = null, events = [] } = {}) {
725
- const fromSeq = Number(window?.fromSeq)
726
- const throughSeq = Number(window?.throughSeq)
727
- if (!Number.isSafeInteger(fromSeq) || !Number.isSafeInteger(throughSeq) || throughSeq < fromSeq) {
728
- return { records: [], text: '', chars: 0, source: 'empty', digest: null }
729
- }
730
- const eventsInWindow = (Array.isArray(events) ? events : []).filter((event) => {
731
- const seq = Number(event?.seq)
732
- return Number.isSafeInteger(seq) && seq >= fromSeq && seq <= throughSeq
733
- })
734
- const domain = binding?.domainOverride || binding?.domain || 'general'
735
- const condenseLimits = condenseLimitsFor(domain)
736
- const condenseFallback = (why) => {
737
- let text = ''
738
- try { text = condenseEvents(eventsInWindow, WORKER_INCREMENT_FALLBACK_CHARS, condenseLimits) || '' } catch { text = '' }
739
- return { records: [], text: String(text), chars: String(text).length, source: 'fallback', digest: why }
740
- }
741
- // A7:off 时不读不写日志,直接现场压缩。
742
- let turnLogOn = true
743
- try { turnLogOn = getSettings().consolidationTurnLog !== 'off' } catch { turnLogOn = true }
744
- if (!turnLogOn) return condenseFallback('现场压缩(turn-log 已关闭)')
745
-
746
- const lastSleepSeq = Number(binding?.lastSleepSeq)
747
- const after = Number.isSafeInteger(lastSleepSeq) && lastSleepSeq >= 0 ? lastSleepSeq : -1
748
- // 工具行额度与兜底压缩都跟随领域:编码域的修改重点在工具输出/参数里。
749
- const limits = turnLogLimits(domain)
750
- const expected = buildTurnRecords(eventsInWindow, limits)
751
- const logRows = () => { try { return readIncrement(sessionId, -1).records || [] } catch { return [] } }
752
- const covers = (rows, rec) => rows.some((row) => {
753
- const s = Number(row?.seq?.[0])
754
- const e = Number(row?.seq?.[1])
755
- return Number.isSafeInteger(s) && Number.isSafeInteger(e) && s <= rec.seq[0] && e >= rec.seq[1]
756
- })
757
- let source = 'turn-log'
758
- let rows = logRows()
759
- let missing = expected.filter((rec) => !covers(rows, rec))
760
- if (missing.length > 0) {
761
- try { rebuildRange(sessionId, fromSeq, throughSeq, events, limits) } catch {}
762
- rows = logRows()
763
- missing = expected.filter((rec) => !covers(rows, rec))
764
- if (missing.length > 0) return condenseFallback('现场压缩(turn-log 缺口重建失败)')
765
- source = 'rebuilt'
766
- } else if (expected.length === 0 && eventsInWindow.length > 0) {
767
- // 没有可记录的闭合回合、日志也没覆盖:可能是开回合/裸转录,现场压缩兜底,
768
- // 避免把有内容的区间喂成空增量。
769
- const inWindow = rows.filter((row) => {
770
- const s = Number(row?.seq?.[0])
771
- const e = Number(row?.seq?.[1])
772
- return Number.isSafeInteger(s) && Number.isSafeInteger(e) && e > after && s <= throughSeq
773
- })
774
- if (inWindow.length === 0) return condenseFallback('现场压缩(无可记录回合)')
775
- }
776
- // 增量 = 尚未完整结算的整回合(seqEnd > lastSleepSeq)且起点在本窗内。窗口已在
777
- // worker 模式对齐到整回合边界(A5),正常不会有跨骑记录;此处仍按整回合过滤兜底。
778
- const records = rows.filter((row) => {
779
- const start = Number(row?.seq?.[0])
780
- const end = Number(row?.seq?.[1])
781
- return Number.isSafeInteger(start) && Number.isSafeInteger(end) && end > after && start <= throughSeq
782
- })
783
- const text = records.map((row) => JSON.stringify(row)).join('\n')
784
- const first = records.length > 0 ? Number(records[0]?.seq?.[0]) : null
785
- const last = records.length > 0 ? Number(records[records.length - 1]?.seq?.[1]) : null
786
- const digest = records.length > 0
787
- ? `${records.length} 回合 · seq ${first}–${last}${source === 'rebuilt' ? ' · 缺口重建' : ''}`
788
- : null
789
- return { records, text, chars: text.length, source, digest }
790
- }
791
-
792
- // —— 包组装(§4.2 续窗增量包 / §5.1 初生·交接包)——————————————————————————
793
-
794
- const PENDING_OPEN = '--- 待处理回合 ---'
795
- const PENDING_CLOSE = '--- 结束 ---'
796
- const TAIL_OPEN = '--- 已结算参考(勿为其写新记忆,只处理待处理区间)---'
797
- const TAIL_CLOSE = '--- 已结算参考结束 ---'
798
-
799
- function renderRecords(records) {
800
- return (Array.isArray(records) ? records : []).map((row) => JSON.stringify(row)).join('\n')
801
- }
802
-
803
- function pendingNoteLine(pendingNote, pendingHash) {
804
- if (!pendingNote) return ''
805
- if (typeof pendingNote === 'string' && pendingNote.trim()) return pendingNote
806
- const prefix = typeof pendingHash === 'string' && pendingHash ? `(${pendingHash.slice(0, 12)}…)` : ''
807
- return `[上窗未结算${prefix}] 上一窗${prefix}未结算完成:先核对库内是否已写入,勿重复写;本包与上一窗是同一段待处理区间的重发,重复写入会被去重拦下,但请先核对再动手。`
808
- }
809
-
810
- function catalogTextOf(catalog) {
811
- if (!catalog) return ''
812
- if (typeof catalog === 'string') return catalog.trim()
813
- const blocks = Array.isArray(catalog?.data?.content) ? catalog.data.content : []
814
- return blocks.map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : '')).filter(Boolean).join('\n').trim()
815
- }
816
-
817
- function catalogIdsOf(catalogText) {
818
- const ids = new Set()
819
- for (const match of String(catalogText || '').matchAll(/^- \[([^\]\n]+)\]/gm)) ids.add(match[1])
820
- return ids
821
- }
822
-
823
- /** 必写候选(续窗包):顺延候选 ≤4、总数 ≤8 的双闸在这里再兜一道(mergeMustCover 同语义)。 */
824
- function renderCarry(rows, { max = 8, carriedMax = 4 } = {}) {
825
- const list = Array.isArray(rows) ? rows : []
826
- if (list.length === 0) return ''
827
- const lines = ['[必写候选(先写这些;每条都必须落库,或在失败说明里写明为什么不写,不得静默跳过)]']
828
- let carried = 0
829
- let shown = 0
830
- for (const row of list) {
831
- if (shown >= Math.max(1, Number(max) || 8)) break
832
- const isCarried = row?.carried === true
833
- if (isCarried && carried >= Math.max(0, Number(carriedMax) || 0)) continue
834
- if (isCarried) carried += 1
835
- shown += 1
836
- const where = isCarried
837
- ? '顺延' + (row?.observedAt ? ' · 事件时间 ' + row.observedAt : '')
838
- : '第 ' + (Number.isSafeInteger(Number(row?.fromSeq)) ? row.fromSeq : '?') + '–'
839
- + (Number.isSafeInteger(Number(row?.throughSeq)) ? row.throughSeq : '?') + ' 条'
840
- + (row?.tag ? ' · ' + row.tag : '') + (row?.observedAt ? ' · 事件时间 ' + row.observedAt : '')
841
- lines.push(`${shown}. [${where}] ${String(row?.text || '').slice(0, 120)}`)
842
- }
843
- return lines.length > 1 ? lines.join('\n') : ''
844
- }
845
-
846
- function sceneTimeLine(sceneTime) {
847
- const value = typeof sceneTime === 'string' ? sceneTime.trim() : ''
848
- if (!value) return ''
849
- return `[场景时间] ${value}(时间锚点:observed_at 与今天/明天/下周X 等相对日期按这个场景时间推算,不要用真实时钟。)`
850
- }
851
-
852
- /**
853
- * 已写入摘要(§4.2/§5.2):账本 recordOperation 历史 → 最近 20 条 id+标题 +
854
- * 「另有 M 条均已在库」,与目录头按 id 去重。摘要只是省无效写入的成本优化,
855
- * 不是正确性防线(铁律 1:对账与库级去重兜底)。
856
- */
857
- function writtenSummary(sessionId, binding, { writtenRows = null, writtenTotal = null, catalogIds = new Set(), limit = 20 } = {}) {
858
- let ids = []
859
- let total = null
860
- if (Array.isArray(writtenRows)) {
861
- ids = writtenRows.map((row) => String(row?.id || '')).filter(Boolean)
862
- total = Number.isSafeInteger(Number(writtenTotal)) ? Number(writtenTotal) : ids.length
863
- } else {
864
- let ops = []
865
- try { ops = Object.values(loadLedger().sessions?.[String(sessionId || '')]?.operations || {}) } catch { ops = [] }
866
- for (const op of ops.slice().sort((a, b) => String(b?.at || '').localeCompare(String(a?.at || '')))) {
867
- for (const id of Array.isArray(op?.ids) ? op.ids : []) {
868
- const key = String(id || '')
869
- if (key && !ids.includes(key)) ids.push(key)
870
- }
871
- }
872
- total = ids.length
873
- }
874
- const deduped = ids.filter((id) => !catalogIds.has(id))
875
- const shown = deduped.slice(0, Math.max(1, Number(limit) || 20))
876
- if (shown.length === 0) return ''
877
- const titles = new Map()
878
- if (Array.isArray(writtenRows)) {
879
- for (const row of writtenRows) titles.set(String(row?.id || ''), String(row?.title || '(untitled)').slice(0, 80))
880
- } else {
881
- try {
882
- const entries = loadPrivateIndex(binding?.libraryId)?.entries || {}
883
- for (const id of shown) titles.set(id, String(entries[id]?.title || '(untitled)').slice(0, 80))
884
- } catch { /* 索引缺失只降级标题,摘要照发 */ }
885
- }
886
- const lines = ['[已写入摘要(账本记录,防重复写;目录里已有的不再列出)]']
887
- for (const id of shown) lines.push(`- [${id}] ${titles.get(id) || '(untitled)'}`)
888
- const rest = Math.max(0, (Number(total) || deduped.length) - shown.length)
889
- if (rest > 0) lines.push(`另有 ${rest} 条均已在库。`)
890
- return lines.join('\n')
891
- }
892
-
893
- /** 交接尾部(§5.2):tailSlice 整回合取尾,再滤掉未结算段(seqEnd ≤ lastSleepSeq)。 */
894
- function tailSection(sessionId, { lastSleepSeq = null, tailChars = WORKER_HANDOFF_TAIL_CHARS } = {}) {
895
- const ceiling = Number.isSafeInteger(Number(lastSleepSeq)) && Number(lastSleepSeq) >= 0 ? Number(lastSleepSeq) : null
896
- // 没有结算游标 = 整份日志都是未结算增量,没有「已结算参考」可带(尾部会与增量整段重复)。
897
- if (ceiling === null) return ''
898
- let slice = null
899
- try { slice = tailSlice(sessionId, tailChars) } catch { return '' }
900
- const records = (Array.isArray(slice?.records) ? slice.records : []).filter((row) => {
901
- const end = Number(row?.seq?.[1])
902
- return Number.isSafeInteger(end) && end <= ceiling
903
- })
904
- if (records.length === 0) return ''
905
- return [TAIL_OPEN, renderRecords(records), TAIL_CLOSE].join('\n')
906
- }
907
-
908
- /**
909
- * 续窗增量包(§4.2):分隔标记夹住的待处理回合 + 目录头(每窗都发)+ 必写候选
910
- * (顺延 ≤4)+ 回执契约 + 场景时间(每窗重读)。已写入摘要不发(worker 上下文里
911
- * 刚写过,续窗发是冗余);上一窗未结算时开头带核对说明(§4.4)。
912
- */
913
- export function buildIncrementPack({
914
- binding = null, incrementRecords = [], incrementText = null, catalog = null,
915
- digest = null, carry = [], contract = '', sceneTime = null,
916
- pendingNote = false, pendingHash = null, carryMax = 4,
917
- } = {}) {
918
- const sections = []
919
- const note = pendingNoteLine(pendingNote, pendingHash)
920
- if (note) sections.push(note)
921
- if (digest) sections.push('[待处理增量] ' + String(digest))
922
- sections.push(PENDING_OPEN)
923
- const body = (typeof incrementText === 'string' && incrementText.trim()) ? incrementText : renderRecords(incrementRecords)
924
- sections.push(body || '(本窗没有可读的回合记录)')
925
- sections.push(PENDING_CLOSE)
926
- const catalogText = catalogTextOf(catalog)
927
- if (catalogText) sections.push(catalogText)
928
- const carryText = renderCarry(carry, { carriedMax: carryMax })
929
- if (carryText) sections.push(carryText)
930
- if (typeof contract === 'string' && contract.trim()) sections.push(contract)
931
- const sceneLine = sceneTimeLine(sceneTime)
932
- if (sceneLine) sections.push(sceneLine)
933
- return sections.join('\n')
934
- }
935
-
936
- /**
937
- * 初生包 = 交接包(§5.1):身份/规则任务书(buildWorkerBrief,必写候选随它下发)+
938
- * 待处理回合 + 库目录头 + 已写入摘要(最近 20 条 + 计数,与目录去重)+ turn-log 尾部
939
- * (标注「已结算参考」,滤掉未结算段)+ 场景时间。退役原因 scope-change / failure 时
940
- * 由调用方传 includeTail: false / writtenRows: []——「不做 handoff」= 不带旧 epoch 的
941
- * 连续性材料,身份与目录照发。
942
- */
943
- export function buildHandoffPack({
944
- sessionId = null, binding = null, snapshot = null, probe = null, jobId = null,
945
- reason = 'auto', singleOnly = false, mustCover = [], contract = '', domain = 'general',
946
- incrementRecords = [], incrementText = null, digest = null,
947
- catalog = null, sceneTime = null, pendingNote = false, pendingHash = null,
948
- writtenRows = null, writtenTotal = null,
949
- lastSleepSeq = null, tailChars = WORKER_HANDOFF_TAIL_CHARS, includeTail = true,
950
- } = {}) {
951
- const brief = buildWorkerBrief({ snapshot, probe, contract, reason, jobId, mustCover, autoReceipt: true, singleOnly, domain })
952
- const sections = [brief]
953
- const note = pendingNoteLine(pendingNote, pendingHash)
954
- if (note) sections.push(note)
955
- if (digest) sections.push('[待处理增量] ' + String(digest))
956
- sections.push(PENDING_OPEN)
957
- const body = (typeof incrementText === 'string' && incrementText.trim()) ? incrementText : renderRecords(incrementRecords)
958
- sections.push(body || '(本窗没有可读的回合记录)')
959
- sections.push(PENDING_CLOSE)
960
- const catalogText = catalogTextOf(catalog)
961
- if (catalogText) sections.push(catalogText)
962
- const summary = writtenSummary(sessionId, binding, { writtenRows, writtenTotal, catalogIds: catalogIdsOf(catalogText) })
963
- if (summary) sections.push(summary)
964
- if (includeTail !== false && sessionId) {
965
- const tail = tailSection(sessionId, { lastSleepSeq, tailChars })
966
- if (tail) sections.push(tail)
967
- }
968
- const sceneLine = sceneTimeLine(sceneTime)
969
- if (sceneLine) sections.push(sceneLine)
970
- return sections.join('\n')
971
- }
972
-
973
- export default {
974
- WORKER_EPOCH_TIERS, WORKER_OUTPUT_FACTOR, WORKER_EPOCH_IDLE_TTL_MS, WORKER_HANDOFF_TAIL_CHARS,
975
- WORKER_TIMEOUT_LIMIT, WORKER_RETIRE_IDLE_WAIT_MS, WORKER_INCREMENT_FALLBACK_CHARS,
976
- epochBudget, budgetFit, packetBudgetFit, measurePacket, createConsolidationMeasurement,
977
- resolveConsolidationCwd, probeModelMaxContext, attachWorkerTools, restrictWorkerTools,
978
- retireWorker, recordEpochProgress, acquireWorker, loadWorkerIncrement, buildIncrementPack, buildHandoffPack,
979
- }
1
+ // Manage the lifecycle of persistent consolidation workers.
2
+ //
3
+ // 定位:worker 与 turn-log 一样是缓存,账本才算数(§0 铁律 1)。本模块只负责
4
+ // 「谁来写」与「喂什么」:三级试活(agents.get → agents.resume 能力探测 → 初生,
5
+ // §4.6)、epoch 记账与退役条件(只在 acquire 时检查,§4.5)、增量包/交接包组装
6
+ // (§4.2/§5.1)、超时计数与退役(§4.4)。每窗结算仍走 private.js 现有的
7
+ // decideCompletion/completeJob/lastSleepSeq/carry 链路,一行语义不改。
8
+ //
9
+ // 默认 consolidationRunner: 'fork'——本模块的全部路径只在设置显式切到 'worker'
10
+ // 时被 private.js 调用;'fork'(现状每窗新 fork)行为逐字节不变。
11
+ import { getSessionBinding, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex } from './state.js'
12
+ import fs from 'node:fs'
13
+ import { warn, shortHash, dataDir } from './paths.js'
14
+ import { estTokens } from './budget.js'
15
+ import { record } from './activity-log.js'
16
+ import { loadLedger, scopeGenerationOf } from './consolidation-ledger.js'
17
+ import { presetSetupFor, resolveConsolidationPreset } from './preset-mount.js'
18
+ import { buildWorkerBrief, CORE_WRITE_TOOLS, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW } from './consolidation-worker.js'
19
+ import { registerTools } from './tools.js'
20
+ import { tailSlice, readIncrement, rebuildRange, buildTurnRecords, turnLogLimits } from './turn-log.js'
21
+ import { condenseEvents, condenseLimitsFor } from './curator.js'
22
+
23
+ // —— epoch 预算分档(§4.5 条件 2/3)————————————————————————————————
24
+ // 按模型 maxContext 自动取档:≤128k 输入窗 → 120k 字符/8 窗;其余(含 ≥1M 旗舰)→ 200k/16。
25
+ // Bound larger-context workers to limit repeated reading of prior windows.
26
+ // A character and window budget prevents unbounded accumulation of old context.
27
+ // Discover the model's maxContext through the public host API when available
28
+ // (probeModelMaxContext);取不到按最保守的第一档。显式设置
29
+ // (workerEpochCharLimit / workerEpochMaxWindows(正整数,未来经 DEFAULT_SETTINGS
30
+ // 放开)覆盖自动档;本阶段这两个键不在设置面里,属于前向兼容钩子。
31
+ export const WORKER_EPOCH_TIERS = Object.freeze([
32
+ Object.freeze({ maxContext: 131_072, charLimit: 120_000, maxWindows: 8 }),
33
+ Object.freeze({ maxContext: 262_144, charLimit: 200_000, maxWindows: 16 }),
34
+ Object.freeze({ maxContext: Number.MAX_SAFE_INTEGER, charLimit: 200_000, maxWindows: 16 }),
35
+ ])
36
+ // 产出系数(§4.5 条件 2):触发时「epoch 已累计 + 本窗增量 × 3 ≤ LIMIT」的粗估,
37
+ // 3 倍覆盖 worker 产出与思考;窗口跑完后按实际观测替换估算(recordEpochProgress)。
38
+ export const WORKER_OUTPUT_FACTOR = 3
39
+ // 条件 4(§4.5):距上一窗 whenIdle 完成超过缓存 TTL 即换新。只在 acquire 时检查,
40
+ // 不做后台定时退役;TTL 是保守方向的启发式——早换新永不吃亏。
41
+ export const WORKER_EPOCH_IDLE_TTL_MS = 30 * 60_000
42
+ // 交接包尾部预算(§5.2):min(20k, 连续回合),tailSlice 保证整回合。
43
+ export const WORKER_HANDOFF_TAIL_CHARS = 20_000
44
+ // §4.4:超时不算失败;同一 worker 连续 2 次超时升级为退役。
45
+ export const WORKER_TIMEOUT_LIMIT = 2
46
+ // 退役时等 whenIdle 的上限:卡死的 worker 不能挂住下一次整理。
47
+ export const WORKER_RETIRE_IDLE_WAIT_MS = 5_000
48
+ // Fallback compaction budget, shared with requestRemoteConsolidation.
49
+ export const WORKER_INCREMENT_FALLBACK_CHARS = 60_000
50
+
51
+ /** 按模型 maxContext 取档;未知模型回最保守的第一档;显式设置覆盖自动档。 */
52
+ export function epochBudget(binding, settings = null) {
53
+ const explicitChars = Number(settings?.workerEpochCharLimit)
54
+ const explicitWindows = Number(settings?.workerEpochMaxWindows)
55
+ const maxContext = Number(binding?.workerEpoch?.modelMaxContext)
56
+ const tier = WORKER_EPOCH_TIERS.find((row) => Number.isSafeInteger(maxContext) && maxContext > 0 && maxContext <= row.maxContext) || WORKER_EPOCH_TIERS[0]
57
+ return {
58
+ charLimit: Number.isSafeInteger(explicitChars) && explicitChars > 0 ? explicitChars : tier.charLimit,
59
+ maxWindows: Number.isSafeInteger(explicitWindows) && explicitWindows > 0 ? explicitWindows : tier.maxWindows,
60
+ }
61
+ }
62
+
63
+ /**
64
+ * 预算合格制(§4.5 条件 2):epoch 已累计 + 本窗增量 × 产出系数 ≤ 字符上限。
65
+ * 触发时检查,粗估、宁可早换新;不做事件级精确记账(宿主 compaction 是溢出安全网)。
66
+ */
67
+ export function budgetFit(epoch, incrementChars, settings = null) {
68
+ const chars = Number(epoch?.chars) || 0
69
+ const increment = Math.max(0, Number(incrementChars) || 0)
70
+ return chars + increment * WORKER_OUTPUT_FACTOR <= epochBudget({ workerEpoch: epoch }, settings).charLimit
71
+ }
72
+
73
+ /** Never repair a user's path or change host permissions; only select a usable cwd. */
74
+ export function resolveConsolidationCwd(headerCwd, fallback = dataDir()) {
75
+ try {
76
+ if (typeof headerCwd === 'string' && headerCwd && fs.statSync(headerCwd).isDirectory()) return headerCwd
77
+ } catch { /* Deleted/inaccessible cwd: use the plugin data directory. */ }
78
+ return fallback
79
+ }
80
+
81
+ export function measurePacket(text, kind = 'increment') {
82
+ const value = String(text ?? '')
83
+ return { kind, inputChars: value.length, estimatedTokens: estTokens(value) }
84
+ }
85
+
86
+ export function packetBudgetFit(epoch, packet, settings = null) {
87
+ return budgetFit(epoch, packet?.inputChars, settings)
88
+ }
89
+
90
+ const USAGE_FIELDS = ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'outputTokens', 'reasoningTokens']
91
+
92
+ /** Per-window counters only. Event/call identities stay in closure, never bodies. */
93
+ export function createConsolidationMeasurement(runner, { sessionId = '', afterSeq = null } = {}) {
94
+ const measurement = {
95
+ schemaVersion: 2, measurementVersion: 2, runner,
96
+ packet: null,
97
+ dispatched: { inputChars: 0, estimatedTokens: 0, followups: 0, wrapupChars: 0 },
98
+ observed: { outputTextChars: 0, toolArgumentsChars: 0, toolResultsChars: 0, reasoningChars: null, estimatedTokens: 0 },
99
+ usage: { ...Object.fromEntries(USAGE_FIELDS.map(key => [key, null])), source: 'unavailable', requests: 0 },
100
+ serializationErrors: 0,
101
+ toolEvents: 0, logicalToolCalls: 0,
102
+ lastEventSeq: Number.isSafeInteger(afterSeq) ? afterSeq : null,
103
+ }
104
+ const events = new Set()
105
+ const calls = new Set()
106
+ const requests = new Map()
107
+ const objects = new WeakSet()
108
+ let anonymousEvent = 0
109
+ const serialized = (value) => {
110
+ if (typeof value === 'string') return value
111
+ if (value == null) return ''
112
+ try { return JSON.stringify(value) ?? '' } catch {
113
+ measurement.serializationErrors += 1
114
+ warn('consolidation measurement: tool payload could not be serialized; size is unknown')
115
+ return null
116
+ }
117
+ }
118
+ const add = (key, text, retained = true) => {
119
+ if (text === null) {
120
+ measurement.observed[key] = null
121
+ if (retained) measurement.observed.estimatedTokens = null
122
+ return
123
+ }
124
+ if (measurement.observed[key] !== null || key === 'reasoningChars') {
125
+ // reasoning is unknown until a real reasoning block is observed.
126
+ measurement.observed[key] = (measurement.observed[key] ?? 0) + text.length
127
+ }
128
+ if (retained && measurement.observed.estimatedTokens !== null) measurement.observed.estimatedTokens += estTokens(text)
129
+ }
130
+ const tool = (phase, id, payload, fallback) => {
131
+ const callId = typeof id === 'string' || Number.isSafeInteger(id) ? id : fallback
132
+ const key = JSON.stringify([phase, callId])
133
+ if (calls.has(key)) return
134
+ if (payload === undefined) return
135
+ calls.add(key)
136
+ if (phase === 'arguments') measurement.logicalToolCalls += 1
137
+ add(phase === 'arguments' ? 'toolArgumentsChars' : 'toolResultsChars', serialized(payload))
138
+ }
139
+ const observe = (event) => {
140
+ if (!event || typeof event !== 'object') return false
141
+ const seq = event.seq
142
+ const eventId = typeof event.id === 'string' || Number.isSafeInteger(event.id) ? event.id : null
143
+ const key = Number.isSafeInteger(seq) ? JSON.stringify([sessionId, seq]) : (eventId !== null ? JSON.stringify([sessionId, eventId]) : null)
144
+ if (Number.isSafeInteger(seq) && Number.isSafeInteger(afterSeq) && seq <= afterSeq) return false
145
+ if (key ? events.has(key) : objects.has(event)) return false
146
+ if (key) events.add(key)
147
+ else objects.add(event)
148
+ if (Number.isSafeInteger(seq)) measurement.lastEventSeq = Math.max(measurement.lastEventSeq ?? -1, seq)
149
+ const fallback = key || 'anonymous-' + (++anonymousEvent)
150
+ const data = event.data || {}
151
+ if (['tool/call', 'tool/result', 'tool/ptc-dispatch-start', 'tool/ptc-dispatch'].includes(event.type)) measurement.toolEvents += 1
152
+ if (event.type === 'assistant/message') {
153
+ for (const [index, block] of (Array.isArray(data.message?.content) ? data.message.content : []).entries()) {
154
+ if (block?.type === 'text' && typeof block.text === 'string') add('outputTextChars', block.text)
155
+ if (block?.type === 'reasoning' && typeof block.text === 'string') add('reasoningChars', block.text, false)
156
+ if (block?.type === 'tool-call') tool('arguments', block.id, block.arguments, fallback + ':' + index)
157
+ }
158
+ // Verified public assistant/message.data.usage only: input is non-cached;
159
+ // output includes reasoning when supplied. Never sum reasoning into output.
160
+ const requestId = typeof data.requestId === 'string' || Number.isSafeInteger(data.requestId) ? data.requestId : null
161
+ const requestKey = requestId !== null ? JSON.stringify([sessionId, requestId]) : key || fallback
162
+ const previous = requests.get(requestKey) || {}
163
+ let known = false
164
+ for (const field of USAGE_FIELDS) {
165
+ const value = data.usage?.[field]
166
+ if (!Number.isSafeInteger(value) || value < 0 || previous[field] !== undefined) continue
167
+ previous[field] = value
168
+ known = true
169
+ }
170
+ requests.set(requestKey, previous)
171
+ for (const field of USAGE_FIELDS) {
172
+ const rows = [...requests.values()]
173
+ measurement.usage[field] = rows.every(row => row[field] !== undefined)
174
+ ? rows.reduce((sum, row) => sum + row[field], 0) : null
175
+ }
176
+ measurement.usage.requests = requests.size
177
+ if (known) measurement.usage.source = 'assistant/message.data.usage'
178
+ }
179
+ if (event.type === 'tool/call' || event.type === 'tool/ptc-dispatch-start') {
180
+ tool('arguments', data.subCallId ?? data.callId, data.arguments, fallback)
181
+ }
182
+ if (event.type === 'tool/ptc-dispatch') {
183
+ if (data.arguments !== undefined) tool('arguments', data.subCallId ?? data.callId, data.arguments, fallback)
184
+ tool('results', data.subCallId ?? data.callId, data.content ?? event.content ?? data.message?.content, fallback)
185
+ }
186
+ if (event.type === 'tool/result') {
187
+ tool('results', data.message?.callId ?? data.callId, data.message?.content ?? data.content ?? event.content, fallback)
188
+ }
189
+ return true
190
+ }
191
+ const dispatch = (text, kind) => {
192
+ const packet = measurePacket(text, kind)
193
+ if (!measurement.packet) measurement.packet = packet
194
+ measurement.dispatched.inputChars += packet.inputChars
195
+ measurement.dispatched.estimatedTokens += packet.estimatedTokens
196
+ measurement.dispatched.followups += 1
197
+ if (kind === 'wrapup') measurement.dispatched.wrapupChars += packet.inputChars
198
+ return packet
199
+ }
200
+ return { measurement, observe, dispatch }
201
+ }
202
+
203
+ /** 宿主模型发现的 maxContext 尽力获取;拿不到返回 null(epochBudget 落第一档)。 */
204
+ export async function probeModelMaxContext(ctx, agentOptions) {
205
+ const provider = typeof agentOptions?.provider === 'string' ? agentOptions.provider : ''
206
+ const model = typeof agentOptions?.model === 'string' ? agentOptions.model : ''
207
+ if (!provider || !model) return null
208
+ const llm = (() => { try { return ctx?.get?.('llm') || null } catch { return null } })()
209
+ if (!llm) return null
210
+ // 首选 resolveModelInfo:宿主唯一的容量口径在 resolved.context.contextWindow。
211
+ // listModels catalog entries (LlmModelInfo) do not normally carry capacity fields.
212
+ try {
213
+ const resolved = await llm.resolveModelInfo?.(provider, model)
214
+ const contextWindow = Number(resolved?.context?.contextWindow)
215
+ if (Number.isSafeInteger(contextWindow) && contextWindow > 0) return contextWindow
216
+ } catch { /* 探测失败降级,绝不阻断整理 */ }
217
+ // Some hosts may expose capacity directly on the catalog entry.
218
+ try {
219
+ const models = await llm.listModels?.(provider)
220
+ if (Array.isArray(models)) {
221
+ const entry = models.find((item) => item && (item.id === model || item.name === model)) || null
222
+ for (const key of ['maxContext', 'contextLength', 'contextWindow', 'maxInputTokens', 'maxContextTokens']) {
223
+ const value = Number(entry?.[key])
224
+ if (Number.isSafeInteger(value) && value > 0) return value
225
+ }
226
+ }
227
+ } catch { /* 同上 */ }
228
+ return null
229
+ }
230
+
231
+ // —— 工具面(自 private.js 迁入;'fork' 路径调用同一份实现,行为逐字节一致)—————
232
+
233
+ // In PTC sessions the request header may expose only
234
+ // run_code,其余工具走 run_code 程序里的 SDK 绑定(宿主 ptc.ts 用
235
+ // tools.schemas(agent, toolSet) 枚举"调用 agent 的可见面")。preset 组合没列出本插件
236
+ // 时,fork 的注册表里根本没有 memu_*,worker 既不能原生调用也没有 SDK 绑定,回执只能
237
+ // 是 tools-unavailable。修法与 preset-scope.js 的注入挂载同构:把 worker 读写面挂进 fork
238
+ // 自己的 ctx scope —— 注册表按 scope 链取可见面,所以只对这个 worker 可见,不扩散到
239
+ // 其它会话;挂载点必须在 followup 之前(宿主在 step 开始时 resolve 一次 admitted set,
240
+ // 之后注册的工具不进本步)。失败不阻断整理:worker 会按任务书如实回执 tools-unavailable。
241
+ export async function attachWorkerTools(agents, childId, parentId) {
242
+ const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
243
+ const ctxOf = (record) => {
244
+ try { return record?.ctx || record?.agent?.ctx || null } catch { return null }
245
+ }
246
+ let parentHasCtx = null
247
+ for (let attempt = 0; attempt < 6; attempt += 1) {
248
+ let record = null
249
+ try { record = agents.get?.(childId) || null } catch { record = null }
250
+ if (record) {
251
+ const actx = ctxOf(record)
252
+ // 有记录但没有 ctx:这版宿主不暴露 agent context(preset-scope.js 的同款限制),
253
+ // 重试不会变出来。ctx 在但没有 tools 服务:组合里就没有。两者都直接放弃。
254
+ if (!actx || !(actx.tools && typeof actx.tools.register === 'function')) break
255
+ try {
256
+ const dispose = registerTools(actx, { only: wanted })
257
+ // tools.js 在 disposer 上附挂实际注册成功的名单(编译 + register 都过的那部分)。
258
+ // 读它,不再把 wanted 全量当成"已挂载"——部分挂载必须结构化可见。
259
+ const attached = Array.isArray(dispose?.attached) ? [...dispose.attached] : null
260
+ return {
261
+ dispose,
262
+ attached,
263
+ requested: wanted,
264
+ // 名单缺失 = 无法证明挂全:partial 照实标 true,attached 落 null(与失败同口径)。
265
+ partial: attached ? attached.length < wanted.length : true,
266
+ }
267
+ } catch (error) {
268
+ warn('consolidation worker tool attach failed: ' + String(error?.message || error))
269
+ return null
270
+ }
271
+ }
272
+ // 子记录还没出现:只在这个宿主确实会暴露 ctx(父记录带 ctx)时才值得短退避等它。
273
+ if (parentHasCtx === null) parentHasCtx = Boolean(ctxOf(agents.get?.(parentId)))
274
+ if (!parentHasCtx) break
275
+ await new Promise(resolve => setTimeout(resolve, 100))
276
+ }
277
+ warn('consolidation worker has no tools service on its own context; the worker may be unable to write memories')
278
+ return null
279
+ }
280
+
281
+ // 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件,见 private.js workerToolsMeta):
282
+ // workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认。
283
+ // workerToolsRequested 请求挂载的完整 wanted 名单;与 attached 全等才是全量挂载。
284
+ // workerToolsPartial true = 未证明 worker 拿到完整 wanted 集。
285
+ // A fork inherits the parent preset's plugin tools. `tools.restrict()` is scoped
286
+ // to the child agent, so this removes every plugin tool the worker never uses
287
+ // without touching the parent session. Restrict before followup: the host
288
+ // resolves the admitted set at step start.
289
+ export async function restrictWorkerTools(agents, childId, parentId) {
290
+ for (let attempt = 0; attempt < 6; attempt += 1) {
291
+ let record = null
292
+ try { record = agents.get?.(childId) || null } catch { record = null }
293
+ const actx = record?.ctx || record?.agent?.ctx || null
294
+ if (actx && actx.tools && typeof actx.tools.restrict === 'function') {
295
+ try {
296
+ const dispose = actx.tools.restrict({ allow: WORKER_TOOL_ALLOW })
297
+ return { dispose, allowed: [...WORKER_TOOL_ALLOW] }
298
+ } catch (error) {
299
+ // A host missing one of the optional tools must not lose consolidation;
300
+ // retry with the write/read core and let the brief tell the truth.
301
+ const core = [...CORE_WRITE_TOOLS]
302
+ try {
303
+ return { dispose: actx.tools.restrict({ allow: core }), allowed: core }
304
+ } catch (inner) {
305
+ warn('consolidation worker tool restriction failed: ' + String(inner?.message || inner))
306
+ return null
307
+ }
308
+ }
309
+ }
310
+ if (record || !(agents.get?.(parentId))) return null
311
+ await new Promise(resolve => setTimeout(resolve, 100))
312
+ }
313
+ return null
314
+ }
315
+
316
+ // —— epoch 句柄注册表 ————————————————————————————————————————————
317
+ // attach/restrict 的 disposer 是插件侧闭包,必须活过整个 epoch(跨窗复用、退役时统一
318
+ // dispose)。进程内 Map:重启后注册表随进程消失,resume 回来的 worker 由 acquireWorker
319
+ // 重新挂一次工具面(宿主的工具注册也是进程内的,本来就非重挂不可)。
320
+ const epochDisposables = new Map()
321
+
322
+ function disposablesOf(forkId) {
323
+ return epochDisposables.get(forkId) || null
324
+ }
325
+
326
+ // 有界等 whenIdle:返回是否真的落到 idle(true=可安全复用/已收敛;false=时限内仍忙)。
327
+ // whenIdle 缺失视为 idle(老宿主/mock 无此能力时不阻塞);reject 也视为 idle(多半已 dispose)。
328
+ async function waitWorkerIdle(handle, idleWaitMs) {
329
+ if (!handle?.agent || typeof handle.agent.whenIdle !== 'function') return true
330
+ let idle = false
331
+ let timer = null
332
+ try {
333
+ await Promise.race([
334
+ Promise.resolve(handle.agent.whenIdle()).then(() => { idle = true }, () => { idle = true }),
335
+ new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Number(idleWaitMs) || 0)) }),
336
+ ])
337
+ } catch {} finally { if (timer) clearTimeout(timer) }
338
+ return idle
339
+ }
340
+
341
+ // Read the public child's cursor AFTER idle, before subscribing to a new window.
342
+ // Catch up output that landed with the old listener detached, charging its epoch
343
+ // without adding a window. Fence its replay off from the next job's counters.
344
+ async function workerEventCursor(ctx, forkId, previous = null, measureTail = false) {
345
+ let lease = null
346
+ try {
347
+ const query = ctx?.get?.('sessionQuery')
348
+ if (typeof query?.observeSession === 'function') lease = await query.observeSession(forkId, { projectionMode: 'none' })
349
+ else if (typeof query?.readSession === 'function') lease = await query.readSession(forkId)
350
+ let cursor = Number.isSafeInteger(previous) ? previous : null
351
+ if (Number.isSafeInteger(lease?.cursor)) cursor = Math.max(cursor ?? -1, lease.cursor)
352
+ const rows = Array.isArray(lease?.events) ? lease.events : []
353
+ for (const event of rows) {
354
+ if (Number.isSafeInteger(event?.seq)) cursor = Math.max(cursor ?? -1, event.seq)
355
+ }
356
+ let tail = null
357
+ if (measureTail && cursor !== null && cursor > (previous ?? -1)) {
358
+ // Seed identities from the old prefix, then take only the new counters.
359
+ // PTC start/result and repeated request usage can straddle the timeout.
360
+ const tracker = createConsolidationMeasurement('worker', { sessionId: forkId })
361
+ const prefix = rows.filter(event => Number.isSafeInteger(event?.seq) && event.seq <= (previous ?? -1))
362
+ const added = rows.filter(event => Number.isSafeInteger(event?.seq) && event.seq > (previous ?? -1))
363
+ if (added.length === 0) return { cursor, tail: null, unavailable: true }
364
+ for (const event of prefix) tracker.observe(event)
365
+ const before = { ...tracker.measurement.observed }
366
+ for (const event of added) tracker.observe(event)
367
+ tail = tracker.measurement
368
+ for (const key of ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars', 'estimatedTokens']) {
369
+ if (tail.observed[key] !== null) tail.observed[key] -= before[key] ?? 0
370
+ }
371
+ }
372
+ return { cursor, tail }
373
+ } catch {
374
+ warn('consolidation worker event cursor unavailable; using the last measured cursor')
375
+ return { cursor: previous, tail: null, unavailable: true }
376
+ } finally {
377
+ try { lease?.[Symbol.dispose]?.() } catch {}
378
+ }
379
+ }
380
+
381
+ // —— 退役(§4.5 退役动作)———————————————————————————————————————
382
+ // 先 abort epoch 控制器(取消在跑回合)→ 等 idle(有上限)→ dispose 工具 restriction/handle
383
+ // → dispose agent → 删子绑定 → 清父绑定 workerEpoch → 活动日志记 epoch 结束。
384
+ // reason ∈ 'scope-change' | 'char-limit' | 'window-limit' | 'idle-ttl' | 'failure' | 'timeout-x2';
385
+ // scope-change / failure 不做交接(不带病工作),其余默认交接——交接包由下一窗初生时组装。
386
+ export async function retireWorker(ctx, forkId, reason, { handoff, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS } = {}) {
387
+ const agents = (() => { try { return ctx?.get?.('agents') || null } catch { return null } })()
388
+ const binding = (() => { try { return getSessionBinding(forkId) } catch { return null } })()
389
+ const epoch = binding?.workerEpoch && typeof binding.workerEpoch === 'object' ? binding.workerEpoch : null
390
+ const parentSessionId = epoch?.parentSession || binding?.parentSessionId || null
391
+ const disposables = disposablesOf(forkId)
392
+ // 0. 先取消在跑回合:epoch 控制器绑定在 agent 生命周期上(A2),abort 才能让卡住的
393
+ // 回合尽快收敛,下面的有界 whenIdle 才不会白等满时限。
394
+ try { disposables?.abort?.abort() } catch {}
395
+ // 1. 等 whenIdle(有上限):超时退役后 worker 可能还在跑上一回合的工具。
396
+ let handle = null
397
+ try { handle = agents?.get?.(forkId) || null } catch { handle = null }
398
+ await waitWorkerIdle(handle, idleWaitMs)
399
+ // 2. dispose 工具面(本模块注册表)+ agent 本体。找不到 handle(已死/已重启)就跳过,
400
+ // 剩下的清理照做——「视为已死,冷启动」(§4.5 非条件项)。
401
+ epochDisposables.delete(forkId)
402
+ try { disposables?.restriction?.dispose?.() } catch {}
403
+ try { disposables?.tools?.dispose?.() } catch {}
404
+ try { await ((handle?.agent) || handle)?.dispose?.() } catch {}
405
+ // 3. 删子绑定;turn-log 不删(§3.4:日志比 worker 活得长)。
406
+ try { deleteSessionBinding(forkId) } catch {}
407
+ // 4. 父绑定 epoch 清零(binding.workerEpoch 清零 → 下窗走初生路径)。
408
+ if (parentSessionId) {
409
+ try {
410
+ const parent = getSessionBinding(parentSessionId)
411
+ if (parent?.workerEpoch?.forkSessionId === forkId) setSessionBinding(parentSessionId, { workerEpoch: null })
412
+ } catch {}
413
+ }
414
+ // 5. 活动日志记 epoch 结束(退役是常规操作而非故障:qq-bridge 类长会话周期性到点换新,§6)。
415
+ try {
416
+ record({
417
+ kind: 'check',
418
+ scope: 'private',
419
+ sessionId: parentSessionId || forkId,
420
+ libraryId: binding?.libraryId || null,
421
+ ok: true,
422
+ message: '整理 worker 退役 · ' + String(reason || 'unknown')
423
+ + (handoff === true ? ' · 交接(下窗交接包冷启动)' : ' · 不交接')
424
+ + ' · epoch ' + (Number(epoch?.index) || '?') + ' · ' + (Number(epoch?.windows) || 0) + ' 窗 / ' + (Number(epoch?.chars) || 0) + ' 字符',
425
+ detail: { forkId, reason: reason || null, handoff: handoff === true, epoch: epoch ? { index: epoch.index, chars: epoch.chars, windows: epoch.windows } : null },
426
+ })
427
+ } catch {}
428
+ return { ok: true, forkId, reason, handoff: handoff === true, hadHandle: Boolean(handle) }
429
+ }
430
+
431
+ // —— epoch 记账 ——————————————————————————————————————————————————————
432
+ // 每窗一次:chars += 增量 + 观测到的 worker 产出(监听器顺手累计的 assistant/tool 体积);
433
+ // windows += 1;结算成功清超时计数;超时 +1(连续 2 次 → 退役,§4.4);idleAt 记
434
+ // whenIdle 完成时刻(条件 4 的 TTL 起算点)。binding 传父会话的(内部重读最新值再写,
435
+ // 避免覆盖并发的绑定补丁);子绑定里的 epoch 副本同步刷新。
436
+ export function recordEpochProgress(binding, { measurement = null, incrementChars = 0, workerOutputChars = 0, idleAt = null, settled = false, timeout = false, progress = true, countWindow = true, usageTotals = false, now = Date.now() } = {}) {
437
+ const sessionId = binding?.sessionId
438
+ if (!sessionId) return null
439
+ const current = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
440
+ const epoch = current?.workerEpoch
441
+ if (!epoch || typeof epoch !== 'object' || !epoch.forkSessionId) return null
442
+ const timeouts = Number(epoch.timeouts) || 0
443
+ const inputChars = measurement ? measurement.dispatched.inputChars : incrementChars
444
+ const outputChars = measurement
445
+ ? ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars'].reduce((sum, key) => sum + (measurement.observed[key] ?? 0), 0)
446
+ : workerOutputChars
447
+ const usage = { ...(epoch.usage || Object.fromEntries(USAGE_FIELDS.map(key => [key, null]))) }
448
+ if (progress && measurement) {
449
+ for (const key of USAGE_FIELDS) {
450
+ usage[key] = usageTotals ? measurement.usage[key]
451
+ : measurement.usage[key] === null || ((Number(epoch.windows) || 0) > 0 && usage[key] === null)
452
+ ? null : (usage[key] ?? 0) + measurement.usage[key]
453
+ }
454
+ }
455
+ const next = {
456
+ ...epoch,
457
+ chars: Math.max(0, Number(epoch.chars) || 0)
458
+ + (progress ? Math.max(0, Number(inputChars) || 0) + Math.max(0, Number(outputChars) || 0) : 0),
459
+ // Legacy callers/unknown serialization must never certify a partially measured epoch.
460
+ measurementVersion: progress ? (measurement && measurement.serializationErrors === 0 ? 2 : null) : epoch.measurementVersion,
461
+ estimatedTokens: progress
462
+ ? (!measurement || epoch.estimatedTokens === null || measurement.observed.estimatedTokens === null ? null
463
+ : (Number(epoch.estimatedTokens) || 0) + measurement.dispatched.estimatedTokens + measurement.observed.estimatedTokens)
464
+ : epoch.estimatedTokens ?? null,
465
+ usage,
466
+ lastEventSeq: measurement?.lastEventSeq ?? epoch.lastEventSeq ?? null,
467
+ lateOutputChars: (Number(epoch.lateOutputChars) || 0) + (progress && !countWindow ? outputChars : 0),
468
+ windows: (Number(epoch.windows) || 0) + (progress && countWindow ? 1 : 0),
469
+ timeouts: timeout ? timeouts + 1 : (settled ? 0 : timeouts),
470
+ lastIdleAt: idleAt ? new Date(Number(idleAt) || now).toISOString() : (epoch.lastIdleAt || null),
471
+ }
472
+ try { setSessionBinding(sessionId, { workerEpoch: next }) } catch (error) {
473
+ try { warn('worker epoch progress write failed: ' + String(error?.message || error)) } catch {}
474
+ return null
475
+ }
476
+ try {
477
+ const child = getSessionBinding(epoch.forkSessionId)
478
+ if (child) setSessionBinding(epoch.forkSessionId, { workerEpoch: next })
479
+ } catch {}
480
+ return next
481
+ }
482
+
483
+ // —— 三级试活(§4.6)———————————————————————————————————————————————
484
+ /**
485
+ * 获取或初生持久 worker。退役条件全部只在 acquire 时检查(执行中不误杀,§4.5):
486
+ * 1. scope/库/域变化 → 立即退役,无交接(上下文已污染)
487
+ * 2. 预算合格制(budgetFit)→ 换新,交接
488
+ * 3. epoch 窗口数超限 → 换新,交接
489
+ * 4. 距上一窗 idle 超 TTL → 换新,交接
490
+ * 条件 5(失败)与超时×2 是反应式退役,由 private.js 在结算失败/超时路径调用 retireWorker。
491
+ *
492
+ * 返回:
493
+ * { ok:true, forkId, handle, birth, reused, resumed, epoch, tools, restriction, epochAbort, retired, handoff }
494
+ * | { ok:false, reasonCode, error, retired? }
495
+ * handoff = 本 次 获 取 是否允许交接包语义(退役原因决定;无退役的复用窗口为 false)。
496
+ * epochAbort = 绑在 worker 生命周期上的控制器,供调用方硬停/重验时真正停住持久 worker(A2)。
497
+ */
498
+ export async function acquireWorker(ctx, binding, {
499
+ incrementChars = 0, settings = null, probe = null,
500
+ agentOptions = null, header = null, agentPreset = undefined, afterEpochIndex = 0, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS,
501
+ } = {}) {
502
+ const sessionId = binding?.sessionId
503
+ if (!sessionId) return { ok: false, reasonCode: 'no-binding', error: 'acquireWorker requires a session binding' }
504
+ const agents = ctx?.get?.('agents')
505
+ if (!agents || typeof agents.create !== 'function') {
506
+ return { ok: false, reasonCode: 'no-agents-service', error: 'host has no agents.create; the consolidation worker cannot start' }
507
+ }
508
+ const presetSelection = resolveConsolidationPreset(ctx, {
509
+ sessionId, presetId: agentPreset === undefined ? header?.agentPreset ?? null : agentPreset,
510
+ })
511
+ const presetLog = message => { try { ctx.logger?.warn?.('dsh-memu-memory: ' + message) } catch {} }
512
+ settings = settings || getSettings()
513
+ const liveBinding = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
514
+ const retired = []
515
+ let epoch = liveBinding?.workerEpoch && typeof liveBinding.workerEpoch === 'object' ? liveBinding.workerEpoch : null
516
+ const prevIndex = Math.max(Number(epoch?.index) || 0, Number(afterEpochIndex) || 0)
517
+ let handoff = true // 初生包默认带交接上下文(§5.1:初生包与 handoff 包是同一个东西)
518
+
519
+ // —— Stage A:退役条件(只在这里查)———————————————————————————————
520
+ if (epoch?.forkSessionId) {
521
+ const generation = scopeGenerationOf(liveBinding)
522
+ const budget = epochBudget(liveBinding, settings)
523
+ let reason = null
524
+ if (!epoch.scopeGeneration || epoch.scopeGeneration !== generation) reason = 'scope-change'
525
+ else if (epoch.measurementVersion !== 2) reason = 'measurement-upgrade'
526
+ else if (!epoch.mountedPreset?.confirmed) reason = 'preset-unverified'
527
+ else if (epoch.mountedPreset.presetId !== presetSelection.presetId) reason = 'preset-change'
528
+ else if (epoch.lastIdleAt && now - (Date.parse(epoch.lastIdleAt) || 0) > WORKER_EPOCH_IDLE_TTL_MS) reason = 'idle-ttl'
529
+ else if (!budgetFit(epoch, incrementChars, settings)) reason = 'char-limit'
530
+ else if ((Number(epoch.windows) || 0) >= budget.maxWindows) reason = 'window-limit'
531
+ if (reason) {
532
+ // 作用域或预设变化/来源不可证实时不交接旧人格上下文;预算与闲置换代保留交接。
533
+ const withHandoff = !['scope-change', 'preset-change', 'preset-unverified'].includes(reason)
534
+ const result = await retireWorker(ctx, epoch.forkSessionId, reason, { handoff: withHandoff, now, idleWaitMs })
535
+ retired.push({ forkId: epoch.forkSessionId, reason, handoff: withHandoff, ok: result?.ok === true })
536
+ handoff = withHandoff
537
+ epoch = null
538
+ }
539
+ }
540
+
541
+ // —— Stage B:试活(get 进程内 → resume 跨重启 → 都失败视为已死)—————————————————
542
+ // Normalize handles: host create returns a wrapper ({agent,...}), while
543
+ // agents.get 返回**裸 Agent**——复用分支若把裸 Agent 当 handle 返回,派发处的
544
+ // `handle.agent.followup` requires the wrapper; returning a bare Agent would fail.
545
+ // Normalize all acquisition sources to the create return shape.
546
+ const toHandle = (raw) => (raw ? (raw.agent != null ? raw : { agent: raw }) : null)
547
+ if (epoch?.forkSessionId) {
548
+ let handle = null
549
+ try { handle = (typeof agents.get === 'function' && toHandle(agents.get(epoch.forkSessionId))) || null } catch { handle = null }
550
+ let resumed = false
551
+ let resumeAbort = null
552
+ if (!handle && typeof agents?.resume === 'function') {
553
+ // 能力探测(任务约束):resume 不可用/抛错都跳过此级,绝不抛错。
554
+ // resume 的 signal 同样被宿主绑到 agent 生命周期(initializeAgent),作为新 epoch 的 abort。
555
+ resumeAbort = new AbortController()
556
+ try { handle = toHandle(await agents.resume({ resumeSessionId: epoch.forkSessionId, signal: resumeAbort.signal })) || null } catch { handle = null }
557
+ resumed = Boolean(handle)
558
+ }
559
+ // A persisted header cannot be repaired through create.meta on resume. Retire
560
+ // instead of changing the user's filesystem or keeping an unusable cwd.
561
+ const workerCwd = handle?.agent?.session?.header?.cwd
562
+ if (handle && typeof workerCwd === 'string' && resolveConsolidationCwd(workerCwd, null) !== workerCwd) {
563
+ try { resumeAbort?.abort() } catch {}
564
+ const result = await retireWorker(ctx, epoch.forkSessionId, 'cwd-invalid', { handoff: true, now, idleWaitMs })
565
+ retired.push({ forkId: epoch.forkSessionId, reason: 'cwd-invalid', handoff: true, ok: result?.ok === true })
566
+ handoff = true
567
+ epoch = null
568
+ handle = null
569
+ }
570
+ if (handle && resumed) {
571
+ // Resume does not promise to rerun create.setup. Reapply through the same
572
+ // public mount API, or retire when the resumed context cannot be verified.
573
+ const mounted = handle.agent.ctx || presetSelection.presetId === null
574
+ ? await presetSetupFor(ctx, { selection: presetSelection, log: presetLog })(handle.agent.ctx, handle.agent)
575
+ : null
576
+ if (!mounted?.confirmed) {
577
+ try { resumeAbort?.abort() } catch {}
578
+ const result = await retireWorker(ctx, epoch.forkSessionId, 'preset-unverified', { handoff: false, now, idleWaitMs })
579
+ retired.push({ forkId: epoch.forkSessionId, reason: 'preset-unverified', handoff: false, ok: result?.ok === true })
580
+ handoff = false
581
+ epoch = null
582
+ handle = null
583
+ } else {
584
+ epoch = { ...epoch, mountedPreset: mounted }
585
+ setSessionBinding(sessionId, { workerEpoch: epoch })
586
+ setSessionBinding(epoch.forkSessionId, { workerEpoch: epoch })
587
+ }
588
+ }
589
+ if (handle) {
590
+ let disposables = disposablesOf(epoch.forkSessionId)
591
+ if (resumed) {
592
+ // 崩溃恢复(§4.6):工具注册是进程内的,resume 回来的 worker 必须重挂读写面。
593
+ const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, epoch.forkSessionId, sessionId)
594
+ const restriction = await restrictWorkerTools(agents, epoch.forkSessionId, sessionId)
595
+ disposables = { tools, restriction, abort: resumeAbort }
596
+ epochDisposables.set(epoch.forkSessionId, disposables)
597
+ }
598
+ // 复用前必须等上一回合落地(有界)。超时废回合后 worker 可能还在跑,
599
+ // 直接发下一窗会把上一回合的 turn/end/回执/工具轮灌进本窗监听器。等到 idle 才安全;
600
+ // 等不到就是卡死——退役冷启动(宁可早换新),绝不把新回合塞进一个还在忙的 worker。
601
+ const idle = await waitWorkerIdle(handle, idleWaitMs)
602
+ if (idle) {
603
+ const eventState = await workerEventCursor(ctx, epoch.forkSessionId, epoch.lastEventSeq, (Number(epoch.windows) || 0) > 0)
604
+ if ((eventState.unavailable && (Number(epoch.timeouts) || 0) > 0) || eventState.tail?.serializationErrors > 0) {
605
+ await retireWorker(ctx, epoch.forkSessionId, 'measurement-unavailable', { handoff: true, now, idleWaitMs })
606
+ return { ok: false, reasonCode: 'worker-measurement-unavailable', retired, error: 'the late worker output could not be measured; the range stays pending for a fresh worker' }
607
+ }
608
+ if (eventState.tail) {
609
+ const measured = recordEpochProgress({ sessionId }, { measurement: eventState.tail, countWindow: false, usageTotals: true, now })
610
+ if (!measured) return { ok: false, reasonCode: 'worker-epoch-unavailable', retired, error: 'the late worker output measurement could not be persisted' }
611
+ epoch = measured
612
+ }
613
+ const optionsChanged = agentOptions && handle.agent.options && ['provider', 'model', 'reasoningEffort', 'maxTokens']
614
+ .some(key => (agentOptions[key] ?? null) !== (handle.agent.options[key] ?? null))
615
+ if (!optionsChanged) {
616
+ return {
617
+ ok: true, forkId: epoch.forkSessionId, handle,
618
+ birth: false, reused: true, resumed, epoch,
619
+ eventCursor: eventState.cursor,
620
+ tools: disposables?.tools || null, restriction: disposables?.restriction || null,
621
+ epochAbort: disposables?.abort || null,
622
+ retired, handoff: false,
623
+ }
624
+ }
625
+ const result = await retireWorker(ctx, epoch.forkSessionId, 'model-options-change', { handoff: true, now, idleWaitMs })
626
+ retired.push({ forkId: epoch.forkSessionId, reason: 'model-options-change', handoff: true, ok: result?.ok === true })
627
+ handoff = true
628
+ epoch = null
629
+ } else {
630
+ const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
631
+ retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, stuck: true, ok: result?.ok === true })
632
+ handoff = true
633
+ epoch = null
634
+ }
635
+ } else if (epoch?.forkSessionId) {
636
+ // 死亡(重启后 resume 不可用/会话被删):冷启动 + 交接包(§8);worker 会话本身没有
637
+ // 可等的回合,retire 只做清理与记账。
638
+ const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
639
+ retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, gone: true, ok: result?.ok === true })
640
+ handoff = true
641
+ epoch = null
642
+ }
643
+ }
644
+
645
+ // —— Stage C:初生(§4.1)———————————————————————————————————————————
646
+ let index = prevIndex + 1
647
+ let forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
648
+ const modelMaxContext = await probeModelMaxContext(ctx, agentOptions)
649
+ // epoch 级 abort 控制器,绑到 agent 生命周期(宿主把 create.signal 永久接到 lifetime)。
650
+ // 续窗的硬停/重验 abort 它才能真正停住持久 worker——窗口级 signal 只在出生那次被宿主接线。
651
+ const epochAbort = new AbortController()
652
+ // 无种子创建(宿主 0.2.2-rc.3 已核实 seed 可选):初生包改为第一条 followup 消息,
653
+ // worker 路径完全解除 buildForkSeed 依赖(§4.1)。
654
+ // A failed dispatch can retire the epoch while the session ID remains occupied:
655
+ // 但 dispose 只关句柄不删会话文件 → 下一窗初生用同一 forkId 被宿主拒绝
656
+ // creation with that ID then fails with already-exists.
657
+ // 撞车处理:无法证明旧上下文尺寸的孤儿保守退役,index 顺延换新 id
658
+ // (≤6 次,逐个跳过已占用的持久 id),绝不把既有上下文记成零。
659
+ let handle = null
660
+ let mountedPreset = { ...presetSelection, confirmed: false, status: 'not-run' }
661
+ for (let createAttempt = 0; createAttempt < 6; createAttempt += 1) {
662
+ let collided = false
663
+ mountedPreset = { ...presetSelection, confirmed: false, status: 'not-run' }
664
+ try {
665
+ handle = await agents.create({
666
+ sessionId: forkId,
667
+ meta: {
668
+ cwd: resolveConsolidationCwd(header?.cwd),
669
+ parentSession: sessionId,
670
+ // Without this the worker is treated as an ordinary user conversation by
671
+ // the injection path and the sidebar session lists(与 fork 同款隔离)。
672
+ origin: 'subagent',
673
+ // 同上:header 是创建事实,真正在跑的预设由调用方按事件算好传进来。
674
+ agentPreset: presetSelection.presetId,
675
+ },
676
+ agentOptions: agentOptions || undefined,
677
+ // 同上:header 只是标签,真正挂载要靠 setup(见 lib/preset-mount.js)。
678
+ setup: presetSetupFor(ctx, {
679
+ selection: presetSelection,
680
+ onResolved: result => { mountedPreset = result },
681
+ log: presetLog,
682
+ }),
683
+ signal: epochAbort.signal,
684
+ })
685
+ } catch (error) {
686
+ const message = String(error?.message || error)
687
+ if (!/already exist/i.test(message)) {
688
+ return {
689
+ ok: false, reasonCode: 'worker-create-failed', forkId, retired,
690
+ error: 'the host rejected the consolidation worker: ' + message,
691
+ }
692
+ }
693
+ collided = true
694
+ }
695
+ if (!collided) break
696
+ // An orphan's existing context is not zero-sized. Retire it conservatively;
697
+ // never adopt it with freshly reset counters or reuse its persisted id.
698
+ const result = await retireWorker(ctx, forkId, 'orphan-unmeasured', { handoff: true, now, idleWaitMs })
699
+ retired.push({ forkId, reason: 'orphan-unmeasured', handoff: true, ok: result?.ok === true })
700
+ index += 1
701
+ forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
702
+ }
703
+ if (!handle?.agent && !handle?.followup) {
704
+ return { ok: false, reasonCode: 'worker-create-failed', forkId, retired, error: 'no worker handle after bounded create attempts' }
705
+ }
706
+ handle = toHandle(handle)
707
+ // 工具面只在初生挂一次(§15.2 改动点 2);标准 preset 的名单里已有 memu_* 时不重复挂。
708
+ const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, forkId, sessionId)
709
+ const restriction = await restrictWorkerTools(agents, forkId, sessionId)
710
+ epochDisposables.set(forkId, { tools, restriction, abort: epochAbort })
711
+ const epochRecord = {
712
+ forkSessionId: forkId,
713
+ index,
714
+ birthAt: new Date(Number(now) || Date.now()).toISOString(),
715
+ chars: 0,
716
+ schemaVersion: 2,
717
+ measurementVersion: 2,
718
+ mountedPreset,
719
+ estimatedTokens: 0,
720
+ usage: Object.fromEntries(USAGE_FIELDS.map(key => [key, null])),
721
+ lastEventSeq: null,
722
+ windows: 0,
723
+ timeouts: 0,
724
+ scopeGeneration: scopeGenerationOf(liveBinding),
725
+ parentSession: sessionId,
726
+ modelMaxContext: modelMaxContext || null,
727
+ lastIdleAt: null,
728
+ }
729
+ try {
730
+ setSessionBinding(forkId, { consolidationFork: true, origin: 'subagent', workerEpoch: epochRecord })
731
+ setSessionBinding(sessionId, { workerEpoch: epochRecord })
732
+ } catch (error) {
733
+ // epoch 记账写不进去就不该继续用持久 worker:这次整理按失败回 pending,下窗重试。
734
+ try { epochAbort.abort() } catch {}
735
+ try { await ((handle?.agent) || handle)?.dispose?.() } catch {}
736
+ epochDisposables.delete(forkId)
737
+ return {
738
+ ok: false, reasonCode: 'worker-epoch-unavailable', forkId, retired,
739
+ error: 'the worker epoch could not be persisted: ' + String(error?.message || error),
740
+ }
741
+ }
742
+ return {
743
+ ok: true, forkId, handle,
744
+ birth: true, reused: false, resumed: false, epoch: epochRecord, tools, restriction,
745
+ epochAbort,
746
+ retired, handoff,
747
+ }
748
+ }
749
+
750
+ // —— 增量读取与缺口重建(§3.3)———————————————————————————————————————
751
+ /**
752
+ * 本窗增量的唯一入口:turn-log 优先,缺口 rebuildRange 补,重建失败退回现场
753
+ * condenseEvents(不写日志,本窗结算语义不变)。回合是不可分单位:返回整回合记录。
754
+ *
755
+ * 缺口按"可记录回合"判定(A3):期望记录 = 宿主事件经 buildTurnRecords 能产出的整回合;
756
+ * 心跳/纯注入回合本就不落行,它们的 seq 区间不是洞,不能拿裸 seq 全覆盖去卡——否则
757
+ * 带心跳的会话每窗都误判缺口、永远退回现场压缩。consolidationTurnLog=off 时不读不写
758
+ * 日志,直接现场压缩(A7,设计 §10.1)。
759
+ */
760
+ export function loadWorkerIncrement({ sessionId, binding = null, window = null, events = [] } = {}) {
761
+ const fromSeq = Number(window?.fromSeq)
762
+ const throughSeq = Number(window?.throughSeq)
763
+ if (!Number.isSafeInteger(fromSeq) || !Number.isSafeInteger(throughSeq) || throughSeq < fromSeq) {
764
+ return { records: [], text: '', chars: 0, source: 'empty', digest: null }
765
+ }
766
+ const eventsInWindow = (Array.isArray(events) ? events : []).filter((event) => {
767
+ const seq = Number(event?.seq)
768
+ return Number.isSafeInteger(seq) && seq >= fromSeq && seq <= throughSeq
769
+ })
770
+ const domain = binding?.domainOverride || binding?.domain || 'general'
771
+ const condenseLimits = condenseLimitsFor(domain)
772
+ const condenseFallback = (why) => {
773
+ let text = ''
774
+ try { text = condenseEvents(eventsInWindow, WORKER_INCREMENT_FALLBACK_CHARS, condenseLimits) || '' } catch { text = '' }
775
+ return { records: [], text: String(text), chars: String(text).length, source: 'fallback', digest: why }
776
+ }
777
+ // off 时不读不写日志,直接现场压缩。
778
+ let turnLogOn = true
779
+ try { turnLogOn = getSettings().consolidationTurnLog !== 'off' } catch { turnLogOn = true }
780
+ if (!turnLogOn) return condenseFallback('现场压缩(turn-log 已关闭)')
781
+
782
+ const lastSleepSeq = Number(binding?.lastSleepSeq)
783
+ const after = Number.isSafeInteger(lastSleepSeq) && lastSleepSeq >= 0 ? lastSleepSeq : -1
784
+ // 工具行额度与兜底压缩都跟随领域:编码域的修改重点在工具输出/参数里。
785
+ const limits = turnLogLimits(domain)
786
+ const expected = buildTurnRecords(eventsInWindow, limits)
787
+ const logRows = () => { try { return readIncrement(sessionId, -1).records || [] } catch { return [] } }
788
+ const covers = (rows, rec) => rows.some((row) => {
789
+ const s = Number(row?.seq?.[0])
790
+ const e = Number(row?.seq?.[1])
791
+ return Number.isSafeInteger(s) && Number.isSafeInteger(e) && s <= rec.seq[0] && e >= rec.seq[1]
792
+ })
793
+ let source = 'turn-log'
794
+ let rows = logRows()
795
+ let missing = expected.filter((rec) => !covers(rows, rec))
796
+ if (missing.length > 0) {
797
+ try { rebuildRange(sessionId, fromSeq, throughSeq, events, limits) } catch {}
798
+ rows = logRows()
799
+ missing = expected.filter((rec) => !covers(rows, rec))
800
+ if (missing.length > 0) return condenseFallback('现场压缩(turn-log 缺口重建失败)')
801
+ source = 'rebuilt'
802
+ } else if (expected.length === 0 && eventsInWindow.length > 0) {
803
+ // 没有可记录的闭合回合、日志也没覆盖:可能是开回合/裸转录,现场压缩兜底,
804
+ // 避免把有内容的区间喂成空增量。
805
+ const inWindow = rows.filter((row) => {
806
+ const s = Number(row?.seq?.[0])
807
+ const e = Number(row?.seq?.[1])
808
+ return Number.isSafeInteger(s) && Number.isSafeInteger(e) && e > after && s <= throughSeq
809
+ })
810
+ if (inWindow.length === 0) return condenseFallback('现场压缩(无可记录回合)')
811
+ }
812
+ // 增量 = 尚未完整结算的整回合(seqEnd > lastSleepSeq)且起点在本窗内。窗口已在
813
+ // worker 模式对齐到整回合边界(A5),正常不会有跨骑记录;此处仍按整回合过滤兜底。
814
+ const records = rows.filter((row) => {
815
+ const start = Number(row?.seq?.[0])
816
+ const end = Number(row?.seq?.[1])
817
+ return Number.isSafeInteger(start) && Number.isSafeInteger(end) && end > after && start <= throughSeq
818
+ })
819
+ const text = records.map((row) => JSON.stringify(row)).join('\n')
820
+ const first = records.length > 0 ? Number(records[0]?.seq?.[0]) : null
821
+ const last = records.length > 0 ? Number(records[records.length - 1]?.seq?.[1]) : null
822
+ const digest = records.length > 0
823
+ ? `${records.length} 回合 · seq ${first}–${last}${source === 'rebuilt' ? ' · 缺口重建' : ''}`
824
+ : null
825
+ return { records, text, chars: text.length, source, digest }
826
+ }
827
+
828
+ // —— 包组装(§4.2 续窗增量包 / §5.1 初生·交接包)——————————————————————————
829
+
830
+ const PENDING_OPEN = '--- 待处理回合 ---'
831
+ const PENDING_CLOSE = '--- 结束 ---'
832
+ const TAIL_OPEN = '--- 已结算参考(勿为其写新记忆,只处理待处理区间)---'
833
+ const TAIL_CLOSE = '--- 已结算参考结束 ---'
834
+
835
+ function renderRecords(records) {
836
+ return (Array.isArray(records) ? records : []).map((row) => JSON.stringify(row)).join('\n')
837
+ }
838
+
839
+ function pendingNoteLine(pendingNote, pendingHash) {
840
+ if (!pendingNote) return ''
841
+ if (typeof pendingNote === 'string' && pendingNote.trim()) return pendingNote
842
+ const prefix = typeof pendingHash === 'string' && pendingHash ? `(${pendingHash.slice(0, 12)}…)` : ''
843
+ return `[上窗未结算${prefix}] 上一窗${prefix}未结算完成:先核对库内是否已写入,勿重复写;本包与上一窗是同一段待处理区间的重发,重复写入会被去重拦下,但请先核对再动手。`
844
+ }
845
+
846
+ function catalogTextOf(catalog) {
847
+ if (!catalog) return ''
848
+ if (typeof catalog === 'string') return catalog.trim()
849
+ const blocks = Array.isArray(catalog?.data?.content) ? catalog.data.content : []
850
+ return blocks.map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : '')).filter(Boolean).join('\n').trim()
851
+ }
852
+
853
+ function catalogIdsOf(catalogText) {
854
+ const ids = new Set()
855
+ for (const match of String(catalogText || '').matchAll(/^- \[([^\]\n]+)\]/gm)) ids.add(match[1])
856
+ return ids
857
+ }
858
+
859
+ /** 必写候选(续窗包):顺延候选 ≤4、总数 ≤8 的双闸在这里再兜一道(mergeMustCover 同语义)。 */
860
+ function renderCarry(rows, { max = 8, carriedMax = 4 } = {}) {
861
+ const list = Array.isArray(rows) ? rows : []
862
+ if (list.length === 0) return ''
863
+ const lines = ['[必写候选(先写这些;每条都必须落库,或在失败说明里写明为什么不写,不得静默跳过)]']
864
+ let carried = 0
865
+ let shown = 0
866
+ for (const row of list) {
867
+ if (shown >= Math.max(1, Number(max) || 8)) break
868
+ const isCarried = row?.carried === true
869
+ if (isCarried && carried >= Math.max(0, Number(carriedMax) || 0)) continue
870
+ if (isCarried) carried += 1
871
+ shown += 1
872
+ const where = isCarried
873
+ ? '顺延' + (row?.observedAt ? ' · 事件时间 ' + row.observedAt : '')
874
+ : '第 ' + (Number.isSafeInteger(Number(row?.fromSeq)) ? row.fromSeq : '?') + '–'
875
+ + (Number.isSafeInteger(Number(row?.throughSeq)) ? row.throughSeq : '?') + ' 条'
876
+ + (row?.tag ? ' · ' + row.tag : '') + (row?.observedAt ? ' · 事件时间 ' + row.observedAt : '')
877
+ lines.push(`${shown}. [${where}] ${String(row?.text || '').slice(0, 120)}`)
878
+ }
879
+ return lines.length > 1 ? lines.join('\n') : ''
880
+ }
881
+
882
+ function sceneTimeLine(sceneTime) {
883
+ const value = typeof sceneTime === 'string' ? sceneTime.trim() : ''
884
+ if (!value) return ''
885
+ return `[场景时间] ${value}(时间锚点:observed_at 与今天/明天/下周X 等相对日期按这个场景时间推算,不要用真实时钟。)`
886
+ }
887
+
888
+ /**
889
+ * 已写入摘要(§4.2/§5.2):账本 recordOperation 历史 → 最近 20 条 id+标题 +
890
+ * 「另有 M 条均已在库」,与目录头按 id 去重。摘要只是省无效写入的成本优化,
891
+ * 不是正确性防线(铁律 1:对账与库级去重兜底)。
892
+ */
893
+ function writtenSummary(sessionId, binding, { writtenRows = null, writtenTotal = null, catalogIds = new Set(), limit = 20 } = {}) {
894
+ let ids = []
895
+ let total = null
896
+ if (Array.isArray(writtenRows)) {
897
+ ids = writtenRows.map((row) => String(row?.id || '')).filter(Boolean)
898
+ total = Number.isSafeInteger(Number(writtenTotal)) ? Number(writtenTotal) : ids.length
899
+ } else {
900
+ let ops = []
901
+ try { ops = Object.values(loadLedger().sessions?.[String(sessionId || '')]?.operations || {}) } catch { ops = [] }
902
+ for (const op of ops.slice().sort((a, b) => String(b?.at || '').localeCompare(String(a?.at || '')))) {
903
+ for (const id of Array.isArray(op?.ids) ? op.ids : []) {
904
+ const key = String(id || '')
905
+ if (key && !ids.includes(key)) ids.push(key)
906
+ }
907
+ }
908
+ total = ids.length
909
+ }
910
+ const deduped = ids.filter((id) => !catalogIds.has(id))
911
+ const shown = deduped.slice(0, Math.max(1, Number(limit) || 20))
912
+ if (shown.length === 0) return ''
913
+ const titles = new Map()
914
+ if (Array.isArray(writtenRows)) {
915
+ for (const row of writtenRows) titles.set(String(row?.id || ''), String(row?.title || '(untitled)').slice(0, 80))
916
+ } else {
917
+ try {
918
+ const entries = loadPrivateIndex(binding?.libraryId)?.entries || {}
919
+ for (const id of shown) titles.set(id, String(entries[id]?.title || '(untitled)').slice(0, 80))
920
+ } catch { /* 索引缺失只降级标题,摘要照发 */ }
921
+ }
922
+ const lines = ['[已写入摘要(账本记录,防重复写;目录里已有的不再列出)]']
923
+ for (const id of shown) lines.push(`- [${id}] ${titles.get(id) || '(untitled)'}`)
924
+ const rest = Math.max(0, (Number(total) || deduped.length) - shown.length)
925
+ if (rest > 0) lines.push(`另有 ${rest} 条均已在库。`)
926
+ return lines.join('\n')
927
+ }
928
+
929
+ /** 交接尾部(§5.2):tailSlice 整回合取尾,再滤掉未结算段(seqEnd ≤ lastSleepSeq)。 */
930
+ function tailSection(sessionId, { lastSleepSeq = null, tailChars = WORKER_HANDOFF_TAIL_CHARS } = {}) {
931
+ const ceiling = Number.isSafeInteger(Number(lastSleepSeq)) && Number(lastSleepSeq) >= 0 ? Number(lastSleepSeq) : null
932
+ // 没有结算游标 = 整份日志都是未结算增量,没有「已结算参考」可带(尾部会与增量整段重复)。
933
+ if (ceiling === null) return ''
934
+ let slice = null
935
+ try { slice = tailSlice(sessionId, tailChars) } catch { return '' }
936
+ const records = (Array.isArray(slice?.records) ? slice.records : []).filter((row) => {
937
+ const end = Number(row?.seq?.[1])
938
+ return Number.isSafeInteger(end) && end <= ceiling
939
+ })
940
+ if (records.length === 0) return ''
941
+ return [TAIL_OPEN, renderRecords(records), TAIL_CLOSE].join('\n')
942
+ }
943
+
944
+ /**
945
+ * 续窗增量包(§4.2):分隔标记夹住的待处理回合 + 目录头(每窗都发)+ 必写候选
946
+ * (顺延 ≤4)+ 回执契约 + 场景时间(每窗重读)。已写入摘要不发(worker 上下文里
947
+ * 刚写过,续窗发是冗余);上一窗未结算时开头带核对说明(§4.4)。
948
+ */
949
+ export function buildIncrementPack({
950
+ binding = null, incrementRecords = [], incrementText = null, catalog = null,
951
+ digest = null, carry = [], contract = '', sceneTime = null,
952
+ pendingNote = false, pendingHash = null, carryMax = 4,
953
+ } = {}) {
954
+ const sections = []
955
+ const note = pendingNoteLine(pendingNote, pendingHash)
956
+ if (note) sections.push(note)
957
+ if (digest) sections.push('[待处理增量] ' + String(digest))
958
+ sections.push(PENDING_OPEN)
959
+ const body = (typeof incrementText === 'string' && incrementText.trim()) ? incrementText : renderRecords(incrementRecords)
960
+ sections.push(body || '(本窗没有可读的回合记录)')
961
+ sections.push(PENDING_CLOSE)
962
+ const catalogText = catalogTextOf(catalog)
963
+ if (catalogText) sections.push(catalogText)
964
+ const carryText = renderCarry(carry, { carriedMax: carryMax })
965
+ if (carryText) sections.push(carryText)
966
+ if (typeof contract === 'string' && contract.trim()) sections.push(contract)
967
+ const sceneLine = sceneTimeLine(sceneTime)
968
+ if (sceneLine) sections.push(sceneLine)
969
+ return sections.join('\n')
970
+ }
971
+
972
+ /**
973
+ * 初生包 = 交接包(§5.1):身份/规则任务书(buildWorkerBrief,必写候选随它下发)+
974
+ * 待处理回合 + 库目录头 + 已写入摘要(最近 20 条 + 计数,与目录去重)+ turn-log 尾部
975
+ * (标注「已结算参考」,滤掉未结算段)+ 场景时间。退役原因 scope-change / failure 时
976
+ * 由调用方传 includeTail: false / writtenRows: []——「不做 handoff」= 不带旧 epoch 的
977
+ * 连续性材料,身份与目录照发。
978
+ */
979
+ export function buildHandoffPack({
980
+ sessionId = null, binding = null, snapshot = null, probe = null, jobId = null,
981
+ reason = 'auto', singleOnly = false, mustCover = [], contract = '', domain = 'general',
982
+ incrementRecords = [], incrementText = null, digest = null,
983
+ catalog = null, sceneTime = null, pendingNote = false, pendingHash = null,
984
+ writtenRows = null, writtenTotal = null,
985
+ lastSleepSeq = null, tailChars = WORKER_HANDOFF_TAIL_CHARS, includeTail = true,
986
+ } = {}) {
987
+ const brief = buildWorkerBrief({ snapshot, probe, contract, reason, jobId, mustCover, autoReceipt: true, singleOnly, domain })
988
+ const sections = [brief]
989
+ const note = pendingNoteLine(pendingNote, pendingHash)
990
+ if (note) sections.push(note)
991
+ if (digest) sections.push('[待处理增量] ' + String(digest))
992
+ sections.push(PENDING_OPEN)
993
+ const body = (typeof incrementText === 'string' && incrementText.trim()) ? incrementText : renderRecords(incrementRecords)
994
+ sections.push(body || '(本窗没有可读的回合记录)')
995
+ sections.push(PENDING_CLOSE)
996
+ const catalogText = catalogTextOf(catalog)
997
+ if (catalogText) sections.push(catalogText)
998
+ const summary = writtenSummary(sessionId, binding, { writtenRows, writtenTotal, catalogIds: catalogIdsOf(catalogText) })
999
+ if (summary) sections.push(summary)
1000
+ if (includeTail !== false && sessionId) {
1001
+ const tail = tailSection(sessionId, { lastSleepSeq, tailChars })
1002
+ if (tail) sections.push(tail)
1003
+ }
1004
+ const sceneLine = sceneTimeLine(sceneTime)
1005
+ if (sceneLine) sections.push(sceneLine)
1006
+ return sections.join('\n')
1007
+ }
1008
+
1009
+ export default {
1010
+ WORKER_EPOCH_TIERS, WORKER_OUTPUT_FACTOR, WORKER_EPOCH_IDLE_TTL_MS, WORKER_HANDOFF_TAIL_CHARS,
1011
+ WORKER_TIMEOUT_LIMIT, WORKER_RETIRE_IDLE_WAIT_MS, WORKER_INCREMENT_FALLBACK_CHARS,
1012
+ epochBudget, budgetFit, packetBudgetFit, measurePacket, createConsolidationMeasurement,
1013
+ resolveConsolidationCwd, probeModelMaxContext, attachWorkerTools, restrictWorkerTools,
1014
+ retireWorker, recordEpochProgress, acquireWorker, loadWorkerIncrement, buildIncrementPack, buildHandoffPack,
1015
+ }