dsh-memu-memory 1.4.2 → 1.4.4
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.
- package/AGENTS.md +108 -110
- package/CHANGELOG.md +173 -868
- package/LICENSE +21 -21
- package/README.md +368 -374
- package/README.zh.md +354 -360
- package/assets/icon.svg +7 -7
- package/cordis.patch.yml +8 -8
- package/docs/active-memory-ab.md +279 -385
- package/docs/binding-lifecycle.md +99 -99
- package/docs/client-conventions.md +75 -75
- package/docs/contributing.md +217 -217
- package/docs/emotion-model-spec.md +247 -281
- package/docs/env-and-commands.md +149 -152
- package/docs/host-adaptation.md +339 -360
- package/docs/host-api.md +131 -137
- package/docs/host-versions.md +117 -120
- package/docs/mcp-porting.md +146 -146
- package/docs/memory-semantics.md +271 -259
- package/docs/pending-work.md +44 -51
- package/docs/troubleshooting.md +909 -854
- package/lib/active-memory.js +160 -165
- package/lib/activity-log.js +207 -207
- package/lib/auto-link/apply.js +248 -249
- package/lib/auto-link/candidates.js +163 -163
- package/lib/auto-link/decide.js +300 -300
- package/lib/auto-link/normalize.js +99 -99
- package/lib/auto-link/policy.js +42 -42
- package/lib/auto-link/suppression.js +101 -101
- package/lib/auto-link/terminology.js +311 -311
- package/lib/backup.js +1254 -1254
- package/lib/binding-diagnostics.js +634 -634
- package/lib/budget.js +118 -118
- package/lib/client.js +9820 -9751
- package/lib/commitment.js +178 -138
- package/lib/consolidation-ledger.js +434 -438
- package/lib/consolidation-receipt.js +386 -387
- package/lib/consolidation-snapshot.js +420 -405
- package/lib/consolidation-worker.js +240 -241
- package/lib/context.js +33 -33
- package/lib/curator-evidence.js +131 -131
- package/lib/curator-policy.js +198 -202
- package/lib/curator.js +1813 -1811
- package/lib/cycle.js +524 -513
- package/lib/diagnostics.js +524 -524
- package/lib/embedding-catalog.js +1051 -1055
- package/lib/embedding-download.js +637 -607
- package/lib/embedding-runtime.js +946 -946
- package/lib/engine.js +1103 -1103
- package/lib/entity-repair.js +285 -285
- package/lib/environment-check.js +394 -394
- package/lib/fork-model.js +312 -312
- package/lib/freshness.js +128 -121
- package/lib/global-graph.js +389 -389
- package/lib/graph.js +1193 -1193
- package/lib/host-surface.js +30 -30
- package/lib/inbound.js +284 -281
- package/lib/index.js +506 -511
- package/lib/inject.js +2639 -2619
- package/lib/lexicon-scope.js +143 -143
- package/lib/lexicon.js +1183 -1192
- package/lib/lifecycle-audit.js +37 -0
- package/lib/local-embedding-entry.js +145 -145
- package/lib/local-embedding-manager.js +306 -306
- package/lib/local-embedding-protocol.js +210 -210
- package/lib/local-embedding-worker.js +682 -682
- package/lib/local-vector-service.js +506 -453
- package/lib/maintenance-ledger.js +138 -0
- package/lib/maintenance-review.js +103 -0
- package/lib/maintenance-runner.js +267 -0
- package/lib/managed-runtime.js +118 -118
- package/lib/media.js +607 -513
- package/lib/memory.js +5035 -4941
- package/lib/memu-config.js +213 -213
- package/lib/memu.js +565 -565
- package/lib/migrate.js +200 -200
- package/lib/mood.js +300 -300
- package/lib/paths.js +453 -457
- package/lib/port-surface.js +82 -82
- package/lib/preset-mount.js +85 -0
- package/lib/preset-scope.js +126 -126
- package/lib/private-links.js +567 -567
- package/lib/private.js +2198 -2209
- package/lib/prompts/global-curator.md +135 -135
- package/lib/prompts/image-caption.md +1 -1
- package/lib/prompts/private-consolidation.coding.md +39 -39
- package/lib/prompts/private-consolidation.md +32 -32
- package/lib/prompts/private-consolidation.mixed.md +37 -37
- package/lib/prompts/private-consolidation.rp.md +47 -47
- package/lib/prompts/private-policy.coding.md +35 -35
- package/lib/prompts/private-policy.md +36 -36
- package/lib/prompts/private-policy.mixed.md +29 -29
- package/lib/prompts/private-policy.rp.md +43 -43
- package/lib/prompts/system-guide.coding.md +20 -20
- package/lib/prompts/system-guide.md +25 -25
- package/lib/prompts/system-guide.mixed.md +22 -22
- package/lib/prompts/system-guide.rp.md +23 -23
- package/lib/prompts.js +331 -331
- package/lib/recall-cache.js +212 -212
- package/lib/remote-summary.js +123 -123
- package/lib/rpc.js +2531 -2532
- package/lib/salient-wake.js +438 -438
- package/lib/snippet.js +125 -125
- package/lib/state.js +1948 -1928
- package/lib/stats.js +236 -236
- package/lib/temporal.js +345 -348
- package/lib/text-retrieval.js +992 -1001
- package/lib/text-similarity.js +305 -305
- package/lib/tokenizer-v2.js +271 -271
- package/lib/tools.js +1098 -1091
- package/lib/turn-log.js +545 -545
- package/lib/vector-migration.js +928 -930
- package/lib/vector-profile.js +1353 -1359
- package/lib/visibility.js +59 -59
- package/lib/webui/graph-LICENSE.txt +1 -1
- package/lib/webui/graph-view.bundle.js +2 -2
- package/lib/webui/graph-view.js +1171 -1175
- package/lib/webui/mark.svg +7 -7
- package/lib/webui/standalone.css +1178 -1178
- package/lib/webui/standalone.js +238 -238
- package/lib/webui.js +136 -136
- package/lib/worker-pool.js +1020 -979
- package/package.json +153 -153
- package/requirements.lock +34 -34
- package/scripts/acceptance-local.mjs +946 -946
- package/scripts/active-memory-ab-live.mjs +653 -655
- package/scripts/active-memory-ab.mjs +1302 -1302
- package/scripts/audit-memory-lifecycle.mjs +55 -0
- package/scripts/bench-recall.mjs +142 -142
- package/scripts/build-graph.mjs +44 -45
- package/scripts/chain-matrix.mjs +541 -541
- package/scripts/check-all.mjs +68 -74
- package/scripts/check-doc-drift.mjs +547 -547
- package/scripts/check-graph-browser.mjs +261 -261
- package/scripts/check-i18n.mjs +81 -83
- package/scripts/check-idle-compositing.mjs +61 -61
- package/scripts/check-seed-compat.mjs +115 -118
- package/scripts/check-text-format.mjs +55 -0
- package/scripts/curator-pair-calibrate.mjs +259 -259
- package/scripts/diagnose-bindings.mjs +176 -176
- package/scripts/drive-session.mjs +863 -864
- package/scripts/engine-smoke.mjs +69 -69
- package/scripts/entity-dedupe.mjs +110 -110
- package/scripts/lexicon-calibrate.mjs +230 -230
- package/scripts/lexicon-dedupe.mjs +318 -318
- package/scripts/local-runtime-install.mjs +142 -142
- package/scripts/local-runtime-verify.mjs +56 -56
- package/scripts/local-vector-verify.mjs +93 -93
- package/scripts/make-readme-shots.mjs +59 -59
- package/scripts/migrate-visibility.mjs +94 -94
- package/scripts/mock-llm.mjs +938 -903
- package/scripts/preview.mjs +58 -58
- package/scripts/prune-sessions.mjs +31 -34
- package/scripts/prune-turnlogs.mjs +29 -30
- package/scripts/prune-vectors.mjs +24 -24
- package/scripts/rebuild-auto-links.mjs +252 -252
- package/scripts/recall-bench.mjs +820 -820
- package/scripts/repetition-ab-scenarios.mjs +93 -93
- package/scripts/repetition-detector-snapshot.mjs +314 -314
- package/scripts/repetition-eval-live.mjs +360 -360
- package/scripts/repetition-eval.mjs +702 -702
- package/scripts/replay.mjs +705 -575
- package/scripts/setup.mjs +46 -46
- package/scripts/simulate-injection.mjs +299 -301
- package/tests/absorb-review.test.mjs +354 -354
- package/tests/activation.test.mjs +89 -89
- package/tests/active-memory-ab.test.mjs +745 -745
- package/tests/active-memory.test.mjs +129 -129
- package/tests/activity-log.test.mjs +126 -126
- package/tests/activity-wiring.test.mjs +155 -155
- package/tests/appendix-b.test.mjs +217 -217
- package/tests/appendix-b2.test.mjs +166 -166
- package/tests/audit-batch3.test.mjs +247 -247
- package/tests/audit-regression.test.mjs +275 -275
- package/tests/audit-safety.test.mjs +227 -227
- package/tests/auto-link-candidates.test.mjs +245 -245
- package/tests/auto-link-decide.test.mjs +512 -512
- package/tests/auto-link-migration.test.mjs +133 -133
- package/tests/backend-compensation.test.mjs +272 -272
- package/tests/backup.test.mjs +793 -793
- package/tests/binding-diagnostics.test.mjs +720 -720
- package/tests/browser.test.mjs +476 -476
- package/tests/client-export.test.mjs +521 -521
- package/tests/client-render.test.mjs +2008 -1728
- package/tests/coalesce.test.mjs +113 -113
- package/tests/commitment.test.mjs +243 -144
- package/tests/config.test.mjs +159 -159
- package/tests/consolidation-credential.test.mjs +330 -330
- package/tests/consolidation-feed.test.mjs +122 -122
- package/tests/consolidation-fork.test.mjs +1587 -1539
- package/tests/consolidation-ledger.test.mjs +389 -389
- package/tests/consolidation-snapshot.test.mjs +567 -505
- package/tests/consolidation-value.test.mjs +89 -89
- package/tests/context-scope.test.mjs +40 -40
- package/tests/cross-library-recall.test.mjs +269 -269
- package/tests/cue.test.mjs +58 -58
- package/tests/curator-absorb.test.mjs +444 -444
- package/tests/curator-calibrate.test.mjs +173 -173
- package/tests/curator-clusters.test.mjs +306 -306
- package/tests/curator-commit.test.mjs +325 -325
- package/tests/curator-contract.test.mjs +191 -191
- package/tests/curator-evidence.test.mjs +102 -102
- package/tests/curator-link.test.mjs +317 -317
- package/tests/curator-pairing.test.mjs +339 -339
- package/tests/curator-probe.test.mjs +490 -490
- package/tests/curator-review-mode.test.mjs +315 -315
- package/tests/curator.test.mjs +152 -152
- package/tests/cycle.test.mjs +567 -568
- package/tests/diagnostics.test.mjs +278 -278
- package/tests/disclosure.test.mjs +249 -249
- package/tests/doc-drift.test.mjs +342 -342
- package/tests/drive-session.test.mjs +152 -152
- package/tests/dynamic-rrf.test.mjs +182 -182
- package/tests/dynamic-threshold.test.mjs +52 -52
- package/tests/embedding-catalog.test.mjs +374 -374
- package/tests/embedding-download.test.mjs +529 -486
- package/tests/embedding-runtime.test.mjs +449 -449
- package/tests/emotion-chain.test.mjs +84 -84
- package/tests/emotion-contract.test.mjs +445 -445
- package/tests/engine.test.mjs +108 -108
- package/tests/entity-merge.test.mjs +278 -278
- package/tests/environment-check.test.mjs +187 -187
- package/tests/fact-version.test.mjs +146 -146
- package/tests/fixtures/active-memory-ab/README.md +56 -56
- package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
- package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
- package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
- package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
- package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
- package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
- package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
- package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
- package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
- package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
- package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
- package/tests/fixtures/active-memory-ab/manifest.json +199 -199
- package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
- package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
- package/tests/fixtures/lexicon-stub.mjs +284 -284
- package/tests/fixtures/mock-llm/reply.txt +1 -1
- package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
- package/tests/fixtures/recall-bench/02-exact.json +152 -152
- package/tests/fixtures/recall-bench/03-negation.json +172 -172
- package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
- package/tests/fixtures/recall-bench/05-conflict.json +193 -193
- package/tests/fixtures/recall-bench/06-boundary.json +272 -272
- package/tests/fixtures/recall-bench/07-secret.json +190 -190
- package/tests/fixtures/recall-bench/08-coding.json +163 -163
- package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
- package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
- package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
- package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
- package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
- package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
- package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
- package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
- package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
- package/tests/fixtures/repetition-eval/02-en.json +96 -96
- package/tests/fixtures/repetition-eval/03-code.json +90 -90
- package/tests/fixtures/repetition-eval/04-names.json +115 -115
- package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
- package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
- package/tests/fixtures/tokenizer-cases.mjs +27 -27
- package/tests/fork-model.test.mjs +345 -345
- package/tests/freshness.test.mjs +140 -140
- package/tests/global-graph.test.mjs +106 -106
- package/tests/global-lifecycle.test.mjs +149 -149
- package/tests/graph-cascade.test.mjs +363 -363
- package/tests/graph-view.test.mjs +414 -414
- package/tests/graph.test.mjs +371 -371
- package/tests/help-page.test.mjs +416 -416
- package/tests/hook-order.test.mjs +72 -72
- package/tests/humanlike.test.mjs +232 -232
- package/tests/hybrid-recall.test.mjs +610 -610
- package/tests/inbound.test.mjs +441 -441
- package/tests/inject-conflict.test.mjs +173 -173
- package/tests/inject-guide.test.mjs +513 -513
- package/tests/inject.test.mjs +384 -384
- package/tests/injection-budget-settings.test.mjs +35 -35
- package/tests/injection-budget.test.mjs +165 -165
- package/tests/injection-chain.test.mjs +442 -442
- package/tests/injection-intent-budget.test.mjs +92 -92
- package/tests/injection-rollback.test.mjs +428 -428
- package/tests/issue2-chain.test.mjs +169 -169
- package/tests/lexical-bm25.test.mjs +171 -171
- package/tests/lexicon-calibrate.test.mjs +48 -48
- package/tests/lexicon-dedupe.test.mjs +171 -171
- package/tests/lexicon-frequency.test.mjs +195 -195
- package/tests/lexicon-inject.test.mjs +459 -459
- package/tests/lexicon-perf.test.mjs +464 -464
- package/tests/lexicon-scope.test.mjs +256 -256
- package/tests/lexicon-ui.test.mjs +667 -667
- package/tests/lexicon.test.mjs +922 -922
- package/tests/lifecycle-audit.test.mjs +56 -0
- package/tests/loader-register.mjs +3 -3
- package/tests/loader.mjs +17 -17
- package/tests/local-embedding-entry.test.mjs +95 -95
- package/tests/local-embedding-env.test.mjs +51 -51
- package/tests/local-embedding-manager.test.mjs +494 -494
- package/tests/local-embedding-protocol.test.mjs +121 -121
- package/tests/local-embedding-worker.test.mjs +440 -440
- package/tests/local-vector-service.test.mjs +41 -0
- package/tests/maintenance-status.test.mjs +77 -0
- package/tests/maintenance.test.mjs +438 -0
- package/tests/managed-memory.test.mjs +1234 -1234
- package/tests/managed-runtime.test.mjs +72 -72
- package/tests/media-injection.test.mjs +225 -0
- package/tests/media.test.mjs +135 -135
- package/tests/memory-chain.test.mjs +169 -169
- package/tests/memory-fields.test.mjs +134 -134
- package/tests/memu-resident-route.test.mjs +130 -130
- package/tests/memu-resident.test.mjs +33 -33
- package/tests/migration-payload.test.mjs +40 -42
- package/tests/mock-llm.test.mjs +263 -225
- package/tests/mood.test.mjs +109 -109
- package/tests/multiprocess.test.mjs +29 -29
- package/tests/negation-polarity.test.mjs +135 -135
- package/tests/new-session-gate.test.mjs +617 -617
- package/tests/open-loop-date.test.mjs +416 -416
- package/tests/ops-hardening.test.mjs +209 -209
- package/tests/package-shipping.test.mjs +88 -88
- package/tests/pending-injection.test.mjs +107 -107
- package/tests/port-surface.test.mjs +138 -138
- package/tests/preset-mount.test.mjs +132 -0
- package/tests/preset-scope.test.mjs +212 -212
- package/tests/private-links.test.mjs +493 -493
- package/tests/prompt-semantics.test.mjs +51 -51
- package/tests/prompts.test.mjs +315 -315
- package/tests/query-decompose.test.mjs +62 -62
- package/tests/react-snapshot.test.mjs +24 -24
- package/tests/recall-bench.test.mjs +317 -317
- package/tests/recall-cache.test.mjs +292 -292
- package/tests/recall-corpus-eligibility.test.mjs +51 -51
- package/tests/recall-dedup.test.mjs +446 -446
- package/tests/recall-intent.test.mjs +172 -172
- package/tests/regression-sweep.test.mjs +311 -311
- package/tests/reminder-fairness.test.mjs +55 -0
- package/tests/remote.test.mjs +140 -140
- package/tests/rename.test.mjs +30 -30
- package/tests/repetition-detector-snapshot.test.mjs +231 -231
- package/tests/repetition-eval-live.test.mjs +177 -177
- package/tests/repetition-eval.test.mjs +373 -373
- package/tests/salience-domain.test.mjs +173 -173
- package/tests/salient-date.test.mjs +142 -142
- package/tests/salient-wake.test.mjs +389 -389
- package/tests/settings-beat.test.mjs +222 -222
- package/tests/settings-coverage.test.mjs +97 -97
- package/tests/settings-plumbing.test.mjs +79 -79
- package/tests/short-term.test.mjs +182 -166
- package/tests/sidebar-beat.test.mjs +213 -213
- package/tests/sidebar-refresh.test.mjs +123 -123
- package/tests/sidebar.test.mjs +102 -74
- package/tests/simulate-injection.test.mjs +76 -76
- package/tests/slot-similarity.test.mjs +153 -153
- package/tests/snippet.test.mjs +79 -79
- package/tests/source-kind.test.mjs +52 -52
- package/tests/speaker-provenance.test.mjs +120 -120
- package/tests/stale-maintenance.test.mjs +206 -131
- package/tests/state-gc.test.mjs +34 -34
- package/tests/state.test.mjs +155 -155
- package/tests/stats.test.mjs +112 -112
- package/tests/storage.test.mjs +125 -125
- package/tests/stubs/child-process-spy.mjs +14 -14
- package/tests/stubs/dsh-llm-pi-ai.js +13 -13
- package/tests/stubs/dsh-llm.js +5 -5
- package/tests/stubs/dsh-schedule.js +140 -140
- package/tests/stubs/dsh-session-query.js +26 -26
- package/tests/stubs/dsh-session.js +7 -7
- package/tests/stubs/dsh-tools.js +101 -101
- package/tests/temporal-repair.test.mjs +78 -0
- package/tests/temporal.test.mjs +124 -124
- package/tests/text-format.test.mjs +24 -0
- package/tests/tokenizer-v2.test.mjs +142 -142
- package/tests/tool-schema.test.mjs +126 -126
- package/tests/tools.test.mjs +810 -810
- package/tests/turn-log.test.mjs +487 -487
- package/tests/ui-defaults.test.mjs +57 -57
- package/tests/update-fields.test.mjs +138 -138
- package/tests/vector-gc.test.mjs +37 -37
- package/tests/vector-migration.test.mjs +810 -810
- package/tests/vector-profile.test.mjs +449 -449
- package/tests/visibility-migration.test.mjs +152 -152
- package/tests/webui-auth.test.mjs +963 -963
- package/tests/webui.test.mjs +421 -421
- package/tests/windows-env.test.mjs +89 -89
- package/tests/worker-lifecycle.test.mjs +1522 -1429
package/lib/private.js
CHANGED
|
@@ -1,2209 +1,2198 @@
|
|
|
1
|
-
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
2
|
-
import crypto from 'node:crypto'
|
|
3
|
-
import fs from 'node:fs'
|
|
4
|
-
import path from 'node:path'
|
|
5
|
-
import { getSessionBinding, getLibrary, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex, effectiveScope } from './state.js'
|
|
6
|
-
import { domainOf, privateRemember, isMemoryEligible, visibleToSession, overdueOpenCommitments } from './memory.js'
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
// the
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
.
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
.
|
|
51
|
-
.
|
|
52
|
-
|
|
53
|
-
return
|
|
54
|
-
|
|
55
|
-
'
|
|
56
|
-
'
|
|
57
|
-
'
|
|
58
|
-
'
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
//
|
|
111
|
-
//
|
|
112
|
-
//
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
//
|
|
116
|
-
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
//
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
if (
|
|
128
|
-
return
|
|
129
|
-
|
|
130
|
-
.
|
|
131
|
-
.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
let
|
|
146
|
-
let
|
|
147
|
-
let
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
if (
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
//
|
|
180
|
-
//
|
|
181
|
-
// tail, compact
|
|
182
|
-
|
|
183
|
-
export const
|
|
184
|
-
|
|
185
|
-
//
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
//
|
|
189
|
-
//
|
|
190
|
-
//
|
|
191
|
-
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
//
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
const
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
if (
|
|
246
|
-
if (block.type === '
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
//
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
//
|
|
302
|
-
//
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
const
|
|
321
|
-
const
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|| startIdx
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
*
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
* the
|
|
349
|
-
*
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if (
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
message
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
//
|
|
383
|
-
//
|
|
384
|
-
//
|
|
385
|
-
//
|
|
386
|
-
//
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
const
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
//
|
|
425
|
-
//
|
|
426
|
-
//
|
|
427
|
-
//
|
|
428
|
-
//
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
//
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
'
|
|
441
|
-
'
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
]
|
|
445
|
-
const
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
]
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
]
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
const
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
if (
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
if (
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
const
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
const
|
|
561
|
-
if (
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
.
|
|
565
|
-
.
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
.
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
const
|
|
625
|
-
|
|
626
|
-
if (
|
|
627
|
-
const
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
const
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
const
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
.filter((
|
|
660
|
-
.
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
if (
|
|
718
|
-
const
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
const
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
.
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
const
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
if (!
|
|
820
|
-
const
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
.
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
const
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
//
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
const
|
|
924
|
-
|
|
925
|
-
const
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
detail: {
|
|
968
|
-
})
|
|
969
|
-
return
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
const
|
|
1020
|
-
if (
|
|
1021
|
-
} catch {}
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
//
|
|
1083
|
-
//
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
} from './
|
|
1092
|
-
import {
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
} catch {}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
//
|
|
1186
|
-
//
|
|
1187
|
-
//
|
|
1188
|
-
//
|
|
1189
|
-
|
|
1190
|
-
//
|
|
1191
|
-
//
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
function
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
export function
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
:
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
//
|
|
1385
|
-
//
|
|
1386
|
-
const
|
|
1387
|
-
if (!
|
|
1388
|
-
|
|
1389
|
-
ok:
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
starved,
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
const
|
|
1517
|
-
const
|
|
1518
|
-
//
|
|
1519
|
-
|
|
1520
|
-
//
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
const
|
|
1535
|
-
const
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
}
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
//
|
|
1623
|
-
//
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
}
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
//
|
|
1641
|
-
//
|
|
1642
|
-
const
|
|
1643
|
-
let
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
workerAcquired
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
}
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
//
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
//
|
|
1975
|
-
//
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
//
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
safeLedger(() => failJob({ sessionId, jobId, reasonCode
|
|
2024
|
-
return finish({
|
|
2025
|
-
ok: false,
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
//
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
decision
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
}
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
// worker
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
//
|
|
2099
|
-
//
|
|
2100
|
-
const
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
//
|
|
2128
|
-
//
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
} else {
|
|
2200
|
-
try { await stopWorker() } catch {}
|
|
2201
|
-
try { workerTools?.dispose?.() } catch {}
|
|
2202
|
-
try { workerRestriction?.dispose?.() } catch {}
|
|
2203
|
-
try { if (childId) deleteSessionBinding(childId) } catch {}
|
|
2204
|
-
}
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
export function isConsolidating(sessionId) {
|
|
2208
|
-
return inFlight.has(sessionId)
|
|
2209
|
-
}
|
|
1
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
2
|
+
import crypto from 'node:crypto'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { getSessionBinding, getLibrary, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex, effectiveScope } from './state.js'
|
|
6
|
+
import { domainOf, privateRemember, isMemoryEligible, visibleToSession, overdueOpenCommitments } from './memory.js'
|
|
7
|
+
import { presetSetupFor, resolveConsolidationPreset } from './preset-mount.js'
|
|
8
|
+
import { loadPromptForDomain, CONSOLIDATION_CONTRACTS } from './prompts.js'
|
|
9
|
+
import { summarizeRemote } from './remote-summary.js'
|
|
10
|
+
import { condenseEvents, condenseLimitsFor, readSessionSnapshot } from './curator.js'
|
|
11
|
+
import { record } from './activity-log.js'
|
|
12
|
+
import { ACTIVE_MEMORY_POLICY, assessWake, collectEvidence } from './active-memory.js'
|
|
13
|
+
import { entryFingerprint } from './consolidation-receipt.js'
|
|
14
|
+
import { DEFAULT_TIME_ZONE } from './temporal.js'
|
|
15
|
+
|
|
16
|
+
// The consolidation worker only sees the transcript as text. Without a visible
|
|
17
|
+
// per-turn clock it falls back to the wall clock (or a single batch sceneTime),
|
|
18
|
+
// which is exactly how "前天" gets written months away from the scene. The seed
|
|
19
|
+
// event keeps the replayed logical time; surface it as a leading text block so
|
|
20
|
+
// the worker can pass that turn's observed_at to the write tools.
|
|
21
|
+
function eventTimeLabel(event) {
|
|
22
|
+
const explicit = event?.data?.sceneTime
|
|
23
|
+
const at = explicit ? new Date(explicit) : (Number.isFinite(event?.time) ? new Date(event.time) : null)
|
|
24
|
+
if (!at || !Number.isFinite(at.getTime())) return null
|
|
25
|
+
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
26
|
+
timeZone: DEFAULT_TIME_ZONE,
|
|
27
|
+
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
28
|
+
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
29
|
+
}).formatToParts(at)
|
|
30
|
+
const pick = (type) => parts.find((part) => part.type === type)?.value || ''
|
|
31
|
+
return `${pick('year')}-${pick('month')}-${pick('day')} ${pick('hour')}:${pick('minute')}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Short-term entries expire on a clock, so the idle pass is the last moment anyone
|
|
35
|
+
// can decide what they were worth. The list is generated in code rather than added
|
|
36
|
+
// to the editable prompt body: it is per-library data plus a protocol (which tool
|
|
37
|
+
// call means "promote"), and a user editing the template must not be able to break
|
|
38
|
+
// the tool names the model is told to use.
|
|
39
|
+
export function shortTermBrief(binding, { now = Date.now() } = {}) {
|
|
40
|
+
if (!binding?.libraryId || binding.useLibrary === false) return ''
|
|
41
|
+
let index = null
|
|
42
|
+
try { index = loadPrivateIndex(binding.libraryId) } catch { return '' }
|
|
43
|
+
const rows = Object.entries(index.entries || {})
|
|
44
|
+
.filter(([, e]) => e && e.layer === 'short_term' && isMemoryEligible(e, { automatic: true, now }) && visibleToSession(e, binding.sessionId))
|
|
45
|
+
.map(([id, e]) => ({
|
|
46
|
+
id,
|
|
47
|
+
title: e.title || '(untitled)',
|
|
48
|
+
left: Math.max(0, Math.round(((Date.parse(e.expiresAt || '') || 0) - now) / 3_600_000)),
|
|
49
|
+
}))
|
|
50
|
+
.filter((row) => row.left > 0)
|
|
51
|
+
.sort((a, b) => a.left - b.left)
|
|
52
|
+
.slice(0, 20)
|
|
53
|
+
if (rows.length === 0) return ''
|
|
54
|
+
return [
|
|
55
|
+
'[short_term · 快到期了]',
|
|
56
|
+
'下面这些是你近期记下的短期条目,到期会自己消失。逐条决定:',
|
|
57
|
+
'值得留下的升级 —— memu_private_update id=<id> layer=long_term(要补充的正文这次一并写上);',
|
|
58
|
+
'不重要的归档 —— memu_private_update id=<id> status=archived;',
|
|
59
|
+
'还说不清的别动,它自己会过期。',
|
|
60
|
+
...rows.map((row) => `- [${row.id}] ${row.title} · 约 ${row.left} 小时后过期`),
|
|
61
|
+
].join('\n')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function buildPrivateConsolidationPrompt(sessionId) {
|
|
65
|
+
const binding = getSessionBinding(sessionId)
|
|
66
|
+
const library = binding?.libraryId ? getLibrary(binding.libraryId) : null
|
|
67
|
+
const settings = getSettings()
|
|
68
|
+
// One shared body for both backends; only the output contract differs.
|
|
69
|
+
return [
|
|
70
|
+
loadPromptForDomain('private-consolidation', {
|
|
71
|
+
libraryName: library ? `${library.name} (${library.id})` : '(unbound)',
|
|
72
|
+
domain: domainOf(binding),
|
|
73
|
+
mustRememberCap: settings.mustRememberCap,
|
|
74
|
+
shortTermTtlHours: settings.shortTermTtlHours ?? 72,
|
|
75
|
+
}, domainOf(binding)).text,
|
|
76
|
+
'',
|
|
77
|
+
CONSOLIDATION_CONTRACTS.local,
|
|
78
|
+
shortTermBrief({ ...binding, sessionId }),
|
|
79
|
+
].filter((part) => part && part.trim()).join('\n')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 一句话说清一个失败原因。
|
|
84
|
+
*
|
|
85
|
+
* 早先这里只写 "... failed" 就返回:诊断页照着这条去查什么也查不到,等于把
|
|
86
|
+
* 报错留在原地。带上 code + message,诊断记录本身就有可复制的证据。
|
|
87
|
+
*/
|
|
88
|
+
function describeError(error) {
|
|
89
|
+
if (!error) return 'unknown error'
|
|
90
|
+
const code = typeof error.code === 'string' ? error.code : ''
|
|
91
|
+
const message = String(error.message || error)
|
|
92
|
+
return code && !message.startsWith(code) ? code + ': ' + message : message
|
|
93
|
+
}
|
|
94
|
+
function noticeMessage(text, summary) {
|
|
95
|
+
return createUserMessage({
|
|
96
|
+
content: [{ type: 'text', text }],
|
|
97
|
+
source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary },
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// "There were new turns" is not the same question as "there is something worth
|
|
102
|
+
// keeping". A conversation of greetings, acknowledgements and one-line lookups costs
|
|
103
|
+
// a fork (a whole seeded transcript, one model turn) and returns nothing; doing that
|
|
104
|
+
// after every idle window is how an automatic pass becomes noise the user turns off.
|
|
105
|
+
// This answers the cheap half of the question locally, before a fork exists: is the
|
|
106
|
+
// part of the transcript since the last consolidation substantive at all? It has to
|
|
107
|
+
// err on the side of running — a false "worth it" costs one model turn, a false
|
|
108
|
+
// "skip" silently throws away the only record of a decision — so the bar is low and
|
|
109
|
+
// deliberately structural rather than semantic: a single short human message with no
|
|
110
|
+
// tool work in it is the only thing it refuses.
|
|
111
|
+
// The gate this replaces counted characters. That was wrong in the one direction
|
|
112
|
+
// that matters: "我不吃香菜" is five characters and is exactly the kind of durable
|
|
113
|
+
// fact the library exists to keep, while "好的,继续" is also short and is worth
|
|
114
|
+
// nothing. Length is not the signal — an acknowledgement is. So this is a shape
|
|
115
|
+
// match on the *only* message in the tail, not a size test, and anything that is not
|
|
116
|
+
// literally an acknowledgement goes to the fork and lets the prompt decide.
|
|
117
|
+
const SMALL_TALK = /^(谢(谢|了)?|多谢|感谢|好(的|吧|嘞)?|ok|okay|收到|明白(了)?|了解(了)?|嗯+|哦+|啊+|行|可以|没问题|继续|你好|hi|hello|hey|thanks?(you)?|thx)+$/i
|
|
118
|
+
const ASSESS_MIN_HUMAN_CHARS = 4
|
|
119
|
+
|
|
120
|
+
function isSmallTalk(text) {
|
|
121
|
+
// Punctuation and spacing are not content: "好的,继续" is one acknowledgement, not
|
|
122
|
+
// two words with a comma in the middle.
|
|
123
|
+
return SMALL_TALK.test(String(text || '').replace(/[\s!!。.,,、~~👍]/g, ''))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function textOfContent(content) {
|
|
127
|
+
if (typeof content === 'string') return content.trim()
|
|
128
|
+
if (!Array.isArray(content)) return ''
|
|
129
|
+
return content
|
|
130
|
+
.map((block) => (block && typeof block === 'object' && typeof block.text === 'string' ? block.text : ''))
|
|
131
|
+
.join(' ')
|
|
132
|
+
.trim()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Only the events after the last consolidation: a session that has been asleep once
|
|
136
|
+
// already keeps all of its old material in the transcript, and scoring the whole file
|
|
137
|
+
// again would make every later turn "worth it" forever.
|
|
138
|
+
export function unconsolidatedEvents(binding, events) {
|
|
139
|
+
const since = Number(binding?.lastSleepSeq)
|
|
140
|
+
if (!Number.isFinite(since) || since < 0) return Array.isArray(events) ? events : []
|
|
141
|
+
return (events || []).filter((event) => Number(event?.seq) > since)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function assessConsolidationValue(events) {
|
|
145
|
+
let humanTurns = 0
|
|
146
|
+
let humanChars = 0
|
|
147
|
+
let humanText = ''
|
|
148
|
+
let toolCalls = 0
|
|
149
|
+
for (const event of events || []) {
|
|
150
|
+
if (event?.type === 'user/message') {
|
|
151
|
+
// The same rule the transcript condenser uses: only a message the person
|
|
152
|
+
// actually typed counts. Plugin notices, tool output and heartbeats all arrive
|
|
153
|
+
// as messages too, and none of them is a reason to spend a fork.
|
|
154
|
+
if (event.data?.source?.kind !== 'user') continue
|
|
155
|
+
const text = textOfContent(event.data?.content)
|
|
156
|
+
if (!text) continue
|
|
157
|
+
humanTurns += 1
|
|
158
|
+
humanChars += text.length
|
|
159
|
+
humanText = text
|
|
160
|
+
continue
|
|
161
|
+
}
|
|
162
|
+
if (event?.type === 'assistant/message') {
|
|
163
|
+
const blocks = event.data?.message?.content
|
|
164
|
+
if (Array.isArray(blocks)) toolCalls += blocks.filter((block) => block?.type === 'tool-call').length
|
|
165
|
+
continue
|
|
166
|
+
}
|
|
167
|
+
if (event?.type === 'tool/call') toolCalls += 1
|
|
168
|
+
}
|
|
169
|
+
const facts = { humanTurns, humanChars, toolCalls }
|
|
170
|
+
if (humanTurns === 0) return { worth: false, reason: 'no-human-turn', ...facts }
|
|
171
|
+
if (toolCalls === 0 && humanTurns === 1 && (isSmallTalk(humanText) || humanChars < ASSESS_MIN_HUMAN_CHARS)) {
|
|
172
|
+
return { worth: false, reason: 'small-talk', ...facts }
|
|
173
|
+
}
|
|
174
|
+
return { worth: true, reason: 'substantive', ...facts }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---- incremental consolidation window --------------------------------------
|
|
178
|
+
// A consolidation fork used to seed the whole transcript up to the snapshot cut,
|
|
179
|
+
// so every run re-read the same old tool logs and the model's attention spread
|
|
180
|
+
// Forks may reread prior context as conversations grow. Keep each fork bounded: seed
|
|
181
|
+
// only the unconsolidated tail, compact noise, and leave the remaining range for the
|
|
182
|
+
// next window.
|
|
183
|
+
export const CONSOLIDATION_BACKLOG_EVENTS = 200
|
|
184
|
+
export const CONSOLIDATION_BACKLOG_TURNS = 10
|
|
185
|
+
// 小增量顺延:非手动整理时,少于 3 个真人回合的增量先不 fork。它不推进游标,
|
|
186
|
+
// 下一次触发会把顺延的事件一起带上;上限仍由上面的水位常量兜底,饥饿时放行。
|
|
187
|
+
export const CONSOLIDATION_MIN_HUMAN_TURNS = 3
|
|
188
|
+
// Use a 500-event window and a 600-second budget so slower reasoning can complete a
|
|
189
|
+
// window without reducing its scope. Unprocessed events remain pending; retry windows
|
|
190
|
+
// use 250 events.
|
|
191
|
+
export const CONSOLIDATION_WINDOW_EVENTS = 500
|
|
192
|
+
// worker 模式按回合扩展窗口:500 事件切在回合中间时,向后补到该回合的 turn/end。
|
|
193
|
+
// worker 的包是 turn-log 记录(单条最多 4000 字符),扩展窗口不会放大模型上下文;
|
|
194
|
+
// 它只避免同一回合被连续两窗整条重发。20k 事件是防御上限,正常回合远小于它。
|
|
195
|
+
export const WORKER_WINDOW_EXTEND_EVENTS = 20_000
|
|
196
|
+
export const CONSOLIDATION_PROBE_MINUTES = 15
|
|
197
|
+
export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
|
|
198
|
+
// 冻结冷却(issue #4 缺陷 1):同一快照失败到上限后熔断——但熔断不该是永久锁死。
|
|
199
|
+
// 外部条件可能恢复(归档被解除、服务商恢复、effortRefusal 自愈),冷却到期后清零
|
|
200
|
+
// 连击、放行一次真实重试;仍失败则按上限重新冻结并重新计时。每个冷却期最多
|
|
201
|
+
// LIMIT 次真实 fork,成本有界。
|
|
202
|
+
export const CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS = 6 * 60 * 60 * 1000
|
|
203
|
+
const SEED_TOOL_RESULT_CHARS = 1_100
|
|
204
|
+
const SEED_TOOL_CALL_CHARS = 500
|
|
205
|
+
// 编码域的修改重点就在工具结果与调用参数(diff、错误签名、编译输出)里;
|
|
206
|
+
// 1.1k/0.5k 只够留下开头。放宽后整窗仍有 ≤500 事件与 12k 文本/条的上限兜着。
|
|
207
|
+
const SEED_TOOL_RESULT_CHARS_CODING = 2_200
|
|
208
|
+
const SEED_TOOL_CALL_CHARS_CODING = 1_000
|
|
209
|
+
const SEED_TEXT_CHARS = 12_000
|
|
210
|
+
const SEED_CATALOG_ENTRIES = 18
|
|
211
|
+
|
|
212
|
+
export function seedLimitsFor(domain) {
|
|
213
|
+
return String(domain) === 'coding'
|
|
214
|
+
? { toolResultChars: SEED_TOOL_RESULT_CHARS_CODING, toolCallChars: SEED_TOOL_CALL_CHARS_CODING }
|
|
215
|
+
: { toolResultChars: SEED_TOOL_RESULT_CHARS, toolCallChars: SEED_TOOL_CALL_CHARS }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Types that carry conversation, plus the structural events a seeded Session
|
|
219
|
+
// replays. Everything else is host bookkeeping: request headers, permissions,
|
|
220
|
+
// runtime snapshots and the plugin's own recall messages. Feeding those to the
|
|
221
|
+
// summarizer is how a memory ends up citing its own earlier injection as a user
|
|
222
|
+
// fact, so they never enter the seed.
|
|
223
|
+
const SEED_EVENT_TYPES = new Set([
|
|
224
|
+
'user/message', 'assistant/message', 'tool/call', 'tool/result',
|
|
225
|
+
'turn/start', 'turn/end', 'step/start', 'step/end',
|
|
226
|
+
])
|
|
227
|
+
|
|
228
|
+
// The subset that joins the host's model-visible surface: every one of these
|
|
229
|
+
// must carry a surfaceOp marker, and their seqs form the fold a replacement cites.
|
|
230
|
+
const SEED_SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result'])
|
|
231
|
+
|
|
232
|
+
function capSeedText(value, limit = SEED_TEXT_CHARS) {
|
|
233
|
+
const text = String(value ?? '')
|
|
234
|
+
return text.length > limit ? text.slice(0, limit) + '…[已截断]' : text
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function cloneSeedBlocks(blocks, caps = {}, seenToolText = null) {
|
|
238
|
+
const textCap = Number(caps.text) > 0 ? Number(caps.text) : SEED_TEXT_CHARS
|
|
239
|
+
const toolCap = Number(caps.tool) > 0 ? Number(caps.tool) : SEED_TOOL_CALL_CHARS
|
|
240
|
+
const out = []
|
|
241
|
+
for (const block of Array.isArray(blocks) ? blocks : []) {
|
|
242
|
+
if (!block || typeof block !== 'object') continue
|
|
243
|
+
if (block.type === 'reasoning') continue
|
|
244
|
+
if (block.type === 'image') { out.push({ type: 'text', text: '[图片/附件]' }); continue }
|
|
245
|
+
if (block.type !== 'text' && block.type !== 'tool-call') { out.push(block); continue }
|
|
246
|
+
if (block.type === 'tool-call') {
|
|
247
|
+
out.push({ ...block, arguments: capSeedText(block.arguments, toolCap) })
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
const text = String(block.text || '')
|
|
251
|
+
// Role cards, emoji catalogs and full unread snapshots repeat verbatim across
|
|
252
|
+
// turns; one copy is enough to summarise what the tool returned.
|
|
253
|
+
if (seenToolText && text && seenToolText.has(text)) {
|
|
254
|
+
out.push({ ...block, text: '[与前面相同的工具输出,已省略]' })
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
257
|
+
if (seenToolText && text) seenToolText.add(text)
|
|
258
|
+
out.push({ ...block, text: capSeedText(text, textCap) })
|
|
259
|
+
}
|
|
260
|
+
return out
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Renumber survivors and rewrite every citation to its final index. A replace
|
|
264
|
+
// whose endpoints did not survive cannot be replayed at all; report it so the
|
|
265
|
+
// caller drops it before seqs are handed out (dropping after renumbering is what
|
|
266
|
+
// left holes the host rejected with "seed event at index N has seq M").
|
|
267
|
+
function buildSeedEvents(pending, offset) {
|
|
268
|
+
const index = new Map()
|
|
269
|
+
pending.forEach((event, i) => index.set(Number(event.seq), i + offset))
|
|
270
|
+
const prepared = []
|
|
271
|
+
const origins = []
|
|
272
|
+
let dropped = false
|
|
273
|
+
pending.forEach((event, origin) => {
|
|
274
|
+
const next = { ...event, seq: index.get(Number(event.seq)) }
|
|
275
|
+
if (Array.isArray(next.sourceEventSeqs)) {
|
|
276
|
+
const mapped = [...new Set(next.sourceEventSeqs
|
|
277
|
+
.map(value => index.get(Number(value)))
|
|
278
|
+
.filter(value => Number.isInteger(value) && value < next.seq))]
|
|
279
|
+
.sort((a, b) => a - b)
|
|
280
|
+
if (mapped.length) next.sourceEventSeqs = mapped
|
|
281
|
+
else delete next.sourceEventSeqs
|
|
282
|
+
}
|
|
283
|
+
if (next.surfaceOp && typeof next.surfaceOp === 'object' && !Array.isArray(next.surfaceOp)) {
|
|
284
|
+
const start = index.get(Number(next.surfaceOp.startSeq))
|
|
285
|
+
const end = index.get(Number(next.surfaceOp.endSeq))
|
|
286
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start > end || !Array.isArray(next.sourceEventSeqs)) {
|
|
287
|
+
dropped = true
|
|
288
|
+
return
|
|
289
|
+
}
|
|
290
|
+
next.surfaceOp = { op: 'replace', startSeq: start, endSeq: end }
|
|
291
|
+
}
|
|
292
|
+
prepared.push(next)
|
|
293
|
+
origins.push(origin)
|
|
294
|
+
})
|
|
295
|
+
return { prepared, origins, dropped }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Mirror the host's surface-fold checks (session `validateNext`) over a candidate
|
|
299
|
+
// seed. A replacement is only accepted when both endpoints are current nodes and
|
|
300
|
+
// sourceEventSeqs cite every node the range shadows — dropping a replacement can
|
|
301
|
+
// reveal nodes it had shadowed, which is why this must run on the whole seed and
|
|
302
|
+
// not just the event being rewritten. Returns the prepared indices that failed.
|
|
303
|
+
function seedSurfaceIssues(events) {
|
|
304
|
+
const nodes = []
|
|
305
|
+
const issues = []
|
|
306
|
+
events.forEach((event, index) => {
|
|
307
|
+
if (!SEED_SURFACE_TYPES.has(event.type)) return
|
|
308
|
+
const op = event.surfaceOp
|
|
309
|
+
if (op === 'append') {
|
|
310
|
+
nodes.push(event.seq)
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
if (!op || typeof op !== 'object' || Array.isArray(op) || op.op !== 'replace') {
|
|
314
|
+
issues.push(index)
|
|
315
|
+
return
|
|
316
|
+
}
|
|
317
|
+
const startSeq = Number(op.startSeq)
|
|
318
|
+
const endSeq = Number(op.endSeq)
|
|
319
|
+
const startIdx = nodes.indexOf(startSeq)
|
|
320
|
+
const endIdx = nodes.indexOf(endSeq)
|
|
321
|
+
const sources = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
|
|
322
|
+
const cited = new Set(sources)
|
|
323
|
+
if (startSeq >= event.seq || endSeq >= event.seq
|
|
324
|
+
|| startIdx < 0 || endIdx < startIdx
|
|
325
|
+
|| sources.length === 0 || sources.length !== cited.size
|
|
326
|
+
|| sources.some(seq => Number(seq) >= event.seq)
|
|
327
|
+
|| nodes.slice(startIdx, endIdx + 1).some(seq => !cited.has(seq))) {
|
|
328
|
+
issues.push(index)
|
|
329
|
+
return
|
|
330
|
+
}
|
|
331
|
+
nodes.splice(startIdx, endIdx - startIdx + 1)
|
|
332
|
+
nodes.push(event.seq)
|
|
333
|
+
})
|
|
334
|
+
return issues
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Build the seed body for one window: only conversation events, with reasoning /
|
|
339
|
+
* replay state / repeated tool output removed, then renumbered seq 0..n so
|
|
340
|
+
* Session's "contiguous from zero" rule holds. The optional catalog event takes
|
|
341
|
+
* seq 0 and is the only synthetic message.
|
|
342
|
+
*
|
|
343
|
+
* Surface replacements are not append-only: their surfaceOp cites the range they
|
|
344
|
+
* shadow, and the host validates those citations while replaying the seed. When
|
|
345
|
+
* the noise filter drops neighbours (or the window starts inside a compacted
|
|
346
|
+
* range), an unremapped startSeq/endSeq points forward or at a node the seed no
|
|
347
|
+
* longer contains and the whole fork is refused. Resolve every replacement
|
|
348
|
+
* against the surviving events, drop the ones that cannot be replayed, and only
|
|
349
|
+
* renumber once the survivor set is stable.
|
|
350
|
+
*/
|
|
351
|
+
export function compactSeedEvents(events, prelude = null, options = {}) {
|
|
352
|
+
const toolResultChars = Number(options.toolResultChars) > 0 ? Number(options.toolResultChars) : SEED_TOOL_RESULT_CHARS
|
|
353
|
+
const toolCallChars = Number(options.toolCallChars) > 0 ? Number(options.toolCallChars) : SEED_TOOL_CALL_CHARS
|
|
354
|
+
const preludeEvents = (Array.isArray(prelude) ? prelude : (prelude ? [prelude] : []))
|
|
355
|
+
.filter((event) => event && typeof event === 'object')
|
|
356
|
+
.map((event, index) => {
|
|
357
|
+
// Preludes are synthetic and sit at the head, so they can only append: a
|
|
358
|
+
// replacement marker there would cite positions that do not exist yet. The
|
|
359
|
+
// host also refuses a surface-eligible event without a marker at all.
|
|
360
|
+
const surfaceOp = SEED_SURFACE_TYPES.has(event.type) ? 'append' : event.surfaceOp
|
|
361
|
+
return { ...event, seq: index, surfaceOp }
|
|
362
|
+
})
|
|
363
|
+
const offset = preludeEvents.length
|
|
364
|
+
const kept = []
|
|
365
|
+
const seenToolText = new Set()
|
|
366
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
367
|
+
if (!event || typeof event !== 'object' || !SEED_EVENT_TYPES.has(event.type)) continue
|
|
368
|
+
if (event.type === 'user/message' && event.data?.source?.kind !== 'user') continue
|
|
369
|
+
const clone = { ...event, data: { ...(event.data || {}) } }
|
|
370
|
+
if (event.type === 'assistant/message') {
|
|
371
|
+
const message = { ...(event.data?.message || {}) }
|
|
372
|
+
const source = { ...(message.source || {}) }
|
|
373
|
+
// The replay state duplicates the response body; it is not conversation.
|
|
374
|
+
delete source.replayState
|
|
375
|
+
message.source = source
|
|
376
|
+
message.content = cloneSeedBlocks(message.content, { text: SEED_TEXT_CHARS, tool: toolCallChars })
|
|
377
|
+
if (message.content.length === 0) message.content = [{ type: 'text', text: '(本轮没有可读的正文)' }]
|
|
378
|
+
clone.data.message = message
|
|
379
|
+
// data.stream is the raw chunk log, not the message the model saw. It must
|
|
380
|
+
// stay present as an (empty) array: DSH 0.2.2-rc.1's seed validation
|
|
381
|
+
// (assertAssistantSettlementShape) requires data.stream to be an array, and
|
|
382
|
+
// deleting it made every consolidation fork seed fail with "invalid
|
|
383
|
+
// settlement fields". An empty array keeps the noise-down intent — the
|
|
384
|
+
// chunks never enter the seed — while satisfying the newer host check;
|
|
385
|
+
// older hosts don't validate the field at all, so this is inert there.
|
|
386
|
+
// Keep an empty array to satisfy the host's assistant-settlement validation.
|
|
387
|
+
clone.data.stream = []
|
|
388
|
+
} else if (event.type === 'tool/result') {
|
|
389
|
+
const message = { ...(event.data?.message || {}) }
|
|
390
|
+
message.content = cloneSeedBlocks(message.content, { text: toolResultChars, tool: toolCallChars }, seenToolText)
|
|
391
|
+
if (message.content.length === 0) message.content = [{ type: 'text', text: '[空工具输出]' }]
|
|
392
|
+
clone.data.message = message
|
|
393
|
+
} else if (event.type === 'tool/call') {
|
|
394
|
+
clone.data.arguments = capSeedText(event.data?.arguments, toolCallChars)
|
|
395
|
+
} else if (event.type === 'user/message') {
|
|
396
|
+
clone.data.content = cloneSeedBlocks(event.data?.content, { text: SEED_TEXT_CHARS })
|
|
397
|
+
const timeLabel = eventTimeLabel(event)
|
|
398
|
+
if (timeLabel) clone.data.content.unshift({ type: 'text', text: `[事件时间 ${timeLabel}]` })
|
|
399
|
+
}
|
|
400
|
+
// Legacy logs can omit the marker; the host refuses a
|
|
401
|
+
// surface-eligible event without one, and inside a seed it can only append.
|
|
402
|
+
if (clone.surfaceOp === undefined && SEED_SURFACE_TYPES.has(clone.type)) clone.surfaceOp = 'append'
|
|
403
|
+
kept.push(clone)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
let pending = kept
|
|
407
|
+
for (;;) {
|
|
408
|
+
const { prepared, origins, dropped } = buildSeedEvents(pending, offset)
|
|
409
|
+
const issues = seedSurfaceIssues([...preludeEvents, ...prepared])
|
|
410
|
+
if (!dropped && issues.length === 0) return [...preludeEvents, ...prepared]
|
|
411
|
+
// Each pass removes at least one event, so this converges; two passes cover
|
|
412
|
+
// the replacement-cites-a-replacement case the host rejects first.
|
|
413
|
+
const survivors = new Set(origins)
|
|
414
|
+
const doomed = new Set()
|
|
415
|
+
pending.forEach((_, origin) => { if (!survivors.has(origin)) doomed.add(origin) })
|
|
416
|
+
for (const index of issues) doomed.add(origins[index - offset])
|
|
417
|
+
pending = pending.filter((_, origin) => !doomed.has(origin))
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// A zero-token local filter prioritizes turns likely to produce durable memories.
|
|
422
|
+
// Strong signals (dates, promises, corrections, identities) count double; generic
|
|
423
|
+
// preference and social words count once. Keep whole turns with adjacent context. If
|
|
424
|
+
// nothing stands out, keep the full window rather than silently dropping it.
|
|
425
|
+
//
|
|
426
|
+
// Select strength terms by domainOf(binding), with unknown domains falling back to
|
|
427
|
+
// general. Keep CJK substring matching and use case-insensitive word boundaries for
|
|
428
|
+
// Latin terms. Preserve score weights: strong signals count double, weak signals once.
|
|
429
|
+
const latin = (words) => words.map((word) => `\\b(?:${word})\\b`)
|
|
430
|
+
|
|
431
|
+
// 生活/中性对话:现状全域表逐字保留(顺序不变,保证中文得分与旧代码一致)+ 英文补充。
|
|
432
|
+
const GENERAL_STRONG = [
|
|
433
|
+
'今天', '明天', '昨天', '前天', '后天', '大后天', '下周', '上周', '这周', '月底', '月初', '年初', '年底',
|
|
434
|
+
'生日', '纪念日', '周年', '星期[一二三四五六日天]', '周[一二三四五六日天]',
|
|
435
|
+
'\\d{1,2}\\s*[月日号]', '\\d{4}\\s*[-/年]', '\\d{1,2}\\s*[点时]',
|
|
436
|
+
'答应', '约定', '说好', '提醒', '帮我', '帮忙', '欠', '借', '还', '截止', '到期', '记得', '别忘', '改口', '说错', '更正', '其实', '矛盾', '两版', '之前说',
|
|
437
|
+
...latin(['birthday', 'anniversary', 'promised?', 'deadline', 'due', 'owe', 'borrowed', 'changed my mind', 'corrected', 'actually']),
|
|
438
|
+
]
|
|
439
|
+
const GENERAL_WEAK = [
|
|
440
|
+
'喜欢', '讨厌', '不吃', '不要', '不能', '不想', '边界', '秘密', '别说', '打算', '计划', '准备', '要去', '想去', '叫', '称呼', '名字', '岁', '住', '工作', '职业', '负责', '接手', '登记', '换', '孩子', '父亲', '母亲', '老公', '老婆', '朋友', '同事', '邻居',
|
|
441
|
+
...latin(['prefers?', 'allergic', "can['’]t eat", 'boundaries?', 'secrets?', 'plans?', 'planned', 'called', 'named', 'ages?', 'lives at', 'works at', 'friends?', 'colleagues?']),
|
|
442
|
+
]
|
|
443
|
+
// 剧情人际:现状表即 rp 向(沿用 general 的生活词 + 现有人际词),补剧情词与英文同人词。
|
|
444
|
+
const RP_STRONG = [...GENERAL_STRONG]
|
|
445
|
+
const RP_WEAK = [
|
|
446
|
+
...GENERAL_WEAK,
|
|
447
|
+
'上位', '下位', '设定', '世界观', '剧情', '人设',
|
|
448
|
+
...latin(['personas?', 'canon', 'lore', 'headcanons?', 'backstory', 'in character', 'out of character']),
|
|
449
|
+
]
|
|
450
|
+
// 工程事实(新表):改了什么/为什么/什么时候上线。bugs 与截止日来自 §6.1 设计表。
|
|
451
|
+
const CODING_STRONG = [
|
|
452
|
+
'修复', '修好', '发布', '上线', '部署', '版本', '回滚', '迁移', '破坏性', '依赖升级', '环境变量', '报错', '崩溃', '回归', '截止日',
|
|
453
|
+
...latin([
|
|
454
|
+
'bugs?', 'fixed', 'fixes', 'fix\\b(?!ture|ing)', 'broke', 'broken', 'deploy(?:ed|s|ing)?', 'release[ds]?',
|
|
455
|
+
'shipped?', 'hotfix(?:es|ed)?', 'rollback(?:ed|s)?', 'migrat(?:e|ed|ion|ing)s?', 'breaking changes?', 'root causes?', 'crash(?:ed|es)?', 'regressions?',
|
|
456
|
+
]),
|
|
457
|
+
]
|
|
458
|
+
const CODING_WEAK = [
|
|
459
|
+
'重构', '优化', '测试', '文档', '依赖', '配置', '接口', '日志', '构建', '打包', '命名',
|
|
460
|
+
...latin(['refactor(?:ed|s|ing)?', 'optimiz(?:e|ed|ing)', 'config(?:s|uration)?', 'env', 'dependenc(?:y|ies)', 'builds?', 'lints?', 'rename[ds]?', 'apis?']),
|
|
461
|
+
]
|
|
462
|
+
// mixed:rp ∪ coding 并集去重。
|
|
463
|
+
const MIXED_STRONG = [...new Set([...RP_STRONG, ...CODING_STRONG])]
|
|
464
|
+
const MIXED_WEAK = [...new Set([...RP_WEAK, ...CODING_WEAK])]
|
|
465
|
+
const compileSalience = (parts) => new RegExp(parts.join('|'), 'gi')
|
|
466
|
+
const SALIENCE_TABLE = {
|
|
467
|
+
general: { strong: compileSalience(GENERAL_STRONG), weak: compileSalience(GENERAL_WEAK) },
|
|
468
|
+
rp: { strong: compileSalience(RP_STRONG), weak: compileSalience(RP_WEAK) },
|
|
469
|
+
coding: { strong: compileSalience(CODING_STRONG), weak: compileSalience(CODING_WEAK) },
|
|
470
|
+
mixed: { strong: compileSalience(MIXED_STRONG), weak: compileSalience(MIXED_WEAK) },
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function turnText(events) {
|
|
474
|
+
const parts = []
|
|
475
|
+
for (const event of events) {
|
|
476
|
+
if (event.type === 'user/message') {
|
|
477
|
+
for (const block of event.data?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
478
|
+
} else if (event.type === 'assistant/message') {
|
|
479
|
+
for (const block of event.data?.message?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return parts.join('\n')
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** 强 ×2 + 弱 ×1;domain 取 domainOf(binding)(四域),未知域回退 general。 */
|
|
486
|
+
export function salienceScore(text, domain = 'general') {
|
|
487
|
+
const table = SALIENCE_TABLE[domain] || SALIENCE_TABLE.general
|
|
488
|
+
const value = String(text)
|
|
489
|
+
const strong = (value.match(table.strong) || []).length
|
|
490
|
+
const weak = (value.match(table.weak) || []).length
|
|
491
|
+
return strong * 2 + weak
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Keep salient complete turns and one neighbour on each side. Coding keeps more:
|
|
496
|
+
* weak signals, every turn that touched a tool, and a doubled turn cap — the
|
|
497
|
+
* change itself lives in the tool calls, not in the prose around them.
|
|
498
|
+
*/
|
|
499
|
+
export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general' } = {}) {
|
|
500
|
+
const coding = String(domain) === 'coding'
|
|
501
|
+
// 编码域的改动发生在工具调用里,正文常常只有一句「改这个函数」;salience 词表
|
|
502
|
+
// 命中不了就整回合丢掉,种子只剩关键词最多的闲聊。coding 因此放宽:弱词也算数,
|
|
503
|
+
// 带工具调用的回合一律保留,回合上限翻倍。
|
|
504
|
+
const threshold = coding ? 1 : 2
|
|
505
|
+
const cap = coding ? Math.max(Number(maxTurns) || 0, 120) : maxTurns
|
|
506
|
+
const groups = []
|
|
507
|
+
let current = null
|
|
508
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
509
|
+
if (event?.type === 'turn/start' || current === null) {
|
|
510
|
+
current = []
|
|
511
|
+
groups.push(current)
|
|
512
|
+
}
|
|
513
|
+
current.push(event)
|
|
514
|
+
if (event?.type === 'turn/end') current = null
|
|
515
|
+
}
|
|
516
|
+
const kept = new Set()
|
|
517
|
+
groups.forEach((group, index) => {
|
|
518
|
+
const scored = salienceScore(turnText(group), domain) >= threshold
|
|
519
|
+
const worked = coding && group.some((event) => event?.type === 'tool/call')
|
|
520
|
+
if (scored || worked) kept.add(index)
|
|
521
|
+
})
|
|
522
|
+
if (kept.size === 0) return Array.isArray(events) ? [...events] : []
|
|
523
|
+
const expanded = new Set(kept)
|
|
524
|
+
for (const index of kept) {
|
|
525
|
+
if (index > 0) expanded.add(index - 1)
|
|
526
|
+
if (index + 1 < groups.length) expanded.add(index + 1)
|
|
527
|
+
}
|
|
528
|
+
const selected = [...expanded].sort((a, b) => a - b).slice(0, cap)
|
|
529
|
+
const covered = selected.reduce((sum, index) => sum + groups[index].length, 0)
|
|
530
|
+
if (covered >= events.length * 0.8) return [...events]
|
|
531
|
+
return selected.flatMap((index) => groups[index])
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// Build a zero-token list of required candidates for this window. Topic selection can
|
|
535
|
+
// omit new people, handoffs, or brief agreements even when their salience is high. Give
|
|
536
|
+
// the worker a short seq-keyed list and require each item to be written or explicitly
|
|
537
|
+
// accounted for in the receipt.
|
|
538
|
+
const MUST_COVER_PERSON = /叫|自称|称呼|换|接手|改成|换成|新来|同事|师傅|阿姨|房东|店长|老板|邻居|朋友|家人/
|
|
539
|
+
export function mustCoverCandidates(events, { max = 8, minScore = 3, domain = 'general' } = {}) {
|
|
540
|
+
const groups = []
|
|
541
|
+
let current = null
|
|
542
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
543
|
+
if (event?.type === 'turn/start' || current === null) {
|
|
544
|
+
current = []
|
|
545
|
+
groups.push(current)
|
|
546
|
+
}
|
|
547
|
+
current.push(event)
|
|
548
|
+
if (event?.type === 'turn/end') current = null
|
|
549
|
+
}
|
|
550
|
+
const rows = []
|
|
551
|
+
const seen = new Set()
|
|
552
|
+
groups.forEach((group) => {
|
|
553
|
+
const text = turnText(group)
|
|
554
|
+
const score = salienceScore(text, domain)
|
|
555
|
+
if (score < minScore) return
|
|
556
|
+
const userText = group
|
|
557
|
+
.filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
|
|
558
|
+
.flatMap((event) => (event.data?.content || []).filter((block) => block?.type === 'text').map((block) => String(block.text || '')))
|
|
559
|
+
.join(' ')
|
|
560
|
+
const source = (userText || text).replace(/\s+/g, ' ').trim().slice(0, 90)
|
|
561
|
+
if (!source || seen.has(source)) return
|
|
562
|
+
seen.add(source)
|
|
563
|
+
const observedAt = group
|
|
564
|
+
.filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
|
|
565
|
+
.map((event) => event.data?.sceneTime)
|
|
566
|
+
.find((value) => typeof value === 'string' && value) || null
|
|
567
|
+
rows.push({
|
|
568
|
+
fromSeq: Number(group[0]?.seq),
|
|
569
|
+
throughSeq: Number(group[group.length - 1]?.seq),
|
|
570
|
+
score,
|
|
571
|
+
tag: MUST_COVER_PERSON.test(text) ? '人物/关系' : '事实',
|
|
572
|
+
text: source,
|
|
573
|
+
observedAt,
|
|
574
|
+
})
|
|
575
|
+
})
|
|
576
|
+
return rows
|
|
577
|
+
.sort((a, b) => b.score - a.score)
|
|
578
|
+
.slice(0, Math.max(1, Number(max) || 8))
|
|
579
|
+
.sort((a, b) => a.fromSeq - b.fromSeq)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** 顺延候选优先占位,但最多 4 条;其余名额留给本窗新候选。 */
|
|
583
|
+
export function mergeMustCover(carry, fresh, { max = 8, carryMax = 4 } = {}) {
|
|
584
|
+
const rows = []
|
|
585
|
+
const seen = new Set()
|
|
586
|
+
const add = (row) => {
|
|
587
|
+
if (!row || typeof row.text !== 'string') return
|
|
588
|
+
const key = row.text.replace(/\s+/g, '').slice(0, 60)
|
|
589
|
+
if (!key || seen.has(key)) return
|
|
590
|
+
seen.add(key)
|
|
591
|
+
rows.push(row)
|
|
592
|
+
}
|
|
593
|
+
for (const row of (Array.isArray(carry) ? carry : []).slice(0, Math.max(0, Number(carryMax) || 0))) {
|
|
594
|
+
add({ ...row, carried: true })
|
|
595
|
+
}
|
|
596
|
+
for (const row of Array.isArray(fresh) ? fresh : []) add(row)
|
|
597
|
+
return rows.slice(0, Math.max(1, Number(max) || 8))
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*月\s*\d{1,2}\s*[日号]?|\d{1,2}\s*[月日号]/g
|
|
601
|
+
const COVER_STOP = new Set([
|
|
602
|
+
'我们', '他们', '你们', '现在', '已经', '可以', '什么', '这个', '那个',
|
|
603
|
+
'时候', '今天', '明天', '昨天', '一下', '一个', '还是', '不是', '就是',
|
|
604
|
+
])
|
|
605
|
+
const COVER_TOKEN_RECALL = 0.55
|
|
606
|
+
function coverText(text) {
|
|
607
|
+
return String(text || '').normalize('NFKC').toLowerCase().replace(COVER_DATE_RE, ' ')
|
|
608
|
+
}
|
|
609
|
+
function coverTokens(text) {
|
|
610
|
+
return new Set(tokenize(text)
|
|
611
|
+
.filter((token) => typeof token === 'string' && token.length >= 2 && !/\d/.test(token) && !COVER_STOP.has(token)))
|
|
612
|
+
}
|
|
613
|
+
function coverAtoms(text) {
|
|
614
|
+
return new Set(text.match(/[\p{Script=Han}]|[a-z]+/gu) || [])
|
|
615
|
+
}
|
|
616
|
+
/** Conservative local evidence check; uncertainty keeps the candidate in carry. */
|
|
617
|
+
export function candidateCovered(candidate, writtenIds, index) {
|
|
618
|
+
const entries = index?.entries || {}
|
|
619
|
+
const text = String(candidate?.text || '')
|
|
620
|
+
if (!text) return true
|
|
621
|
+
const normalized = coverText(text)
|
|
622
|
+
const wanted = coverTokens(normalized)
|
|
623
|
+
const atoms = coverAtoms(normalized)
|
|
624
|
+
const values = numericSet(text)
|
|
625
|
+
// A date or an uninformative fragment cannot prove a fact was written.
|
|
626
|
+
if (wanted.size < 2 || atoms.size === 0) return false
|
|
627
|
+
for (const id of Array.isArray(writtenIds) ? writtenIds : []) {
|
|
628
|
+
const entry = entries[id]
|
|
629
|
+
if (!entry) continue
|
|
630
|
+
const body = String(entry.title || '') + ' ' + String(entry.content || '')
|
|
631
|
+
const haveValues = numericSet(body)
|
|
632
|
+
if ([...values].some((value) => !haveValues.has(value))) continue
|
|
633
|
+
const normalizedBody = coverText(body)
|
|
634
|
+
const haveAtoms = coverAtoms(normalizedBody)
|
|
635
|
+
// Missing names, actions or objects are not covered by a matching topic/date.
|
|
636
|
+
if ([...atoms].some((atom) => !haveAtoms.has(atom))) continue
|
|
637
|
+
const have = coverTokens(normalizedBody)
|
|
638
|
+
const shared = [...wanted].filter((token) => have.has(token))
|
|
639
|
+
if (shared.length < Math.min(3, wanted.size) || shared.length / wanted.size < COVER_TOKEN_RECALL) continue
|
|
640
|
+
if (shared.some((token) => polarityAt(text, token) !== polarityAt(body, token))) continue
|
|
641
|
+
return true
|
|
642
|
+
}
|
|
643
|
+
return false
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Existing entries, compact, for dedupe/update instead of duplicate writes. */
|
|
647
|
+
export function memoryCatalogEvent(binding, now = Date.now()) {
|
|
648
|
+
if (!binding?.libraryId) return null
|
|
649
|
+
let entries = []
|
|
650
|
+
try { entries = Object.entries(loadPrivateIndex(binding.libraryId).entries || {}) } catch { return null }
|
|
651
|
+
const rows = entries
|
|
652
|
+
.filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
|
|
653
|
+
.filter(([, entry]) => visibleToSession(entry, binding.sessionId))
|
|
654
|
+
.sort((a, b) => String(b[1].updatedAt || b[1].createdAt || '').localeCompare(String(a[1].updatedAt || a[1].createdAt || '')))
|
|
655
|
+
.slice(0, SEED_CATALOG_ENTRIES)
|
|
656
|
+
.map(([id, entry]) => `- [${id}] ${capSeedText(entry.title || '(untitled)', 120)} · ${entry.layer || 'long_term'} · ${entry.status || 'active'}`)
|
|
657
|
+
// 欠账单列:目录按更新时间截断,逾期的承诺很可能不在前 N 条里,而整理必须看见它。
|
|
658
|
+
const overdueRows = overdueOpenCommitments({ libraryId: binding.libraryId, now, minOverdueDays: 0, limit: 8, sessionId: binding.sessionId })
|
|
659
|
+
.filter(({ entry }) => visibleToSession(entry, binding.sessionId))
|
|
660
|
+
.map(({ id, entry, commitment, dueAt, daysOverdue }) => {
|
|
661
|
+
const who = commitment.counterparty ? `对 ${capSeedText(commitment.counterparty, 40)}:` : ''
|
|
662
|
+
return `- [${id}] ${capSeedText(entry.title || '(untitled)', 80)} · due=${dueAt} · 已逾期 ${daysOverdue} 天 · ${who}${capSeedText(commitment.action, 120)}`
|
|
663
|
+
})
|
|
664
|
+
if (rows.length === 0 && overdueRows.length === 0) return null
|
|
665
|
+
const text = [
|
|
666
|
+
'[memory-catalog · 已有记忆目录(只读上下文,不是用户发言,也不属于本轮转录)]',
|
|
667
|
+
'下面这些是本次整理之前已经写入本库的条目。不要当作用户说过的话,也不要重复创建;同一事实用 memu_private_update id=<id> 合并,真正新增的内容才用 memu_private_remember。',
|
|
668
|
+
...rows,
|
|
669
|
+
...(overdueRows.length > 0
|
|
670
|
+
? ['欠账(status=open 且已过 due_at):整理时按本轮转录证据结案——兑现写 done、明确取消写 cancelled、确实作废写 expired;没有证据就保留 open,并在正文写明仍欠着谁。',
|
|
671
|
+
...overdueRows]
|
|
672
|
+
: []),
|
|
673
|
+
].join('\n')
|
|
674
|
+
return {
|
|
675
|
+
type: 'user/message',
|
|
676
|
+
seq: 0,
|
|
677
|
+
time: now,
|
|
678
|
+
data: createUserMessage({
|
|
679
|
+
content: [{ type: 'text', text }],
|
|
680
|
+
source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' },
|
|
681
|
+
}),
|
|
682
|
+
surfaceOp: 'append',
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function recentUserText(events, limit = 6) {
|
|
687
|
+
const parts = []
|
|
688
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
689
|
+
if (event?.type !== 'user/message' || event.data?.source?.kind !== 'user') continue
|
|
690
|
+
for (const block of event.data?.content || []) {
|
|
691
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) parts.push(block.text.trim())
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return parts.slice(-limit).join('\n')
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* 1.3.1:本窗候选的本地召回命中。worker 不再获得 recall/list 工具,去重所需的
|
|
699
|
+
* 旧条目必须在种子里就给出;这里用插件现有的 BM25 词法腿做零 Token 预召回,
|
|
700
|
+
* 只给 id + 标题 + 一段正文,够 worker 判断 update 还是 remember。
|
|
701
|
+
*/
|
|
702
|
+
export function memoryRecallEvent({ binding = null, candidates = [], events = [], now = Date.now(), topK = 6 } = {}) {
|
|
703
|
+
if (!binding?.libraryId) return null
|
|
704
|
+
let rows = []
|
|
705
|
+
try {
|
|
706
|
+
rows = Object.entries(loadPrivateIndex(binding.libraryId).entries || {})
|
|
707
|
+
.filter(([, entry]) => entry && isMemoryEligible(entry, { automatic: true, now }))
|
|
708
|
+
.filter(([, entry]) => visibleToSession(entry, binding.sessionId))
|
|
709
|
+
.map(([id, entry]) => ({ ...entry, id }))
|
|
710
|
+
} catch { return null }
|
|
711
|
+
if (rows.length === 0) return null
|
|
712
|
+
const query = [
|
|
713
|
+
...(Array.isArray(candidates) ? candidates.map((item) => item?.text) : []),
|
|
714
|
+
recentUserText(events),
|
|
715
|
+
].filter(Boolean).join('\n')
|
|
716
|
+
const tokens = tokenize(query)
|
|
717
|
+
if (tokens.length === 0) return null
|
|
718
|
+
const corpus = buildCorpus(rows)
|
|
719
|
+
const scored = rows
|
|
720
|
+
.map((entry) => ({ entry, score: bm25(tokens, corpus.docs.get(entry.id), corpus) }))
|
|
721
|
+
.filter((item) => item.score > 0)
|
|
722
|
+
.sort((a, b) => b.score - a.score)
|
|
723
|
+
.slice(0, Math.max(1, Number(topK) || 6))
|
|
724
|
+
if (scored.length === 0) return null
|
|
725
|
+
const text = [
|
|
726
|
+
'[memory-recall · 本地召回命中(只读上下文,不是用户发言,也不属于本轮转录)]',
|
|
727
|
+
'下面是与本窗候选最相关的已有条目;只用于去重/合并,不是用户说过的话,也不是新证据。',
|
|
728
|
+
...scored.map(({ entry }) => `- [${entry.id}] ${capSeedText(entry.title || '(untitled)', 80)} — ${capSeedText(entry.content || '', 90)}`),
|
|
729
|
+
].join('\n')
|
|
730
|
+
return {
|
|
731
|
+
type: 'user/message',
|
|
732
|
+
seq: 0,
|
|
733
|
+
time: now,
|
|
734
|
+
data: createUserMessage({
|
|
735
|
+
content: [{ type: 'text', text }],
|
|
736
|
+
source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' },
|
|
737
|
+
}),
|
|
738
|
+
surfaceOp: 'append',
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** First `limit` events, trimmed back to a complete turn so a fork never sees half a step. */
|
|
743
|
+
export function selectConsolidationWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
|
|
744
|
+
const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
|
|
745
|
+
if (list.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
|
|
746
|
+
if (list.length <= limit) return { events: list, fromSeq: eventSeq(list[0]), throughSeq: eventSeq(list[list.length - 1]), remaining: 0 }
|
|
747
|
+
const cutSeq = eventSeq(list[Math.max(0, limit - 1)])
|
|
748
|
+
const sliced = list.filter(event => eventSeq(event) <= cutSeq)
|
|
749
|
+
const safe = safePrefix(sliced, { requireClosedTurn: false })
|
|
750
|
+
const window = safe.ok && safe.events.length > 0 ? safe.events : sliced
|
|
751
|
+
const throughSeq = eventSeq(window[window.length - 1])
|
|
752
|
+
return {
|
|
753
|
+
events: window,
|
|
754
|
+
fromSeq: eventSeq(window[0]),
|
|
755
|
+
throughSeq,
|
|
756
|
+
remaining: list.filter(event => eventSeq(event) > throughSeq).length,
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** Align worker windows to completed turns. If a window ends mid-turn, move that
|
|
761
|
+
* turn to the next window so adjacent windows do not resend it. Return the original
|
|
762
|
+
* range when there is no completed turn for alignment; the caller handles fallback.
|
|
763
|
+
* This applies only to the worker path. Do not move the cursor backward when only a
|
|
764
|
+
* session-level event follows the last turn; a new turn has started only if a
|
|
765
|
+
* turn/start follows the last turn/end. */
|
|
766
|
+
export function alignWindowToTurn(window) {
|
|
767
|
+
const events = Array.isArray(window?.events) ? window.events : []
|
|
768
|
+
let lastEnd = null
|
|
769
|
+
for (const event of events) {
|
|
770
|
+
if (event?.type !== 'turn/end') continue
|
|
771
|
+
const seq = eventSeq(event)
|
|
772
|
+
if (seq !== null && (lastEnd === null || seq > lastEnd)) lastEnd = seq
|
|
773
|
+
}
|
|
774
|
+
if (lastEnd === null || lastEnd === window.throughSeq) return window
|
|
775
|
+
const trailing = events.filter((event) => {
|
|
776
|
+
const seq = eventSeq(event)
|
|
777
|
+
return seq !== null && seq > lastEnd
|
|
778
|
+
})
|
|
779
|
+
// 最后回合结束后只剩宿主元数据:整段保留,别为了对齐丢掉转录末尾的事件。
|
|
780
|
+
if (!trailing.some((event) => event?.type === 'turn/start')) return window
|
|
781
|
+
const aligned = events.filter((event) => {
|
|
782
|
+
const seq = eventSeq(event)
|
|
783
|
+
return seq !== null && seq <= lastEnd
|
|
784
|
+
})
|
|
785
|
+
if (aligned.length === 0) return window
|
|
786
|
+
return {
|
|
787
|
+
events: aligned,
|
|
788
|
+
fromSeq: window.fromSeq,
|
|
789
|
+
throughSeq: lastEnd,
|
|
790
|
+
remaining: (Number(window.remaining) || 0) + (events.length - aligned.length),
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** Select a worker window by event count, then extend it through the current turn's
|
|
795
|
+
* turn/end. Turn-log entries represent whole turns, so leaving a partial turn for the
|
|
796
|
+
* next window would resend that turn in full. The worker package is bounded by record
|
|
797
|
+
* size, so completing the turn does not enlarge its context. If the extension exceeds
|
|
798
|
+
* the defensive limit, retain the original window.
|
|
799
|
+
*/
|
|
800
|
+
export function selectWorkerWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS, maxExtend = WORKER_WINDOW_EXTEND_EVENTS) {
|
|
801
|
+
const list = (Array.isArray(events) ? events : []).filter((event) => eventSeq(event) !== null)
|
|
802
|
+
const initial = selectConsolidationWindow(list, limit)
|
|
803
|
+
if (!initial.events || initial.events.length === 0) return initial
|
|
804
|
+
const lastEndIndex = (() => {
|
|
805
|
+
for (let i = initial.events.length - 1; i >= 0; i -= 1) {
|
|
806
|
+
if (initial.events[i]?.type === 'turn/end') return i
|
|
807
|
+
}
|
|
808
|
+
return -1
|
|
809
|
+
})()
|
|
810
|
+
const openAfter = lastEndIndex < 0
|
|
811
|
+
|| initial.events.slice(lastEndIndex + 1).some((event) => event?.type === 'turn/start')
|
|
812
|
+
if (!openAfter) return alignWindowToTurn(initial)
|
|
813
|
+
const extraBudget = Math.max(0, Number(maxExtend) || 0)
|
|
814
|
+
if (extraBudget === 0) return alignWindowToTurn(initial)
|
|
815
|
+
const nextEnd = list
|
|
816
|
+
.filter((event) => eventSeq(event) > initial.throughSeq)
|
|
817
|
+
.slice(0, extraBudget)
|
|
818
|
+
.find((event) => event?.type === 'turn/end')
|
|
819
|
+
if (!nextEnd) return alignWindowToTurn(initial)
|
|
820
|
+
const through = eventSeq(nextEnd)
|
|
821
|
+
const extended = list.filter((event) => {
|
|
822
|
+
const seq = eventSeq(event)
|
|
823
|
+
return seq >= initial.fromSeq && seq <= through
|
|
824
|
+
})
|
|
825
|
+
const safe = safePrefix(extended, { requireClosedTurn: false })
|
|
826
|
+
const chosen = safe.ok && safe.events.length > 0 ? safe.events : extended
|
|
827
|
+
const chosenThrough = eventSeq(chosen[chosen.length - 1])
|
|
828
|
+
return {
|
|
829
|
+
events: chosen,
|
|
830
|
+
fromSeq: eventSeq(chosen[0]),
|
|
831
|
+
throughSeq: chosenThrough,
|
|
832
|
+
remaining: list.filter((event) => eventSeq(event) > chosenThrough).length,
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** Last complete turn window, for a manual re-check when the cursor is already at the end. */
|
|
837
|
+
export function selectTailTurnWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
|
|
838
|
+
const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
|
|
839
|
+
const slice = list.slice(-limit)
|
|
840
|
+
if (slice.length === 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
|
|
841
|
+
let start = slice.findIndex(event => event.type === 'turn/start')
|
|
842
|
+
if (start < 0) start = slice.findIndex(event => event.type === 'user/message')
|
|
843
|
+
if (start < 0) return { events: [], fromSeq: null, throughSeq: null, remaining: 0 }
|
|
844
|
+
for (let i = start - 1; i >= 0; i -= 1) {
|
|
845
|
+
if (slice[i].type === 'user/message' && slice[i].data?.source?.kind === 'user') { start = i; break }
|
|
846
|
+
if (slice[i].type === 'turn/end' || slice[i].type === 'turn/start') break
|
|
847
|
+
}
|
|
848
|
+
const window = slice.slice(start)
|
|
849
|
+
const safe = safePrefix(window, { requireClosedTurn: false })
|
|
850
|
+
const chosen = safe.ok && safe.events.length > 0 ? safe.events : window
|
|
851
|
+
return { events: chosen, fromSeq: eventSeq(chosen[0]), throughSeq: eventSeq(chosen[chosen.length - 1]), remaining: 0 }
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* 整理游标只能前进:尾部人工重检选中最后一个回合时,窗口可能比已有游标更靠前
|
|
856
|
+
* (例如已经结算过 turn/end 后的 session/end-seed),直接写回会把 lastSleepSeq
|
|
857
|
+
* 从 5099 拉回 5098。统一走这里,取当前值与新值的较大者。
|
|
858
|
+
*/
|
|
859
|
+
function advanceSleepCursor(sessionId, seq, patch = {}) {
|
|
860
|
+
const next = Number(seq)
|
|
861
|
+
if (!Number.isSafeInteger(next) || next < 0) return null
|
|
862
|
+
const current = (() => {
|
|
863
|
+
try { return Number(getSessionBinding(sessionId)?.lastSleepSeq) } catch { return NaN }
|
|
864
|
+
})()
|
|
865
|
+
const value = Number.isSafeInteger(current) && current >= 0 ? Math.max(current, next) : next
|
|
866
|
+
setSessionBinding(sessionId, { lastSleepSeq: value, ...patch })
|
|
867
|
+
return value
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// 归档会话集合(issue #4 缺陷 3):宿主 workspaceRegistry 的 archivedSessionIds 是
|
|
871
|
+
// 使命名数组;包装成 Set 供 cycle.js 与 private.js 入口共用。注册表缺失/异常时返回
|
|
872
|
+
// null(无信息,不做拦截),与 rpc.js 的读法一致。
|
|
873
|
+
export function archivedSessionIdsOf(ctx) {
|
|
874
|
+
try {
|
|
875
|
+
return new Set((ctx?.get?.('workspaceRegistry')?.archivedSessionIds || []).map(String))
|
|
876
|
+
} catch {
|
|
877
|
+
return null
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
export async function requestPrivateConsolidation(ctx, sessionId, options = {}) {
|
|
882
|
+
const binding = getSessionBinding(sessionId)
|
|
883
|
+
if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
|
|
884
|
+
if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
|
|
885
|
+
// 归档会话在宿主 agent/pre-step 必被拒("the fork turn ended blocked"),fork 只会
|
|
886
|
+
// 白建一次再计两次失败踩进冻结。cycle.js 已在候选阶段事前跳过;这里拦手动调用,
|
|
887
|
+
// 给出明确的 reasonCode 而不是让用户等到失败回执。
|
|
888
|
+
const archived = archivedSessionIdsOf(ctx)
|
|
889
|
+
if (archived?.size && archived.has(String(sessionId))) {
|
|
890
|
+
return {
|
|
891
|
+
ok: false, skipped: 'session-archived', settled: false, reasonCode: 'session-archived',
|
|
892
|
+
error: 'session is archived; unarchive it before consolidating',
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
// Always a fork, never the live session's own inbox. `agent.followup` on the
|
|
896
|
+
// chat the user is looking at does queue a real turn — but the host renders a
|
|
897
|
+
// queued next-turn message as a pending draft above the composer (editable,
|
|
898
|
+
// deletable, sent on demand), and once it runs it stays in that transcript
|
|
899
|
+
// forever, re-sent on every later turn. A live session is no exception: the
|
|
900
|
+
// fork seeds the same transcript, so recall quality is unchanged, while the
|
|
901
|
+
// housekeeping turn lands in a scratch subagent session (origin: subagent —
|
|
902
|
+
// out of the window list and out of the injection path) that is disposed.
|
|
903
|
+
return requestHistoricalConsolidation(ctx, sessionId, options)
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// Remote mode: the configured remote chat endpoint writes the memories, then they
|
|
907
|
+
// are committed through the same backend. No local agent or tool chain is touched.
|
|
908
|
+
export async function requestRemoteConsolidation(ctx, sessionId, { signal, timeoutMs, force = false } = {}) {
|
|
909
|
+
const binding = getSessionBinding(sessionId)
|
|
910
|
+
if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
|
|
911
|
+
if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
|
|
912
|
+
const sessionQuery = ctx.get?.('sessionQuery')
|
|
913
|
+
if (!sessionQuery) return { ok: false, error: 'host has no sessionQuery; cannot read this conversation' }
|
|
914
|
+
try {
|
|
915
|
+
const snapshot = await readSessionSnapshot(sessionQuery, sessionId)
|
|
916
|
+
const events = Array.isArray(snapshot?.events) ? snapshot.events : []
|
|
917
|
+
if (events.length === 0) return { ok: false, error: 'this session has no content to consolidate' }
|
|
918
|
+
const fresh = unconsolidatedEvents(binding, events)
|
|
919
|
+
if (!force) {
|
|
920
|
+
const value = assessConsolidationValue(fresh)
|
|
921
|
+
if (!value.worth) return { ok: true, sessionId, backend: 'api', count: 0, skipped: value.reason, assessment: value }
|
|
922
|
+
}
|
|
923
|
+
const transcript = condenseEvents(fresh, 60_000, condenseLimitsFor(domainOf(binding)))
|
|
924
|
+
const library = binding.libraryId ? getLibrary(binding.libraryId) : null
|
|
925
|
+
const memories = await summarizeRemote({
|
|
926
|
+
transcript,
|
|
927
|
+
libraryName: library ? `${library.name} (${library.id})` : '(unbound)',
|
|
928
|
+
domain: domainOf(binding),
|
|
929
|
+
signal,
|
|
930
|
+
timeoutMs,
|
|
931
|
+
})
|
|
932
|
+
// 写入计数必须说真话:`memories` 是模型给的清单,逐条 privateRemember 可能被
|
|
933
|
+
// 事实级去重拒绝(deduped,不落库)或因矛盾暂扣(pending_review,仅入索引)。
|
|
934
|
+
// count 只数真正落库的;被拒/暂扣分列进 detail,否则"写入 N 条"就是误报。
|
|
935
|
+
let written = 0
|
|
936
|
+
let deduped = 0
|
|
937
|
+
let held = 0
|
|
938
|
+
for (const memory of memories) {
|
|
939
|
+
const outcome = await privateRemember({
|
|
940
|
+
...memory,
|
|
941
|
+
exec: { agent: { session: { header: { id: sessionId } } } },
|
|
942
|
+
content: memory.content,
|
|
943
|
+
title: memory.title || memory.content,
|
|
944
|
+
tags: memory.tags,
|
|
945
|
+
openLoop: memory.openLoop,
|
|
946
|
+
confidence: memory.confidence,
|
|
947
|
+
source: memory.source || 'inferred',
|
|
948
|
+
})
|
|
949
|
+
if (outcome?.deduped === true) deduped += 1
|
|
950
|
+
else if (outcome?.entry?.status === 'pending_review') held += 1
|
|
951
|
+
else written += 1
|
|
952
|
+
}
|
|
953
|
+
advanceSleepCursor(sessionId, events[events.length - 1]?.seq)
|
|
954
|
+
const result = { ok: true, sessionId, backend: 'api', count: written, deduped, held }
|
|
955
|
+
record({
|
|
956
|
+
kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
|
|
957
|
+
message: `整理完成(远程)· 写入 ${written}`
|
|
958
|
+
+ (deduped ? ` · 去重拦下 ${deduped}` : '')
|
|
959
|
+
+ (held ? ` · 待复核 ${held}` : ''),
|
|
960
|
+
detail: { ...result, forced: force },
|
|
961
|
+
})
|
|
962
|
+
return result
|
|
963
|
+
} catch (error) {
|
|
964
|
+
record({
|
|
965
|
+
kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'error',
|
|
966
|
+
message: '整理失败(远程):' + String(error?.message || error),
|
|
967
|
+
detail: { forced: force },
|
|
968
|
+
})
|
|
969
|
+
return { ok: false, error: String(error?.message || error) }
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// `buildForkSeed` lives in dsh-session, which this plugin does not need for
|
|
974
|
+
// anything else. Imported lazily so a host that does not expose it loses only
|
|
975
|
+
// historical consolidation, not the whole plugin half.
|
|
976
|
+
async function loadBuildForkSeed() {
|
|
977
|
+
try {
|
|
978
|
+
const mod = await import('@deepseek-ai/dsh-session')
|
|
979
|
+
return typeof mod?.buildForkSeed === 'function' ? mod.buildForkSeed : null
|
|
980
|
+
} catch {
|
|
981
|
+
return null
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
function agentOptionsFromConfig(config) {
|
|
986
|
+
if (!config || typeof config !== 'object') return null
|
|
987
|
+
const provider = typeof config.provider === 'string' ? config.provider.trim() : ''
|
|
988
|
+
const model = typeof config.model === 'string' ? config.model.trim() : ''
|
|
989
|
+
if (!provider || !model) return null
|
|
990
|
+
const options = { provider, model }
|
|
991
|
+
if (typeof config.reasoningEffort === 'string' && config.reasoningEffort) options.reasoningEffort = config.reasoningEffort
|
|
992
|
+
if (Number.isSafeInteger(config.maxTokens) && config.maxTokens > 0) options.maxTokens = config.maxTokens
|
|
993
|
+
return options
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// A fork starts a new agent loop and does not inherit the parent's Agent options.
|
|
997
|
+
// Use the live request header for an active session or its latest recorded request for
|
|
998
|
+
// a closed session. If neither is available, the standard preset cannot resolve
|
|
999
|
+
// {{model}}, so do not create the fork. A session with externally appended history may
|
|
1000
|
+
// have no request header; use the public resume() API to re-register its own loop when
|
|
1001
|
+
// available. If that capability is unavailable or fails, return null and refuse the fork.
|
|
1002
|
+
async function inheritedAgentOptions(ctx, sessionId, events) {
|
|
1003
|
+
let agents = null
|
|
1004
|
+
try { agents = ctx.get?.('agents') || null } catch {}
|
|
1005
|
+
const probe = (agent) => {
|
|
1006
|
+
try {
|
|
1007
|
+
const fromRequest = liveAgentOptions(agent)
|
|
1008
|
+
if (fromRequest) return fromRequest
|
|
1009
|
+
} catch {}
|
|
1010
|
+
return agentOptionsFromConfig(agent?.options)
|
|
1011
|
+
}
|
|
1012
|
+
let live = null
|
|
1013
|
+
try { live = agents?.get?.(sessionId) || null } catch {}
|
|
1014
|
+
const direct = probe(live)
|
|
1015
|
+
if (direct) return direct
|
|
1016
|
+
if (agents && typeof agents.resume === 'function') {
|
|
1017
|
+
try {
|
|
1018
|
+
const resumed = await agents.resume({ resumeSessionId: sessionId })
|
|
1019
|
+
const fromResumed = probe(resumed?.agent || resumed)
|
|
1020
|
+
if (fromResumed) return fromResumed
|
|
1021
|
+
} catch {}
|
|
1022
|
+
}
|
|
1023
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1024
|
+
if (events[i]?.type !== 'request/header') continue
|
|
1025
|
+
const fromEvent = agentOptionsFromConfig(events[i]?.data?.header?.config)
|
|
1026
|
+
if (fromEvent) return fromEvent
|
|
1027
|
+
}
|
|
1028
|
+
return null
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
function turnEndFailure(event) {
|
|
1032
|
+
const reason = event?.data?.reason
|
|
1033
|
+
if (!reason || typeof reason !== 'object') return 'the fork produced no turn/end event'
|
|
1034
|
+
if (reason.kind === 'completed') return null
|
|
1035
|
+
const message = reason?.error?.message || reason?.reason?.message || reason?.message
|
|
1036
|
+
return 'the fork turn ended ' + (reason.kind || 'without a reason') + (message ? ': ' + message : '')
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// attachWorkerTools / restrictWorkerTools are shared implementations in worker-pool.js;
|
|
1040
|
+
// both persistent workers and the 'fork' path import them from that module.
|
|
1041
|
+
|
|
1042
|
+
// 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件):
|
|
1043
|
+
// workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认
|
|
1044
|
+
// (fork ctx 无 tools 服务、register 抛错、宿主没回名单),
|
|
1045
|
+
// 与"挂全了"严格区分——这正是旧字段把 wanted 全量误报成
|
|
1046
|
+
// 已挂载的教训。
|
|
1047
|
+
// workerToolsRequested 请求挂载的完整 wanted 名单;与 attached 全等才是全量挂载。
|
|
1048
|
+
// workerToolsPartial true = 未证明 worker 拿到完整 wanted 集(子集、空集、或挂载
|
|
1049
|
+
// 整体失败)。刻意把"一件都没挂上"也标 true:若失败标 false,
|
|
1050
|
+
// false 会被一眼读成"全量挂载",元数据又不准了。
|
|
1051
|
+
function workerToolsMeta(workerTools) {
|
|
1052
|
+
const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
|
|
1053
|
+
if (!workerTools) {
|
|
1054
|
+
return { workerToolsAttached: null, workerToolsRequested: wanted, workerToolsPartial: true }
|
|
1055
|
+
}
|
|
1056
|
+
return {
|
|
1057
|
+
workerToolsAttached: Array.isArray(workerTools.attached) ? workerTools.attached : null,
|
|
1058
|
+
workerToolsRequested: Array.isArray(workerTools.requested) ? workerTools.requested : wanted,
|
|
1059
|
+
workerToolsPartial: workerTools.partial === true,
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
const inFlight = new Map()
|
|
1064
|
+
// How long a cancelled fork gets to finish the tool call it was in the middle of.
|
|
1065
|
+
// Bounded on purpose: a child that ignores the cancel must not hang the sweep, and
|
|
1066
|
+
// the alternative — disposing immediately — is what let a write land after the range
|
|
1067
|
+
// was already handed back to pending.
|
|
1068
|
+
const WORKER_STOP_GRACE_MS = 5_000
|
|
1069
|
+
|
|
1070
|
+
// 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
|
|
1071
|
+
// 的 file:line 当成诊断契约(当前 lib/private.js:1014),修改位置时同步更新该诊断映射,
|
|
1072
|
+
// ESM imports are hoisted; synchronize diagnostic source mappings after relocation.
|
|
1073
|
+
import { warn, dataDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
|
|
1074
|
+
import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
|
|
1075
|
+
import {
|
|
1076
|
+
beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey, sessionState,
|
|
1077
|
+
recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
|
|
1078
|
+
readCarryCandidates, setCarryCandidates,
|
|
1079
|
+
} from './consolidation-ledger.js'
|
|
1080
|
+
import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
|
|
1081
|
+
import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
|
|
1082
|
+
// worker-pool.js owns worker acquisition, retirement, epoch tracking, package assembly,
|
|
1083
|
+
// and tool mounting; the 'fork' path uses the same tool-mount implementation.
|
|
1084
|
+
import {
|
|
1085
|
+
acquireWorker, attachWorkerTools, buildHandoffPack, buildIncrementPack, loadWorkerIncrement,
|
|
1086
|
+
recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
|
|
1087
|
+
resolveConsolidationCwd, measurePacket, packetBudgetFit, createConsolidationMeasurement,
|
|
1088
|
+
} from './worker-pool.js'
|
|
1089
|
+
import { tokenize, buildCorpus, bm25, numericSet, polarityAt } from './text-retrieval.js'
|
|
1090
|
+
import { isGoneSessionError } from './cycle.js'
|
|
1091
|
+
import { autoLinkPrivateMemories } from './private-links.js'
|
|
1092
|
+
import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
|
|
1093
|
+
|
|
1094
|
+
function liveAgentOptions(agent) {
|
|
1095
|
+
const options = agent?.options
|
|
1096
|
+
let request = null
|
|
1097
|
+
try { request = agentOptionsFromConfig(agent?.session?.requestHeader?.()?.config) } catch {}
|
|
1098
|
+
if (!request) return agentOptionsFromConfig(options)
|
|
1099
|
+
const sameRoute = (!options?.provider || options.provider.trim() === request.provider) && (!options?.model || options.model.trim() === request.model)
|
|
1100
|
+
if (sameRoute && Number.isSafeInteger(options?.maxTokens) && options.maxTokens > 0) return { ...request, maxTokens: options.maxTokens }
|
|
1101
|
+
return request
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
async function consolidationExecutionContext(ctx, sessionId, settings, events, inheritedOptions = null) {
|
|
1105
|
+
const mode = settings.consolidationModelMode || 'inherit'
|
|
1106
|
+
let inherited = inheritedOptions
|
|
1107
|
+
if (mode !== 'host' && mode !== 'custom' && !inherited) {
|
|
1108
|
+
try {
|
|
1109
|
+
const agent = ctx.get?.('agents')?.get?.(sessionId)
|
|
1110
|
+
inherited = liveAgentOptions(agent)
|
|
1111
|
+
} catch {}
|
|
1112
|
+
if (!inherited) {
|
|
1113
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1114
|
+
if (events[i]?.type !== 'request/header') continue
|
|
1115
|
+
inherited = agentOptionsFromConfig(events[i]?.data?.header?.config)
|
|
1116
|
+
if (inherited) break
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
const { options } = resolveConsolidationAgentOptions(settings, inherited)
|
|
1121
|
+
const configuredEffort = settings.consolidationReasoningEffort
|
|
1122
|
+
let effort = configuredEffort && configuredEffort !== 'inherit' ? configuredEffort : options?.reasoningEffort ?? null
|
|
1123
|
+
if (options && effort && isEffortRefused([options.provider, options.model, effort].join('|'))) effort = null
|
|
1124
|
+
let maxTokens = options?.maxTokens ?? null
|
|
1125
|
+
const settingsKey = crypto.createHash('sha256').update(JSON.stringify({
|
|
1126
|
+
mode, runner: settings.consolidationRunner || 'fork',
|
|
1127
|
+
provider: options?.provider ?? null, model: options?.model ?? null, maxTokens, effort,
|
|
1128
|
+
})).digest('hex')
|
|
1129
|
+
let defaultsComparable = maxTokens !== null && effort !== null
|
|
1130
|
+
if (options && !defaultsComparable) {
|
|
1131
|
+
try {
|
|
1132
|
+
const info = await ctx.get?.('llm')?.resolveModelInfo?.(options.provider, options.model)
|
|
1133
|
+
defaultsComparable = !!info && typeof info === 'object'
|
|
1134
|
+
if (maxTokens === null && Number.isSafeInteger(info?.defaultMaxTokens) && info.defaultMaxTokens > 0) maxTokens = info.defaultMaxTokens
|
|
1135
|
+
if (effort === null && typeof info?.reasoning?.defaultEffort === 'string') effort = info.reasoning.defaultEffort
|
|
1136
|
+
} catch {}
|
|
1137
|
+
}
|
|
1138
|
+
const key = crypto.createHash('sha256').update(JSON.stringify({ settingsKey, maxTokens, effort })).digest('hex')
|
|
1139
|
+
return { key, settingsKey, defaultsComparable, maxTokens }
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// 账本异常必须可见;调用方只有拿到明确的持久租约才可启动 worker。
|
|
1143
|
+
// 其余读写失败返回保守结果,不得据此推进已确认边界。
|
|
1144
|
+
function safeLedger(action, fallback = null) {
|
|
1145
|
+
try {
|
|
1146
|
+
return action()
|
|
1147
|
+
} catch (error) {
|
|
1148
|
+
try { warn('consolidation ledger: ' + String(error?.message || error)) } catch {}
|
|
1149
|
+
return fallback
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// 交给结果日志的快照身份:有 hash、有边界、没有正文。
|
|
1154
|
+
function snapshotMetaOf(snapshot) {
|
|
1155
|
+
if (!snapshot) return null
|
|
1156
|
+
return {
|
|
1157
|
+
hash: snapshot.hash,
|
|
1158
|
+
source: snapshot.source,
|
|
1159
|
+
fromSeq: snapshot.fromSeq,
|
|
1160
|
+
throughSeq: snapshot.throughSeq,
|
|
1161
|
+
eventCount: snapshot.eventCount,
|
|
1162
|
+
droppedEvents: snapshot.droppedEvents,
|
|
1163
|
+
capturedAt: snapshot.capturedAt,
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
// Every agent-backend consolidation runs here, live sessions included: the same
|
|
1168
|
+
// main agent, on a seeded copy of the transcript, writing into the library the
|
|
1169
|
+
// original used. In-place consolidation would append a housekeeping turn to the
|
|
1170
|
+
// user's own chat — a queued draft until it runs, then a permanent resident of
|
|
1171
|
+
// that transcript — so the one visible difference between a live and a closed
|
|
1172
|
+
// session is that a closed one has to be read back from disk first.
|
|
1173
|
+
// 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
|
|
1174
|
+
// Forks read the seeded transcript before writing, so the wait budget must account for
|
|
1175
|
+
// window size. The 600-second budget covers the configured window; the worker lease
|
|
1176
|
+
// extends 90 seconds beyond it so stale work can be recovered. Calls that explicitly
|
|
1177
|
+
// pass maxWaitMs retain that override.
|
|
1178
|
+
export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
|
|
1179
|
+
baseMs: 120_000,
|
|
1180
|
+
perEventMs: 350,
|
|
1181
|
+
minMs: 600_000,
|
|
1182
|
+
maxMs: 600_000,
|
|
1183
|
+
})
|
|
1184
|
+
|
|
1185
|
+
// Remember rejected provider/model/effort combinations so later forks do not repeat an
|
|
1186
|
+
// unsupported effort setting. Persist this information across restarts; a refusal is a
|
|
1187
|
+
// configuration incompatibility, not a transcript or provider outage. Load lazily, and
|
|
1188
|
+
// retry failed reads or writes on the next call.
|
|
1189
|
+
const effortRefusalCaches = new Map()
|
|
1190
|
+
// Deduplicate activity logs during a snapshot-failure freeze: record one entry per
|
|
1191
|
+
// operation key and timestamp, then ignore repeated sweeps. The in-memory cache may
|
|
1192
|
+
// reset on restart, allowing one additional record.
|
|
1193
|
+
const frozenLogStamps = new Map()
|
|
1194
|
+
|
|
1195
|
+
function effortRefusalCache() {
|
|
1196
|
+
const file = path.resolve(dataDir(), 'effort-refusals.json')
|
|
1197
|
+
if (!effortRefusalCaches.has(file)) {
|
|
1198
|
+
effortRefusalCaches.set(file, { file, keys: new Set(), loaded: false, dirty: false })
|
|
1199
|
+
}
|
|
1200
|
+
return effortRefusalCaches.get(file)
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
function readEffortRefusals(file) {
|
|
1204
|
+
const result = readJsonStrict(file)
|
|
1205
|
+
if (result.missing) return []
|
|
1206
|
+
if (!result.ok) throw result.error || new Error('cannot read effort refusals')
|
|
1207
|
+
const raw = result.value
|
|
1208
|
+
if (raw?.version !== 1 || !Array.isArray(raw.keys) || !raw.keys.every(key => typeof key === 'string')) {
|
|
1209
|
+
throw new Error('invalid effort refusals schema')
|
|
1210
|
+
}
|
|
1211
|
+
return raw.keys
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
function syncEffortRefusals(cache) {
|
|
1215
|
+
try {
|
|
1216
|
+
if (cache.dirty) {
|
|
1217
|
+
withFileLock(cache.file, () => {
|
|
1218
|
+
// 必须在锁内重读:其它进程可能已写入本缓存尚未见过的键。
|
|
1219
|
+
// 读错/坏 schema 直接退出,绝不把它当空表覆盖;写失败仍保留 dirty。
|
|
1220
|
+
const keys = new Set([...readEffortRefusals(cache.file), ...cache.keys])
|
|
1221
|
+
writeJson(cache.file, { version: 1, keys: [...keys] })
|
|
1222
|
+
cache.keys = keys
|
|
1223
|
+
cache.loaded = true
|
|
1224
|
+
cache.dirty = false
|
|
1225
|
+
})
|
|
1226
|
+
} else if (!cache.loaded) {
|
|
1227
|
+
cache.keys = new Set(readEffortRefusals(cache.file))
|
|
1228
|
+
cache.loaded = true
|
|
1229
|
+
}
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
warn('consolidation effort refusals: ' + String(error?.message || error))
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/** 从 fork 失败信息里识别『该模型不支持这个思考强度』并给出学习键。 */
|
|
1236
|
+
export function effortRefusalOf(failure) {
|
|
1237
|
+
const m = /provider "([^"]+)" model "([^"]+)" does not support reasoning effort "([^"]+)"/.exec(String(failure || ''))
|
|
1238
|
+
return m ? { provider: m[1], model: m[2], effort: m[3], key: [m[1], m[2], m[3]].join('|') } : null
|
|
1239
|
+
}
|
|
1240
|
+
export function markEffortRefused(key) {
|
|
1241
|
+
const cache = effortRefusalCache()
|
|
1242
|
+
const k = String(key)
|
|
1243
|
+
if (!cache.keys.has(k)) {
|
|
1244
|
+
cache.keys.add(k)
|
|
1245
|
+
cache.dirty = true
|
|
1246
|
+
}
|
|
1247
|
+
syncEffortRefusals(cache)
|
|
1248
|
+
}
|
|
1249
|
+
export function isEffortRefused(key) {
|
|
1250
|
+
const cache = effortRefusalCache()
|
|
1251
|
+
syncEffortRefusals(cache)
|
|
1252
|
+
return cache.keys.has(String(key))
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_POLICY) {
|
|
1256
|
+
const count = Number.isFinite(Number(eventCount)) ? Math.max(0, Math.floor(Number(eventCount))) : 0
|
|
1257
|
+
const raw = policy.baseMs + count * policy.perEventMs
|
|
1258
|
+
return Math.min(policy.maxMs, Math.max(policy.minMs, raw))
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
export async function requestHistoricalConsolidation(ctx, sessionId, options = {}) {
|
|
1262
|
+
const { maxWaitMs = null, force = false, trigger = null } = options
|
|
1263
|
+
const binding = getSessionBinding(sessionId)
|
|
1264
|
+
if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
|
|
1265
|
+
if (!binding.libraryId || !effectiveScope(binding).useLibrary) return { ok: false, error: 'private memory is disabled for this session or folder' }
|
|
1266
|
+
if (inFlight.has(sessionId)) return { ok: false, error: 'this session is already being consolidated', running: true }
|
|
1267
|
+
|
|
1268
|
+
// The session is claimed before the first await. readSession and agents.create
|
|
1269
|
+
// both yield, so two callers arriving in the same tick used to pass the guard
|
|
1270
|
+
// together and fork the same transcript twice.
|
|
1271
|
+
const abort = new AbortController()
|
|
1272
|
+
inFlight.set(sessionId, abort)
|
|
1273
|
+
let handle = null
|
|
1274
|
+
let offSession = null
|
|
1275
|
+
// N3:worker 工具循环的软/硬上限。软上限追加收尾提示,硬上限停掉 fork;
|
|
1276
|
+
// 已经写入库的条目不会因为硬停被撤销(游标不推进,下一窗重试剩余范围)。
|
|
1277
|
+
let workerToolRounds = 0
|
|
1278
|
+
let idle = null
|
|
1279
|
+
// Stopped once, callable twice: the timeout path and `finally` both need it.
|
|
1280
|
+
let stopped = false
|
|
1281
|
+
// The host's own order is cancel -> whenIdle -> dispose. dispose() alone does not
|
|
1282
|
+
// wait for a tool call in flight, and this fork writes memories *through tools*, so
|
|
1283
|
+
// "the fork was stopped" was not true when the timeout path returned: failJob had
|
|
1284
|
+
// already handed the range back and the next pass could fork the same window while
|
|
1285
|
+
// the old child was still writing. Bounded, because a child that ignores the cancel
|
|
1286
|
+
// must not hang the sweep.
|
|
1287
|
+
const stopWorker = async () => {
|
|
1288
|
+
if (stopped) return
|
|
1289
|
+
stopped = true
|
|
1290
|
+
try { abort.abort() } catch {}
|
|
1291
|
+
try { offSession?.() } catch {}
|
|
1292
|
+
if (idle) {
|
|
1293
|
+
try {
|
|
1294
|
+
await Promise.race([
|
|
1295
|
+
idle.then(() => {}, () => {}),
|
|
1296
|
+
// Deliberately NOT unref'd: this promise is what we are awaiting, so an
|
|
1297
|
+
// unref'd timer lets the event loop drain while the await is still pending
|
|
1298
|
+
// and the caller (or the test runner) is left holding a promise that can
|
|
1299
|
+
// never settle. A <=5s hold on the loop is the correct trade.
|
|
1300
|
+
new Promise((resolve) => setTimeout(resolve, WORKER_STOP_GRACE_MS)),
|
|
1301
|
+
])
|
|
1302
|
+
} catch {}
|
|
1303
|
+
}
|
|
1304
|
+
try { await handle?.dispose?.() } catch {}
|
|
1305
|
+
}
|
|
1306
|
+
let turnEnd = null
|
|
1307
|
+
let jobId = null
|
|
1308
|
+
let scopeChanged = null
|
|
1309
|
+
let workerTools = null
|
|
1310
|
+
let workerRestriction = null
|
|
1311
|
+
// 执行器选择在 try 内赋值;finally 需要 workerMode 来决定清理口径(worker 模式
|
|
1312
|
+
// 不销毁 worker——它的生命周期归 epoch,见 §15.2 改动点 6)。
|
|
1313
|
+
let workerMode = false
|
|
1314
|
+
// worker 生命周期上绑定的 epoch abort(acquireWorker 返回)。续窗的硬停/重验必须
|
|
1315
|
+
// abort 它才停得住持久 worker——窗口级 abort 只在出生那次被宿主接进生命周期。
|
|
1316
|
+
let workerEpochAbort = null
|
|
1317
|
+
const assistantTexts = []
|
|
1318
|
+
let childId = null
|
|
1319
|
+
let accounting = null
|
|
1320
|
+
let executionContext = null
|
|
1321
|
+
// 每次整理都要在活动日志里留一条:谁触发(手动/空闲)、fork 有没有建、结果是完成、
|
|
1322
|
+
// 超时还是失败。否则"点了没反应"只能靠翻会话文件才知道发生了什么。
|
|
1323
|
+
const finish = (result) => {
|
|
1324
|
+
result = { ...result, runner: workerMode ? 'worker' : 'fork', measurement: accounting?.measurement || null }
|
|
1325
|
+
const ok = result?.ok === true
|
|
1326
|
+
const skipped = Boolean(result?.skipped)
|
|
1327
|
+
const skipText = !skipped
|
|
1328
|
+
? ''
|
|
1329
|
+
: (['small-talk', 'no-human-turn', 'no-value', 'no-new-events'].includes(result.skipped)
|
|
1330
|
+
? '跳过(没有值得记的内容)'
|
|
1331
|
+
: '跳过 · ' + result.skipped)
|
|
1332
|
+
record({
|
|
1333
|
+
kind: 'consolidate',
|
|
1334
|
+
scope: 'private',
|
|
1335
|
+
sessionId,
|
|
1336
|
+
libraryId: binding.libraryId || null,
|
|
1337
|
+
ok,
|
|
1338
|
+
level: ok ? 'info' : (result?.timedOut ? 'warn' : 'error'),
|
|
1339
|
+
message: '整理' + (ok ? (skipped ? skipText : '完成') : (result?.timedOut ? '超时' : '失败'))
|
|
1340
|
+
+ (force ? ' · 手动' : (options.trigger === 'backlog' ? ' · 水位' : ' · 空闲'))
|
|
1341
|
+
+ (result?.childId ? ' · fork ' + result.childId.slice(-8) : '')
|
|
1342
|
+
+ (result?.reasonCode ? ' · ' + result.reasonCode : '')
|
|
1343
|
+
+ (result?.error ? ':' + String(result.error) : '')
|
|
1344
|
+
+ (result?.count !== undefined ? ' · 写入 ' + result.count : '')
|
|
1345
|
+
+ (result?.wrote !== null && result?.wrote !== undefined ? ' · 索引 +' + result.wrote : '')
|
|
1346
|
+
+ (result?.scanned !== undefined ? ' · 扫描 ' + result.scanned + ' 事件 / 新 ' + (result.fresh ?? '?') : ''),
|
|
1347
|
+
detail: { force, jobId, ...result },
|
|
1348
|
+
refs: [],
|
|
1349
|
+
})
|
|
1350
|
+
return result
|
|
1351
|
+
}
|
|
1352
|
+
try {
|
|
1353
|
+
const settings = getSettings()
|
|
1354
|
+
workerMode = settings.consolidationRunner === 'worker'
|
|
1355
|
+
accounting = createConsolidationMeasurement(workerMode ? 'worker' : 'fork')
|
|
1356
|
+
// 僵尸租约先回收:进程被杀之后 inflight 会留在账本里,不能让一条死记录永久挡住这个会话。
|
|
1357
|
+
safeLedger(() => {
|
|
1358
|
+
const recovered = recoverStaleJobs()
|
|
1359
|
+
if (recovered.length > 0) {
|
|
1360
|
+
record({ kind: 'check', scope: 'private', ok: true, message: '回收 ' + recovered.length + ' 个过期整理租约', detail: { recovered } })
|
|
1361
|
+
}
|
|
1362
|
+
return recovered
|
|
1363
|
+
})
|
|
1364
|
+
|
|
1365
|
+
// 读不到会话就什么都不用谈,所以先确认快照能力,再确认 fork 能力——
|
|
1366
|
+
// 失败信息要说清缺的是哪一个(readSession/observeSession 还是 agents.create)。
|
|
1367
|
+
const sessionQuery = (() => { try { return ctx.get?.('sessionQuery') || null } catch { return null } })()
|
|
1368
|
+
if (!sessionQuery || (typeof sessionQuery.readSession !== 'function' && typeof sessionQuery.observeSession !== 'function')) {
|
|
1369
|
+
return finish({
|
|
1370
|
+
ok: false, sessionId, code: 'unavailable', reasonCode: 'no-session-query', settled: false,
|
|
1371
|
+
error: 'host has no sessionQuery.readSession / observeSession; historical consolidation is unavailable',
|
|
1372
|
+
})
|
|
1373
|
+
}
|
|
1374
|
+
const agents = ctx.get?.('agents')
|
|
1375
|
+
if (typeof agents?.create !== 'function') {
|
|
1376
|
+
return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-agents-service', settled: false, error: 'host has no agents.create; historical consolidation is unavailable' })
|
|
1377
|
+
}
|
|
1378
|
+
const buildForkSeed = workerMode ? null : await loadBuildForkSeed()
|
|
1379
|
+
if (!workerMode && !buildForkSeed) {
|
|
1380
|
+
return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-fork-seed', settled: false, error: 'dsh-session buildForkSeed is unavailable' })
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// 安全快照:cut 固定、身份可核验。未闭合的回合、没配对的工具调用、半截 step 在这里就被挡住,
|
|
1384
|
+
// rather than pass them to the worker as evidence. If a safe snapshot is unavailable,
|
|
1385
|
+
// defer the job.
|
|
1386
|
+
const captured = await captureSessionSnapshot(ctx, sessionId, { signal: abort.signal })
|
|
1387
|
+
if (!captured.ok) {
|
|
1388
|
+
if (captured.code === 'deferred') {
|
|
1389
|
+
return finish({ ok: true, sessionId, skipped: captured.reasonCode, settled: false, deferred: true, reasonCode: captured.reasonCode, detail: captured.error })
|
|
1390
|
+
}
|
|
1391
|
+
// 会话已被删除(host 回答 not found)是正常生命周期,不是整理故障:标记
|
|
1392
|
+
// sessionGone(空闲扫描从此跳过)、记 info 级 check 而不是 error——删除的
|
|
1393
|
+
// Deleted sessions are a normal lifecycle state, not a consolidation failure.
|
|
1394
|
+
if (isGoneSessionError(captured.error)) {
|
|
1395
|
+
setSessionBinding(sessionId, { sessionGone: true, sessionGoneAt: new Date().toISOString(), sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null })
|
|
1396
|
+
try { clearSessionState(sessionId) } catch {}
|
|
1397
|
+
record({
|
|
1398
|
+
kind: 'check', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
|
|
1399
|
+
message: '对话已删除,不再整理(session not found)',
|
|
1400
|
+
detail: { reasonCode: 'session-gone' },
|
|
1401
|
+
})
|
|
1402
|
+
return { ok: false, sessionId, code: 'session-gone', reasonCode: 'session-gone', settled: false, retryable: false, error: captured.error }
|
|
1403
|
+
}
|
|
1404
|
+
return finish({
|
|
1405
|
+
ok: false, sessionId, code: captured.code, reasonCode: captured.reasonCode, settled: false,
|
|
1406
|
+
retryable: captured.retryable === true, error: captured.error,
|
|
1407
|
+
})
|
|
1408
|
+
}
|
|
1409
|
+
const fullSnapshot = captured.snapshot
|
|
1410
|
+
const events = captured.events
|
|
1411
|
+
const fresh = unconsolidatedEvents(binding, events)
|
|
1412
|
+
if (events.length === 0) return finish({ ok: false, sessionId, reasonCode: 'empty-snapshot', settled: false, error: 'this session has no content to consolidate' })
|
|
1413
|
+
// A manual click on an already-settled session still re-checks the tail instead
|
|
1414
|
+
// of replaying megabytes; automatic runs only look at what the cursor has not
|
|
1415
|
+
// covered. Either way the fork gets one bounded window, not the whole log.
|
|
1416
|
+
const candidateEvents = force && fresh.length === 0 ? selectTailTurnWindow(events).events : fresh
|
|
1417
|
+
if (candidateEvents.length === 0) {
|
|
1418
|
+
return finish({ ok: true, sessionId, skipped: 'no-new-events', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
|
|
1419
|
+
}
|
|
1420
|
+
const generationAtStart = scopeGenerationOf(binding)
|
|
1421
|
+
// 待检查边界与已确认边界分开记:证据到达就记一次,失败不回退。
|
|
1422
|
+
safeLedger(() => noteEvidence({ sessionId, fromSeq: fullSnapshot.fromSeq, throughSeq: fullSnapshot.throughSeq }))
|
|
1423
|
+
|
|
1424
|
+
let value = null
|
|
1425
|
+
if (!force) {
|
|
1426
|
+
value = assessConsolidationValue(candidateEvents)
|
|
1427
|
+
// 这一批里没有真人回合、或只有一句「好的继续」:这一段确实没什么可整理的,
|
|
1428
|
+
// 是终态而不是 deferral——写入完成边界由 cycle 落到 lastSleepAt,下一次真人
|
|
1429
|
+
// 消息到达前不再重扫同一个寒暄窗口。
|
|
1430
|
+
if (!value.worth) {
|
|
1431
|
+
// A terminal policy skip advances the coarse cursor and checked range:
|
|
1432
|
+
// otherwise the same greetings stay pending forever and the sweep keeps
|
|
1433
|
+
// treating them as a real backlog.
|
|
1434
|
+
safeLedger(() => skipRange({ sessionId, snapshot: fullSnapshot, reasonCode: value.reason }))
|
|
1435
|
+
advanceSleepCursor(sessionId, fullSnapshot.throughSeq)
|
|
1436
|
+
return finish({
|
|
1437
|
+
ok: true, sessionId, skipped: value.reason, settled: true, deferred: false,
|
|
1438
|
+
reasonCode: value.reason, assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
|
|
1439
|
+
})
|
|
1440
|
+
}
|
|
1441
|
+
// 事件/回合水位:积压到一定规模就直接整理,不再等评分。它和空闲触发是
|
|
1442
|
+
// 两条腿:空闲保证收尾,水位保证一场持续几小时的会话不会攒到几千条才动。
|
|
1443
|
+
const backlog = candidateEvents.length >= CONSOLIDATION_BACKLOG_EVENTS
|
|
1444
|
+
|| Number(value.humanTurns) >= CONSOLIDATION_BACKLOG_TURNS
|
|
1445
|
+
if (options.trigger === 'backlog' && !backlog) {
|
|
1446
|
+
return finish({
|
|
1447
|
+
ok: true, sessionId, skipped: 'backlog-below-threshold', settled: false, deferred: true,
|
|
1448
|
+
reasonCode: 'backlog-below-threshold', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
|
|
1449
|
+
trigger: options.trigger,
|
|
1450
|
+
})
|
|
1451
|
+
}
|
|
1452
|
+
if (!backlog) {
|
|
1453
|
+
// 加权判定:短空闲要求分数达标,长空闲(饥饿阈值)无条件放行;
|
|
1454
|
+
// 阈值与权重集中在 lib/active-memory.js,可根据回放标定。
|
|
1455
|
+
const idleMinutes = binding.lastTurnAt ? (Date.now() - (Date.parse(binding.lastTurnAt) || Date.now())) / 60_000 : Infinity
|
|
1456
|
+
const starved = idleMinutes >= Number(settings.activeMemoryStarvationMinutes ?? ACTIVE_MEMORY_POLICY.starvationMinutes)
|
|
1457
|
+
// 小增量顺延:不 fork、不推进游标;下一次触发把这段一起带上。
|
|
1458
|
+
// 首次整理(还没有成功游标)不受限,尽快建立记忆基线;饥饿(长时间空闲)
|
|
1459
|
+
// 仍然放行,保证收尾;force 手动路径不经过这里。
|
|
1460
|
+
const firstPass = !binding.lastSleepSeq
|
|
1461
|
+
if (!starved && !firstPass && Number(value.humanTurns) < CONSOLIDATION_MIN_HUMAN_TURNS) {
|
|
1462
|
+
return finish({
|
|
1463
|
+
ok: true, sessionId, skipped: 'below-min-turns', settled: false, deferred: true,
|
|
1464
|
+
reasonCode: 'below-min-turns', assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
|
|
1465
|
+
trigger: options.trigger,
|
|
1466
|
+
})
|
|
1467
|
+
}
|
|
1468
|
+
const evidence = collectEvidence(candidateEvents)
|
|
1469
|
+
const wake = assessWake({
|
|
1470
|
+
evidence,
|
|
1471
|
+
starved,
|
|
1472
|
+
transcriptEvents: events.length,
|
|
1473
|
+
pendingEvents: candidateEvents.length,
|
|
1474
|
+
policy: { ...ACTIVE_MEMORY_POLICY, minScore: Number(settings.activeMemoryMinScore ?? ACTIVE_MEMORY_POLICY.minScore) },
|
|
1475
|
+
})
|
|
1476
|
+
record({
|
|
1477
|
+
kind: 'check',
|
|
1478
|
+
scope: 'private',
|
|
1479
|
+
sessionId,
|
|
1480
|
+
libraryId: binding.libraryId || null,
|
|
1481
|
+
ok: wake.wake,
|
|
1482
|
+
message: (wake.wake ? '主动检查触发' : '主动检查跳过')
|
|
1483
|
+
+ ' · score ' + wake.score
|
|
1484
|
+
+ ' · ' + wake.reason
|
|
1485
|
+
+ ' · 空闲 ' + (Number.isFinite(idleMinutes) ? Math.round(idleMinutes) + ' 分钟' : '未知')
|
|
1486
|
+
+ ' · 会话 ' + events.length + ' 事件'
|
|
1487
|
+
+ ' · 待整理 ' + candidateEvents.length + ' 事件'
|
|
1488
|
+
+ ' · 快照 ' + fullSnapshot.hash,
|
|
1489
|
+
detail: { trigger: options.trigger || 'idle', reason: wake.reason, score: wake.score, parts: wake.parts, starved, transcriptEvents: events.length, pendingEvents: candidateEvents.length, snapshot: snapshotMetaOf(fullSnapshot) },
|
|
1490
|
+
})
|
|
1491
|
+
if (!wake.wake) return finish({ ok: true, sessionId, skipped: 'low-score', settled: false, assessment: value, score: wake.score, parts: wake.parts, snapshot: snapshotMetaOf(fullSnapshot) })
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// One bounded window per run: the next sweep continues from the new cursor.
|
|
1496
|
+
// 失败重试(sleepAttempts>0)时窗口减半:同一游标反复超时不该每次都付整窗成本,
|
|
1497
|
+
// 前半段先结算,剩余留给下一次。
|
|
1498
|
+
const sleepAttempt = Number(binding.sleepAttempts || 0)
|
|
1499
|
+
const windowLimit = sleepAttempt > 0 ? Math.floor(CONSOLIDATION_WINDOW_EVENTS / 2) : CONSOLIDATION_WINDOW_EVENTS
|
|
1500
|
+
// Runner and model route use the same settings snapshot captured before awaits.
|
|
1501
|
+
// worker 模式按回合取窗(切在回合中间时向后补到 turn/end,避免同一回合
|
|
1502
|
+
// 被连续两窗整条重发);fork 路径窗口定义不变。
|
|
1503
|
+
let window = workerMode
|
|
1504
|
+
? selectWorkerWindow(candidateEvents, windowLimit)
|
|
1505
|
+
: selectConsolidationWindow(candidateEvents, windowLimit)
|
|
1506
|
+
if (window.events.length === 0) {
|
|
1507
|
+
return finish({ ok: true, sessionId, skipped: 'empty-window', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
|
|
1508
|
+
}
|
|
1509
|
+
const windowSnapshot = {
|
|
1510
|
+
...fullSnapshot,
|
|
1511
|
+
fromSeq: window.fromSeq,
|
|
1512
|
+
throughSeq: window.throughSeq,
|
|
1513
|
+
eventCount: window.events.length,
|
|
1514
|
+
hash: snapshotHash(window.events, window.fromSeq, window.throughSeq),
|
|
1515
|
+
}
|
|
1516
|
+
const snapshot = windowSnapshot
|
|
1517
|
+
const snapshotMeta = snapshotMetaOf(windowSnapshot)
|
|
1518
|
+
// 范围大小决定等多久:显式给了就听调用方的,没给按这一窗的事件数推。
|
|
1519
|
+
const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
|
|
1520
|
+
// 1.3.1:目录与本地召回命中在种子开头一次给全,worker 不再开只读回合。
|
|
1521
|
+
const carry = safeLedger(() => readCarryCandidates(sessionId), [])
|
|
1522
|
+
const domain = domainOf(binding)
|
|
1523
|
+
const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
|
|
1524
|
+
const seedEvents = workerMode ? null : compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
|
|
1525
|
+
memoryCatalogEvent({ ...binding, sessionId }),
|
|
1526
|
+
memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
|
|
1527
|
+
], seedLimitsFor(domain))
|
|
1528
|
+
if (!workerMode && seedEvents.length === 0) {
|
|
1529
|
+
return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
// 幂等:同一份固定快照已经结算过就不再 fork 一次(失败的部分写入靠操作键判同再试,
|
|
1533
|
+
// 而不是靠"同一个主题就跳过")。
|
|
1534
|
+
const opKey = operationKey({ sessionId, libraryId: binding.libraryId, snapshotHash: windowSnapshot.hash, scopeGeneration: generationAtStart })
|
|
1535
|
+
const previous = safeLedger(() => findOperation(sessionId, opKey))
|
|
1536
|
+
if (previous && (previous.outcome === 'completed' || previous.outcome === 'skipped')) {
|
|
1537
|
+
return finish({ ok: true, sessionId, skipped: 'already-consolidated', settled: true, snapshot: snapshotMeta, credential: previous })
|
|
1538
|
+
}
|
|
1539
|
+
// 同一份快照连续失败到上限就不再「自动」重跑:窗口已经很小,重试成本可控,但
|
|
1540
|
+
// 没有新事件的同一段转录不值得无限重试。手动整理(force)是明确的一次再决定,
|
|
1541
|
+
// 不受上限约束——否则冻结回放/用户重试都会被永久卡在同一个窗口。新消息会改变
|
|
1542
|
+
// 快照哈希,自动路径也重新获得机会。
|
|
1543
|
+
if (!force && previous?.outcome === 'failed' && Number(previous.failures) >= CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT) {
|
|
1544
|
+
// Learn unsupported effort combinations before clearing the freeze and retrying.
|
|
1545
|
+
// 清连击,本次直接放行 fork(fork 起点读不到拒绝表就会带档失败——放行前先学习,
|
|
1546
|
+
// effort 应用处读到拒绝表即不带档)。已冻结的会话由此自愈,不必等手动 force。
|
|
1547
|
+
const failureState = safeLedger(() => sessionState(sessionId), null)
|
|
1548
|
+
const lastError = failureState?.lastError ?? null
|
|
1549
|
+
const staleRefusal = effortRefusalOf(lastError)
|
|
1550
|
+
const newRefusal = staleRefusal && !isEffortRefused(staleRefusal.key)
|
|
1551
|
+
const legacyOutputLimit = (previous.reasonCode ?? failureState?.lastReasonCode) === 'fork-turn-failed'
|
|
1552
|
+
&& /^the fork turn ended max-tokens(?::|$)/.test(String(lastError || ''))
|
|
1553
|
+
const outputLimited = previous.reasonCode === 'model-output-limit' || legacyOutputLimit
|
|
1554
|
+
const execution = outputLimited ? await consolidationExecutionContext(ctx, sessionId, settings, events) : null
|
|
1555
|
+
const changedExecution = execution && (!previous.executionSettingsKey || execution.settingsKey !== previous.executionSettingsKey
|
|
1556
|
+
|| execution.defaultsComparable && execution.key !== previous.executionKey)
|
|
1557
|
+
if (!newRefusal && !changedExecution) {
|
|
1558
|
+
// 冷却(issue #4 缺陷 1):冻结超过冷却期就放行一次真实重试——连击清零交给
|
|
1559
|
+
// 下方与 newRefusal/changedExecution 共用的 recordOperation;否则维持熔断。
|
|
1560
|
+
const frozenAt = Date.parse(previous.at || '') || 0
|
|
1561
|
+
if (Date.now() - frozenAt >= CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS) {
|
|
1562
|
+
warn('consolidation freeze expired: ' + String(previous.reasonCode || 'snapshot-failed') + ' streak reset after cooldown; retrying this window')
|
|
1563
|
+
} else {
|
|
1564
|
+
// settled: false(不再假装这段已整理——那是失败熔断,不是终态跳过):
|
|
1565
|
+
// cycle.js 走 deferred 路径,不推 lastSleepAt、不清 lastSleepError,
|
|
1566
|
+
// 「整理提醒」里保持可见;冷却到期后闸门自动放行重试。
|
|
1567
|
+
const result = {
|
|
1568
|
+
ok: true, sessionId, skipped: 'snapshot-failed', settled: false, deferred: true,
|
|
1569
|
+
reasonCode: 'snapshot-failed-too-many', cooldownUntil: new Date(frozenAt + CONSOLIDATION_SNAPSHOT_FAILURE_COOLDOWN_MS).toISOString(),
|
|
1570
|
+
frozenAt: previous.at || null, snapshot: snapshotMeta, failures: Number(previous.failures) || 0, lastError,
|
|
1571
|
+
}
|
|
1572
|
+
// 冻结期活动日志去重:同一份冻结记录(按 previous.at 判同)只落一条。
|
|
1573
|
+
// cycle.js 现已用 sleepFrozenUntil 在候选阶段退避,正常不再每扫扫入;这里的
|
|
1574
|
+
// 去重兜住「冻结期新活动让路后、同哈希再次冻结」的重复返回,避免刷屏。
|
|
1575
|
+
const freezeStamp = String(previous.at || '')
|
|
1576
|
+
if (frozenLogStamps.get(opKey) !== freezeStamp) {
|
|
1577
|
+
frozenLogStamps.set(opKey, freezeStamp)
|
|
1578
|
+
return finish(result)
|
|
1579
|
+
}
|
|
1580
|
+
return result
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
if (newRefusal) {
|
|
1584
|
+
warn('consolidation unfrozen: ' + staleRefusal.key + ' was refused by the model; retrying this window without the effort')
|
|
1585
|
+
markEffortRefused(staleRefusal.key)
|
|
1586
|
+
}
|
|
1587
|
+
if (changedExecution) warn('consolidation output-limit retry: execution configuration changed or needs its first fingerprint')
|
|
1588
|
+
safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: previous.ids || [] }))
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// 工具面必须可验证:父会话这一轮真实发给模型的工具表里若没有记忆写工具,
|
|
1592
|
+
// A safe snapshot and a verified write-tool surface are required before starting work.
|
|
1593
|
+
const probe = probeToolSurface({ ctx, sessionId, events })
|
|
1594
|
+
if (!probe.ok) {
|
|
1595
|
+
return finish({
|
|
1596
|
+
ok: false, sessionId, code: 'unavailable', reasonCode: probe.reasonCode, settled: false, retryable: false,
|
|
1597
|
+
toolSurface: probe.tools || null, ptc: probe.ptcObserved === true,
|
|
1598
|
+
error: 'this conversation exposes no memory write tool to the model (' + String(probe.source || 'unknown') + '), so a consolidation worker could not write anything; consolidation is unavailable until the session has memu_private_remember / memu_private_update',
|
|
1599
|
+
})
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
jobId = 'cons-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
|
|
1603
|
+
// Let the lease track the execution budget plus its recovery margin.
|
|
1604
|
+
// 走不到超时路径就死的任务(插件重启 / fork 被外力杀掉)不会调 failJob,
|
|
1605
|
+
// 固定 15 分钟租约让该会话的重试一直撞 lease-held;预算封顶 600s,
|
|
1606
|
+
// 租约最迟在真死后 ~90s 由 recoverStaleJobs 回收,而不是再等 9 分钟。
|
|
1607
|
+
const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding, leaseMs: budgetMs + 90_000 }))
|
|
1608
|
+
if (!begun) {
|
|
1609
|
+
return finish({
|
|
1610
|
+
ok: false, sessionId, settled: false, retryable: true, reasonCode: 'ledger-unavailable',
|
|
1611
|
+
error: 'the consolidation lease could not be persisted; no worker was created',
|
|
1612
|
+
})
|
|
1613
|
+
}
|
|
1614
|
+
if (begun.ok !== true) {
|
|
1615
|
+
return finish({
|
|
1616
|
+
ok: false, sessionId, running: true, settled: false, reasonCode: 'lease-held',
|
|
1617
|
+
error: 'this session already holds a consolidation lease (' + String(begun.jobId) + ' until ' + new Date(begun.leaseUntil).toISOString() + '); the previous run is still unaccounted for — the lease self-heals when it expires, then the range is retried on the next sweep',
|
|
1618
|
+
})
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
const header = captured.header || {}
|
|
1622
|
+
// 每次整理都留"看了多少、新的多少、真正写了几条",否则"0 记忆"无法定位是
|
|
1623
|
+
// 没触发、被门挡住还是提取空转。
|
|
1624
|
+
const freshCount = fresh.length
|
|
1625
|
+
let beforeIds = null
|
|
1626
|
+
let beforeEntries = null
|
|
1627
|
+
try {
|
|
1628
|
+
const beforeIndex = loadPrivateIndex(binding.libraryId)
|
|
1629
|
+
beforeIds = new Set(Object.keys(beforeIndex.entries))
|
|
1630
|
+
beforeEntries = Object.fromEntries(Object.entries(beforeIndex.entries).map(([id, entry]) => [id, entryFingerprint(entry)]))
|
|
1631
|
+
} catch { beforeIds = null; beforeEntries = null }
|
|
1632
|
+
|
|
1633
|
+
// 整理 fork 的模型选择(三模式,lib/fork-model.js)。inherit 保持原路径逐字节一致;
|
|
1634
|
+
// host 直接指名宿主已激活 route;custom 要先在宿主 llm 注册表确认本插件私有 route
|
|
1635
|
+
// 可用(能力缺失/注册失败/服务性探测不过 → 降级回 inherit 或拒绝本次整理,warn 一
|
|
1636
|
+
// 行,绝不 fail closed)。fork 的 AgentOptions 没有 baseURL/apiKey 通道,custom 的
|
|
1637
|
+
// 自定义端点只能走注册 route。(settings 已在窗口选择处读取。)
|
|
1638
|
+
//
|
|
1639
|
+
// host/custom 不需要父会话 route:这里不探测父会话,也避免 inheritedAgentOptions 的
|
|
1640
|
+
// resume 回退把父会话挂成宿主活视图——活视图会钉住 sessionQuery 的快照,外部追加的
|
|
1641
|
+
// persistent log would remain unread. Probe lazily only if the custom route fails.
|
|
1642
|
+
const modelModeSetting = settings.consolidationModelMode || 'inherit'
|
|
1643
|
+
let inherited = null
|
|
1644
|
+
if (modelModeSetting !== 'host' && modelModeSetting !== 'custom') {
|
|
1645
|
+
inherited = await inheritedAgentOptions(ctx, sessionId, events)
|
|
1646
|
+
}
|
|
1647
|
+
const resolved = resolveConsolidationAgentOptions(settings, inherited)
|
|
1648
|
+
let agentOptions = resolved.options
|
|
1649
|
+
let modelMode = resolved.reason
|
|
1650
|
+
if (!agentOptions) {
|
|
1651
|
+
// no-inherited-route 与旧失败路径逐字节一致(inherit 模式语义不变);host/custom
|
|
1652
|
+
// 的坏配置各自带 reasonCode,整理提醒能直接说清是哪个配置面写错了。
|
|
1653
|
+
if (resolved.reason === 'no-inherited-route') {
|
|
1654
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'no-parent-route', retryable: true, error: 'cannot inherit the parent model/provider' }))
|
|
1655
|
+
return finish({ ok: false, sessionId, reasonCode: 'no-parent-route', settled: false, error: 'cannot inherit the parent model/provider; consolidation fork was not created' })
|
|
1656
|
+
}
|
|
1657
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: resolved.reason, retryable: true, error: 'cannot resolve the consolidation model (' + resolved.reason + ')' }))
|
|
1658
|
+
return finish({ ok: false, sessionId, reasonCode: resolved.reason, settled: false, error: 'cannot resolve the consolidation model (' + resolved.reason + '); consolidation fork was not created' })
|
|
1659
|
+
}
|
|
1660
|
+
if (resolved.reason === 'custom') {
|
|
1661
|
+
// 每次整理都重挂一次(先卸旧再注册,设置变更自然生效);成功后才允许 fork 指名
|
|
1662
|
+
// dsh-memu-custom。失败降级:有父 route 就回 inherit,没有就只能拒绝。
|
|
1663
|
+
const ensured = await ensureConsolidationRoute(ctx, settings)
|
|
1664
|
+
if (!ensured.ok) {
|
|
1665
|
+
warn('consolidation custom model route unavailable (' + ensured.reason + (ensured.error ? ': ' + ensured.error : '') + '); falling back to the inherited route')
|
|
1666
|
+
if (!inherited) inherited = await inheritedAgentOptions(ctx, sessionId, events)
|
|
1667
|
+
if (inherited) {
|
|
1668
|
+
agentOptions = inherited
|
|
1669
|
+
modelMode = 'inherit-fallback'
|
|
1670
|
+
} else {
|
|
1671
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'custom-route-unavailable', retryable: true, error: 'the custom consolidation route is unavailable (' + ensured.reason + ')' }))
|
|
1672
|
+
return finish({ ok: false, sessionId, reasonCode: 'custom-route-unavailable', settled: false, error: 'the custom consolidation route is unavailable (' + ensured.reason + '); consolidation fork was not created' })
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
// 最终 route(含 custom 回退)确定后再覆盖档位、过滤实际生效的组合。
|
|
1678
|
+
// inherit 也可能从父 options 带入被拒档位;只克隆子 options,不改父对象或其它参数。
|
|
1679
|
+
const effort = settings.consolidationReasoningEffort
|
|
1680
|
+
if (effort && effort !== 'inherit') agentOptions = { ...agentOptions, reasoningEffort: effort }
|
|
1681
|
+
const effectiveEffort = agentOptions.reasoningEffort
|
|
1682
|
+
if (effectiveEffort && isEffortRefused([agentOptions.provider, agentOptions.model, effectiveEffort].join('|'))) {
|
|
1683
|
+
warn('consolidation reasoning effort ' + effectiveEffort + ' previously refused by ' + agentOptions.provider + '/' + agentOptions.model + ' — starting the worker/fork without it')
|
|
1684
|
+
agentOptions = { ...agentOptions }
|
|
1685
|
+
delete agentOptions.reasoningEffort
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
// The executor mode is determined when the window is selected. 'fork' remains the
|
|
1689
|
+
// default; an explicit 'worker' selection uses the persistent worker pool.
|
|
1690
|
+
executionContext = await consolidationExecutionContext(ctx, sessionId, settings, events, modelMode === 'inherit' ? agentOptions : null)
|
|
1691
|
+
let workerAcquired = null
|
|
1692
|
+
let workerEpochRecord = null
|
|
1693
|
+
let workerIncrement = null
|
|
1694
|
+
let dispatchText = null
|
|
1695
|
+
let dispatchKind = 'fork'
|
|
1696
|
+
if (workerMode) {
|
|
1697
|
+
const workerBinding = { ...binding, sessionId }
|
|
1698
|
+
workerIncrement = loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
|
|
1699
|
+
if (!workerIncrement.text.trim()) {
|
|
1700
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'empty-increment', retryable: true }))
|
|
1701
|
+
return finish({ ok: false, sessionId, settled: false, retryable: true, reasonCode: 'empty-increment', error: 'no readable worker increment; the range stays pending' })
|
|
1702
|
+
}
|
|
1703
|
+
const current = getSessionBinding(sessionId) || binding
|
|
1704
|
+
const privatePrompt = buildPrivateConsolidationPrompt(sessionId)
|
|
1705
|
+
const common = {
|
|
1706
|
+
sessionId, binding: workerBinding, snapshot, probe, jobId,
|
|
1707
|
+
reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly), mustCover,
|
|
1708
|
+
contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
|
|
1709
|
+
incrementRecords: workerIncrement.records,
|
|
1710
|
+
incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
|
|
1711
|
+
digest: workerIncrement.digest, catalog: memoryCatalogEvent(workerBinding),
|
|
1712
|
+
domain,
|
|
1713
|
+
sceneTime: current.sceneTime || binding.sceneTime || null,
|
|
1714
|
+
pendingNote: Boolean(current.consolidationPending), pendingHash: current.consolidationPending?.snapshotHash || null,
|
|
1715
|
+
carry: mustCover, lastSleepSeq: binding.lastSleepSeq ?? null,
|
|
1716
|
+
}
|
|
1717
|
+
const buildPacket = (acquired) => {
|
|
1718
|
+
dispatchKind = acquired.birth ? 'handoff' : 'increment'
|
|
1719
|
+
const pack = acquired.birth ? buildHandoffPack({
|
|
1720
|
+
...common, includeTail: acquired.handoff !== false, writtenRows: acquired.handoff === false ? [] : null,
|
|
1721
|
+
}) : buildIncrementPack(common)
|
|
1722
|
+
return acquired.birth ? [privatePrompt, '', pack].join('\n') : pack
|
|
1723
|
+
}
|
|
1724
|
+
const acquireOptions = { settings, probe, agentOptions, header, agentPreset: captured.agentPreset }
|
|
1725
|
+
workerAcquired = await acquireWorker(ctx, workerBinding, acquireOptions)
|
|
1726
|
+
if (workerAcquired.ok) {
|
|
1727
|
+
dispatchText = buildPacket(workerAcquired)
|
|
1728
|
+
let packet = measurePacket(dispatchText, dispatchKind)
|
|
1729
|
+
if (!packetBudgetFit(workerAcquired.epoch, packet, settings) && !workerAcquired.birth) {
|
|
1730
|
+
// The final text, not just the pending increment, must fit. Rebuild at
|
|
1731
|
+
// most once, since a handoff includes extra identity/settled-tail text.
|
|
1732
|
+
await retireWorker(ctx, workerAcquired.forkId, 'packet-budget', { handoff: true })
|
|
1733
|
+
workerAcquired = await acquireWorker(ctx, workerBinding, { ...acquireOptions, afterEpochIndex: workerAcquired.epoch.index })
|
|
1734
|
+
if (workerAcquired.ok) {
|
|
1735
|
+
dispatchText = buildPacket(workerAcquired)
|
|
1736
|
+
packet = measurePacket(dispatchText, dispatchKind)
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
if (workerAcquired.ok && !packetBudgetFit(workerAcquired.epoch, packet, settings)) {
|
|
1740
|
+
accounting.measurement.packet = { ...packet, dispatched: false }
|
|
1741
|
+
await retireWorker(ctx, workerAcquired.forkId, 'packet-too-large', { handoff: false })
|
|
1742
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'packet-too-large', retryable: true, error: 'the complete first packet exceeds the worker epoch budget' }))
|
|
1743
|
+
return finish({ ok: false, sessionId, childId: workerAcquired.forkId, settled: false, retryable: true, reasonCode: 'packet-too-large', error: 'the complete worker packet is too large; the range stays pending (no automatic unsafe truncation)' })
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
if (!workerAcquired.ok) {
|
|
1747
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed', retryable: true, error: workerAcquired.error || null }))
|
|
1748
|
+
return finish({
|
|
1749
|
+
ok: false, sessionId, settled: false, retryable: true,
|
|
1750
|
+
reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed',
|
|
1751
|
+
error: workerAcquired.error || 'the consolidation worker could not be acquired',
|
|
1752
|
+
})
|
|
1753
|
+
}
|
|
1754
|
+
childId = workerAcquired.forkId
|
|
1755
|
+
handle = workerAcquired.handle
|
|
1756
|
+
workerTools = workerAcquired.tools
|
|
1757
|
+
workerRestriction = workerAcquired.restriction
|
|
1758
|
+
workerEpochRecord = workerAcquired.epoch
|
|
1759
|
+
workerEpochAbort = workerAcquired.epochAbort || null
|
|
1760
|
+
accounting = createConsolidationMeasurement('worker', { sessionId: childId, afterSeq: workerAcquired.eventCursor ?? workerEpochRecord.lastEventSeq })
|
|
1761
|
+
} else {
|
|
1762
|
+
childId = 'memu-consolidate-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
|
|
1763
|
+
// 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
|
|
1764
|
+
// 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
|
|
1765
|
+
// 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
|
|
1766
|
+
// 保留仍存在的会话 cwd;旧目录失效时回退 dataDir,避免宿主拒绝启动回合。
|
|
1767
|
+
const forkCwd = resolveConsolidationCwd(header.cwd)
|
|
1768
|
+
const presetSelection = resolveConsolidationPreset(ctx, { sessionId, presetId: captured.agentPreset })
|
|
1769
|
+
try {
|
|
1770
|
+
handle = await agents.create({
|
|
1771
|
+
sessionId: childId,
|
|
1772
|
+
meta: {
|
|
1773
|
+
cwd: forkCwd,
|
|
1774
|
+
parentSession: sessionId,
|
|
1775
|
+
isSeeded: true,
|
|
1776
|
+
// Without this the fork is treated as an ordinary user conversation by
|
|
1777
|
+
// the injection path and the sidebar session lists.
|
|
1778
|
+
origin: 'subagent',
|
|
1779
|
+
// Use the session's active preset rather than immutable creation metadata.
|
|
1780
|
+
// Later preset selections are recorded by agent-preset/selected events.
|
|
1781
|
+
// Apply the event projection when choosing the fork preset.
|
|
1782
|
+
agentPreset: presetSelection.presetId,
|
|
1783
|
+
},
|
|
1784
|
+
inheritedEventCount: seedEvents.length,
|
|
1785
|
+
seed: buildForkSeed(seedEvents, seedEvents.length - 1),
|
|
1786
|
+
agentOptions,
|
|
1787
|
+
// 只写 meta.agentPreset 不会挂载预设(agent-loop 从不读它),fork 会跑根组合、
|
|
1788
|
+
// 整理出来的记忆不带那个人格的口吻。setup 里 mount 才是真挂上。
|
|
1789
|
+
setup: presetSetupFor(ctx, { selection: presetSelection, log: message => { try { ctx.logger?.warn?.('dsh-memu-memory: ' + message) } catch {} }, }),
|
|
1790
|
+
signal: abort.signal,
|
|
1791
|
+
})
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
// 宿主拒绝种子时最需要的诊断信息就在这条错误里("seed event at index …"),
|
|
1794
|
+
// 用独立 reasonCode 写进活动日志,别让它塌成一句 exception。
|
|
1795
|
+
const failure = String(error?.message || error)
|
|
1796
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-create-failed', retryable: true, error: failure }))
|
|
1797
|
+
return finish({
|
|
1798
|
+
ok: false, sessionId, childId, settled: false, retryable: true,
|
|
1799
|
+
reasonCode: 'fork-create-failed',
|
|
1800
|
+
error: 'the host rejected the consolidation fork: ' + failure,
|
|
1801
|
+
})
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
// header 无法证明 worker 有写工具时(PTC 会话名单只有 run_code / 旧会话没有名单),
|
|
1806
|
+
// 把 worker 读写面挂进 fork 自己的 scope,保证 SDK 面(PTC)与原生面(普通会话)都真能写入。
|
|
1807
|
+
// 标准 preset 的 fork 名单里已有 memu_*(probe.hasWrite === true),不重复挂。
|
|
1808
|
+
// worker 模式:工具面只在初生挂一次(acquireWorker 内部处理),续窗跳过(§15.2 改动点 2)。
|
|
1809
|
+
if (!workerMode) {
|
|
1810
|
+
if (probe.hasWrite !== true) {
|
|
1811
|
+
workerTools = await attachWorkerTools(agents, childId, sessionId)
|
|
1812
|
+
}
|
|
1813
|
+
workerRestriction = await restrictWorkerTools(agents, childId, sessionId)
|
|
1814
|
+
}
|
|
1815
|
+
// Counters are shared by fork/worker; only the latter persists an epoch.
|
|
1816
|
+
if (!workerMode) {
|
|
1817
|
+
accounting = createConsolidationMeasurement('fork', { sessionId: childId })
|
|
1818
|
+
const brief = buildWorkerBrief({
|
|
1819
|
+
snapshot, probe, jobId, mustCover, autoReceipt: true, domain,
|
|
1820
|
+
contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
|
|
1821
|
+
reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly),
|
|
1822
|
+
})
|
|
1823
|
+
dispatchText = [buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n')
|
|
1824
|
+
}
|
|
1825
|
+
accounting.measurement.packet = measurePacket(dispatchText, dispatchKind)
|
|
1826
|
+
|
|
1827
|
+
// 先记"已开始"再等结果:一个大会话的 fork 可能跑好几分钟,没有这条记录,
|
|
1828
|
+
// 侧边栏和日志页在等待期间只会显示上一次的结果,用户会以为按钮没生效。
|
|
1829
|
+
record({
|
|
1830
|
+
kind: 'consolidate',
|
|
1831
|
+
scope: 'private',
|
|
1832
|
+
sessionId,
|
|
1833
|
+
libraryId: binding.libraryId || null,
|
|
1834
|
+
ok: true,
|
|
1835
|
+
message: '整理已开始 · ' + (force ? '手动' : (options.trigger === 'backlog' ? '水位' : '空闲'))
|
|
1836
|
+
+ ' · fork ' + childId.slice(-8)
|
|
1837
|
+
+ ' · 窗口 ' + window.events.length + ' 条事件(父会话 ' + events.length + ' 条 / 新 ' + freshCount + ' 条)'
|
|
1838
|
+
+ (window.remaining > 0 ? ' · 还余 ' + window.remaining : '')
|
|
1839
|
+
+ ' · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
|
|
1840
|
+
detail: { childId, jobId, force, trigger: options.trigger || 'idle', events: window.events.length, transcriptEvents: events.length, fresh: freshCount, remaining: window.remaining, budgetMs, phase: 'started', snapshot: snapshotMeta,
|
|
1841
|
+
modelMode, runner: workerMode ? 'worker' : 'fork', measurement: accounting.measurement,
|
|
1842
|
+
probe: { source: probe.source, hasWrite: probe.hasWrite, ptc: probe.ptcObserved === true },
|
|
1843
|
+
...workerToolsMeta(workerTools) },
|
|
1844
|
+
})
|
|
1845
|
+
|
|
1846
|
+
// turn/end 是这一轮的唯一权威结果;whenIdle 只说明 driver 停了(失败的回合也停)。
|
|
1847
|
+
// 顺带从同一个公共事件流里收三样东西:worker 的正文(回执在里面)、
|
|
1848
|
+
// 它的工具动作(用来在写入途中重验父授权),以及父会话自己是否动过。
|
|
1849
|
+
const childSession = handle?.agent?.session
|
|
1850
|
+
const parentAgent = (() => { try { return agents.get?.(sessionId) || null } catch { return null } })()
|
|
1851
|
+
const parentLive = parentAgent?.session || null
|
|
1852
|
+
const isParentSession = (session) => session === parentLive || (session && parentLive === null && session?.id === sessionId)
|
|
1853
|
+
const revalidate = (source) => {
|
|
1854
|
+
if (scopeChanged) return
|
|
1855
|
+
const now = scopeGenerationOf(getSessionBinding(sessionId))
|
|
1856
|
+
if (!generationAtStart || now === generationAtStart) return
|
|
1857
|
+
scopeChanged = { source, expected: generationAtStart, actual: now }
|
|
1858
|
+
record({
|
|
1859
|
+
kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: false, level: 'warn',
|
|
1860
|
+
message: '整理作废:父会话授权变化(' + source + ')',
|
|
1861
|
+
detail: { jobId, childId, ...scopeChanged },
|
|
1862
|
+
})
|
|
1863
|
+
try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
|
|
1864
|
+
}
|
|
1865
|
+
if (typeof ctx.on === 'function' && childSession) {
|
|
1866
|
+
try {
|
|
1867
|
+
offSession = ctx.on('session/event', (session, event) => {
|
|
1868
|
+
if (session === childSession) {
|
|
1869
|
+
if (!accounting.observe(event)) return
|
|
1870
|
+
if (event?.type === 'turn/end') { turnEnd = event; return }
|
|
1871
|
+
if (event?.type === 'assistant/message') {
|
|
1872
|
+
const blocks = event?.data?.message?.content
|
|
1873
|
+
if (Array.isArray(blocks)) {
|
|
1874
|
+
for (const block of blocks) {
|
|
1875
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
|
|
1876
|
+
assistantTexts.push(block.text)
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
return
|
|
1881
|
+
}
|
|
1882
|
+
// 工具动作是写入的落点:每出现一次就重验一次父授权,变了立刻停掉这条 fork。
|
|
1883
|
+
if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
|
|
1884
|
+
revalidate('worker-write')
|
|
1885
|
+
workerToolRounds += 1
|
|
1886
|
+
if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
|
|
1887
|
+
// worker 模式 abort 的是绑在生命周期上的 epoch 控制器,硬停才真正生效;
|
|
1888
|
+
// 回合以 aborted 收尾 → turnEndFailure → 退役。fork 模式仍 abort 窗口 signal。
|
|
1889
|
+
try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
|
|
1890
|
+
} else {
|
|
1891
|
+
const guidance = workerRoundGuidance(workerToolRounds)
|
|
1892
|
+
if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
|
|
1893
|
+
try {
|
|
1894
|
+
const queued = handle.agent.followup(noticeMessage(guidance.text, '整理收尾提示'))
|
|
1895
|
+
accounting.dispatch(guidance.text, 'wrapup')
|
|
1896
|
+
Promise.resolve(queued).catch((error) => warn('consolidation wrapup followup failed: ' + describeError(error)))
|
|
1897
|
+
} catch (error) { warn('consolidation wrapup followup failed: ' + describeError(error)) }
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
return
|
|
1901
|
+
}
|
|
1902
|
+
return
|
|
1903
|
+
}
|
|
1904
|
+
// 用户又说话了:父会话的库/域/上下文可能已经被切换,重新比一次指纹。
|
|
1905
|
+
if (isParentSession(session) && (event?.type === 'turn/start' || event?.type === 'user/message')) revalidate('parent-activity')
|
|
1906
|
+
})
|
|
1907
|
+
} catch {}
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
// The fork must write into the parent's library, not derive one from its own
|
|
1911
|
+
// freshly minted session id.
|
|
1912
|
+
setSessionBinding(childId, {
|
|
1913
|
+
libraryId: binding.libraryId,
|
|
1914
|
+
consolidationFork: true,
|
|
1915
|
+
// 整理发生在几小时后,父会话此刻的心境不是这段转录里那件事的情绪,所以 fork
|
|
1916
|
+
// 不继承 mood。显式写 null 而不是留空:缺字段和「这一刻是中性」在写入时都走
|
|
1917
|
+
// 同一条兜底,但只有 null 能把「后台 worker 没有当下心境」说清楚。
|
|
1918
|
+
mood: null,
|
|
1919
|
+
// The fork writes memories on the same logical clock as its parent. Without
|
|
1920
|
+
// this the worker falls back to the wall clock at fork time; the per-turn
|
|
1921
|
+
// [事件时间] markers in the seed remain the authoritative override.
|
|
1922
|
+
sceneTime: binding.sceneTime || null,
|
|
1923
|
+
parentSessionId: sessionId,
|
|
1924
|
+
parentScopeGeneration: generationAtStart,
|
|
1925
|
+
snapshotHash: snapshot.hash,
|
|
1926
|
+
// 调试/测试用:worker 的回执范围必须和这两项一致,否则 completeJob 不会推进。
|
|
1927
|
+
snapshotFromSeq: snapshot.fromSeq,
|
|
1928
|
+
snapshotThroughSeq: snapshot.throughSeq,
|
|
1929
|
+
snapshotEventCount: snapshot.eventCount,
|
|
1930
|
+
jobId,
|
|
1931
|
+
scopeKey: binding.scopeKey,
|
|
1932
|
+
memoryOwnerSessionId: binding.memoryOwnerSessionId || sessionId,
|
|
1933
|
+
memoryContext: binding.memoryContext || {},
|
|
1934
|
+
useLibrary: true,
|
|
1935
|
+
useGlobal: binding.useGlobal === true,
|
|
1936
|
+
domain: binding.domain,
|
|
1937
|
+
domainOverride: binding.domainOverride || null,
|
|
1938
|
+
})
|
|
1939
|
+
// worker 模式(§15.2 改动点 3):子绑定补 epoch 副本;sceneTime 每窗重读父绑定
|
|
1940
|
+
// (RP 剧情可能推进;现状 fork 是诞生时定死一次,worker 路径每窗刷新,§6)。
|
|
1941
|
+
if (workerMode && workerEpochRecord) {
|
|
1942
|
+
const sceneTimeNow = (() => {
|
|
1943
|
+
try { return getSessionBinding(sessionId)?.sceneTime || binding.sceneTime || null } catch { return binding.sceneTime || null }
|
|
1944
|
+
})()
|
|
1945
|
+
setSessionBinding(childId, { workerEpoch: workerEpochRecord, sceneTime: sceneTimeNow })
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// 写入前最后一次重验:这次的授权还成立吗?不成立就别把 prompt 发出去。
|
|
1949
|
+
revalidate('pre-dispatch')
|
|
1950
|
+
if (scopeChanged) {
|
|
1951
|
+
// worker 模式:scope 已污染,立即退役且不交接(§4.5 条件 1)。
|
|
1952
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
|
|
1953
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope before dispatch' }))
|
|
1954
|
+
return finish({
|
|
1955
|
+
ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
|
|
1956
|
+
error: 'the parent conversation switched library, scope or memory context before the worker was dispatched; nothing was credited',
|
|
1957
|
+
})
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
// Measure exactly the final followup text, including all separators/briefs.
|
|
1961
|
+
handle.agent.followup(noticeMessage(dispatchText, '整理这场对话的私有记忆'))
|
|
1962
|
+
accounting.dispatch(dispatchText, dispatchKind)
|
|
1963
|
+
// followup only queues. whenIdle says the driver stopped; turn/end says
|
|
1964
|
+
// whether that turn actually succeeded, so both are checked below.
|
|
1965
|
+
idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
|
|
1966
|
+
let timer = null
|
|
1967
|
+
let outcome
|
|
1968
|
+
try {
|
|
1969
|
+
const wait = new Promise((resolve) => { timer = setTimeout(() => resolve('timeout'), budgetMs) })
|
|
1970
|
+
outcome = await Promise.race([idle.then(() => 'done'), wait])
|
|
1971
|
+
} finally { clearTimeout(timer) }
|
|
1972
|
+
|
|
1973
|
+
// worker 模式 epoch 记账(§4.5/§15.2 改动点 3):本窗增量 + 观测到的 worker 产出
|
|
1974
|
+
// 并入 chars、windows +1;whenIdle 正常完成记 lastIdleAt(条件 4 的 TTL 起算点)。
|
|
1975
|
+
// 结算成功后的超时清零在 completeJob 之后单独落一次。
|
|
1976
|
+
if (workerMode) {
|
|
1977
|
+
workerEpochRecord = recordEpochProgress({ sessionId }, {
|
|
1978
|
+
measurement: accounting.measurement,
|
|
1979
|
+
idleAt: outcome === 'done' ? Date.now() : null,
|
|
1980
|
+
}) || workerEpochRecord
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
let wrote = null
|
|
1984
|
+
let decision = null
|
|
1985
|
+
let completion = null
|
|
1986
|
+
if (outcome === 'done') {
|
|
1987
|
+
const failure = turnEndFailure(turnEnd)
|
|
1988
|
+
if (failure) {
|
|
1989
|
+
// batch 参数的 JSON 畸形是模型生成问题,不是整理逻辑故障:标记下一次
|
|
1990
|
+
// 只用逐条 remember,并让重试路径接住(consolidateAll 已有 2 次重试)。
|
|
1991
|
+
const batchJsonInvalid = /memu_private_remember_batch/.test(String(failure))
|
|
1992
|
+
&& /JSON|Expected ','|after array element/.test(String(failure))
|
|
1993
|
+
const outputLimited = turnEnd?.data?.reason?.kind === 'max-tokens'
|
|
1994
|
+
const execution = outputLimited ? executionContext : null
|
|
1995
|
+
const reasonCode = outputLimited ? 'model-output-limit' : batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
|
|
1996
|
+
const outputLimitError = outputLimited
|
|
1997
|
+
? failure + '; 输出预算不足(含思考/剩余上下文限制),请调整宿主最大输出 token 或使用模型支持的思考档位;待处理范围未结算'
|
|
1998
|
+
: failure
|
|
1999
|
+
// 思考强度不被支持 = 配置与模型不匹配,失败发生在回合起点、代价极小:
|
|
2000
|
+
// 学习该组合(下次 fork 不带档)并把本次标记可重试,让下一次扫描很快接住。
|
|
2001
|
+
const effortRefusal = effortRefusalOf(failure)
|
|
2002
|
+
if (effortRefusal) {
|
|
2003
|
+
markEffortRefused(effortRefusal.key)
|
|
2004
|
+
// 同时清掉该快照的失败连击:失败是配置不匹配(已学习),不是这段转录有病——
|
|
2005
|
+
// 不清零的话 snapshot-failed-too-many 闸门会让自动重试永远进不来。
|
|
2006
|
+
safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: [] }))
|
|
2007
|
+
}
|
|
2008
|
+
if (batchJsonInvalid) setSessionBinding(sessionId, { consolidationSingleOnly: true })
|
|
2009
|
+
// worker 模式:回合失败即退役条件 5,不带病工作、不做交接(§4.5)。
|
|
2010
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
|
|
2011
|
+
const retryable = outputLimited || batchJsonInvalid || Boolean(effortRefusal)
|
|
2012
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable, error: outputLimitError, executionKey: execution?.key || null, executionSettingsKey: execution?.settingsKey || null, executionDefaultsComparable: execution?.defaultsComparable ?? true }))
|
|
2013
|
+
return finish({
|
|
2014
|
+
ok: false, error: 'consolidation fork failed: ' + outputLimitError, sessionId, childId,
|
|
2015
|
+
settled: false, timedOut: false, retryable, reasonCode,
|
|
2016
|
+
...(outputLimited ? { configuredMaxTokens: agentOptions.maxTokens ?? execution.maxTokens } : {}),
|
|
2017
|
+
})
|
|
2018
|
+
}
|
|
2019
|
+
// 父授权重验:写入可能已经落了一部分,但凭证只有在授权还成立时才算数。
|
|
2020
|
+
const generationNow = scopeGenerationOf(getSessionBinding(sessionId))
|
|
2021
|
+
if (scopeChanged || (generationAtStart && generationNow !== generationAtStart)) {
|
|
2022
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
|
|
2023
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope during consolidation' }))
|
|
2024
|
+
return finish({
|
|
2025
|
+
ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
|
|
2026
|
+
error: 'the parent conversation switched library, scope or memory context while the worker was running; the result was not credited (writes that already landed stay in the library, the range stays pending)',
|
|
2027
|
+
})
|
|
2028
|
+
}
|
|
2029
|
+
// 兼容字段 lastSleepSeq 只能跟着凭证走:没有对账过的结果就不算整理过,
|
|
2030
|
+
// Otherwise the legacy cursor could mark failed work as completed.
|
|
2031
|
+
if (beforeIds) {
|
|
2032
|
+
try {
|
|
2033
|
+
const afterIds = Object.keys(loadPrivateIndex(binding.libraryId).entries)
|
|
2034
|
+
wrote = afterIds.filter((id) => !beforeIds.has(id)).length
|
|
2035
|
+
} catch { wrote = null }
|
|
2036
|
+
}
|
|
2037
|
+
let index = null
|
|
2038
|
+
try { index = loadPrivateIndex(binding.libraryId) } catch { index = null }
|
|
2039
|
+
// 完成不是"没报错":worker 的回执 + 库里的真实变化,两边对上才结算。
|
|
2040
|
+
const workerText = assistantTexts.join('\n')
|
|
2041
|
+
decision = decideCompletion({
|
|
2042
|
+
text: workerText,
|
|
2043
|
+
wrote,
|
|
2044
|
+
index,
|
|
2045
|
+
beforeIds,
|
|
2046
|
+
beforeEntries,
|
|
2047
|
+
expectedJobId: jobId,
|
|
2048
|
+
expectedSnapshotHash: snapshot.hash,
|
|
2049
|
+
autoReceipt: { jobId, snapshotHash: snapshot.hash, checkedRange: { fromSeq: snapshot.fromSeq, throughSeq: snapshot.throughSeq } },
|
|
2050
|
+
})
|
|
2051
|
+
|
|
2052
|
+
if (!decision.advance) {
|
|
2053
|
+
// worker 模式:对账不过 = 退役条件 5(无交接);已写入的条目保留,区间回 pending。
|
|
2054
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
|
|
2055
|
+
safeLedger(() => failJob({
|
|
2056
|
+
sessionId, jobId, reasonCode: decision.reasonCode || 'not-settled',
|
|
2057
|
+
retryable: decision.retryable !== false, error: decision.error || null,
|
|
2058
|
+
}))
|
|
2059
|
+
return finish({
|
|
2060
|
+
ok: false, sessionId, childId, settled: false, retryable: decision.retryable !== false,
|
|
2061
|
+
status: decision.status, outcome: decision.outcome, reasonCode: decision.reasonCode,
|
|
2062
|
+
counts: decision.counted || null, snapshot: snapshotMeta,
|
|
2063
|
+
error: decision.error || ('consolidation result was not verified: ' + String(decision.reasonCode || 'unknown')),
|
|
2064
|
+
})
|
|
2065
|
+
}
|
|
2066
|
+
completion = safeLedger(() => completeJob({
|
|
2067
|
+
sessionId, jobId, snapshot,
|
|
2068
|
+
covered: decision.covered,
|
|
2069
|
+
status: decision.status,
|
|
2070
|
+
outcome: decision.outcome,
|
|
2071
|
+
reasonCode: decision.reasonCode,
|
|
2072
|
+
retryable: decision.retryable === true,
|
|
2073
|
+
counts: decision.counted,
|
|
2074
|
+
receipt: decision.receipt,
|
|
2075
|
+
}))
|
|
2076
|
+
if (!completion?.advanced) {
|
|
2077
|
+
return finish({ ok: false, sessionId, childId, settled: false, retryable: true,
|
|
2078
|
+
reasonCode: 'ledger-not-advanced', snapshot: snapshotMeta,
|
|
2079
|
+
error: 'the consolidation ledger could not verify the covered snapshot range' })
|
|
2080
|
+
}
|
|
2081
|
+
advanceSleepCursor(sessionId, snapshot.throughSeq, { consolidationSingleOnly: false })
|
|
2082
|
+
// worker 模式:结算成功清超时连击、清「上窗未结算」标记(下一窗增量包不再带核对说明)。
|
|
2083
|
+
if (workerMode) {
|
|
2084
|
+
workerEpochRecord = recordEpochProgress({ sessionId }, { settled: true, progress: false }) || workerEpochRecord
|
|
2085
|
+
setSessionBinding(sessionId, { consolidationPending: null })
|
|
2086
|
+
}
|
|
2087
|
+
// 候选跨窗顺延:本窗没写进库的候选留给下一窗的必写清单;最后一窗也在同一份
|
|
2088
|
+
// brief 里见到它们,不需要为了补写再开一次整窗 fork。核验纯本地,0 Token。
|
|
2089
|
+
const writtenIds = [...(decision.createdIds || []), ...(decision.updatedIds || []), ...(decision.heldIds || [])]
|
|
2090
|
+
const missed = mustCover.filter((candidate) => !candidateCovered(candidate, writtenIds, index))
|
|
2091
|
+
safeLedger(() => setCarryCandidates(sessionId, missed))
|
|
2092
|
+
// 摘要要覆盖 created/updated/held 全部落库 id(设计 §4.2),不只 created——
|
|
2093
|
+
// 否则续窗 worker 看不到已 update/held 的条目,可能重复尝试。ids 仅供摘要,不参与判同。
|
|
2094
|
+
safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: decision.status, ids: writtenIds }))
|
|
2095
|
+
// 私有自动关联(§5.6 兜底):只在整理真的对账并推进边界之后跑,纯算法,
|
|
2096
|
+
// 0 token。worker 若已调用 memu_private_link_suggest,这一遍是幂等的(已有的
|
|
2097
|
+
// relation/person 边会跳过)。link 只是图元数据:失败只记 warn,绝不能让一次
|
|
2098
|
+
// 已经成功的整理变成失败;timeout / unsettled / ledger-not-advanced 三条路径
|
|
2099
|
+
// 走不到这里,所以它们不会触发自动关联。
|
|
2100
|
+
const linkIds = [...(decision.createdIds || []), ...(decision.updatedIds || [])]
|
|
2101
|
+
if (linkIds.length) {
|
|
2102
|
+
try {
|
|
2103
|
+
await autoLinkPrivateMemories({ libraryId: binding.libraryId, sessionId, ids: linkIds })
|
|
2104
|
+
} catch (error) {
|
|
2105
|
+
// autoLinkPrivateMemories 自己已捕获操作性失败;这里只兜"意料之外"的抛错。
|
|
2106
|
+
try { warn('private auto-link after consolidation skipped: ' + String(error?.message || error)) } catch {}
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
// A timeout is not success: the fork may still be mid-write. It has to come
|
|
2111
|
+
// back with a message, not just `timedOut` — the settings button renders
|
|
2112
|
+
// `result.error` and an empty string there is indistinguishable from a click
|
|
2113
|
+
// that did nothing at all (observed: two clicks, no feedback, no memories).
|
|
2114
|
+
if (outcome === 'timeout') {
|
|
2115
|
+
if (workerMode) {
|
|
2116
|
+
// 持久模式(§4.4):超时 = 废弃本回合的结算,不废弃 worker。已写入的条目保留
|
|
2117
|
+
// (本来如此);游标不进(failJob 照旧);区间回 pending;下一窗增量包开头带
|
|
2118
|
+
// 「上窗未结算」核对说明(consolidationPending 标记)。连续 2 次超时升级退役
|
|
2119
|
+
// (防反复卡死吃窗口),退役允许交接——worker 上下文没坏,只是慢。
|
|
2120
|
+
workerEpochRecord = recordEpochProgress({ sessionId }, { timeout: true, progress: false }) || workerEpochRecord
|
|
2121
|
+
setSessionBinding(sessionId, { consolidationPending: { snapshotHash: snapshot.hash, jobId, at: new Date().toISOString() } })
|
|
2122
|
+
if ((Number(workerEpochRecord?.timeouts) || 0) >= WORKER_TIMEOUT_LIMIT) {
|
|
2123
|
+
try { await retireWorker(ctx, childId, 'timeout-x2', { handoff: true }) } catch {}
|
|
2124
|
+
}
|
|
2125
|
+
} else {
|
|
2126
|
+
// Stop the writer before releasing the range, not after. Waiting matters here
|
|
2127
|
+
// because a tool call already in flight can still land a memory on disk, and the
|
|
2128
|
+
// range going back to pending is what lets the next pass redo this window.
|
|
2129
|
+
await stopWorker()
|
|
2130
|
+
}
|
|
2131
|
+
safeLedger(() => failJob({
|
|
2132
|
+
sessionId, jobId, reasonCode: 'timeout',
|
|
2133
|
+
error: workerMode
|
|
2134
|
+
? 'timed out before a receipt; the turn was abandoned and the range is pending again (a tool call already in flight may have written; the worker is kept for the next window)'
|
|
2135
|
+
: 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written',
|
|
2136
|
+
}))
|
|
2137
|
+
return finish({
|
|
2138
|
+
ok: false,
|
|
2139
|
+
sessionId,
|
|
2140
|
+
childId,
|
|
2141
|
+
settled: false,
|
|
2142
|
+
timedOut: true,
|
|
2143
|
+
reasonCode: 'timeout',
|
|
2144
|
+
// The next pass must not assume this window left nothing behind: the range is
|
|
2145
|
+
// pending again and some writes may already have landed.
|
|
2146
|
+
partialWritesPossible: true,
|
|
2147
|
+
error: workerMode
|
|
2148
|
+
? 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the turn was abandoned and the range was released (memories written before the timeout are kept, the worker is kept). Retry, or consolidate a shorter conversation.'
|
|
2149
|
+
: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
|
|
2150
|
+
})
|
|
2151
|
+
}
|
|
2152
|
+
return finish({
|
|
2153
|
+
ok: outcome === 'done',
|
|
2154
|
+
sessionId,
|
|
2155
|
+
childId,
|
|
2156
|
+
settled: outcome === 'done',
|
|
2157
|
+
timedOut: false,
|
|
2158
|
+
status: decision?.status || null,
|
|
2159
|
+
outcome: decision?.outcome || null,
|
|
2160
|
+
reasonCode: decision?.reasonCode || null,
|
|
2161
|
+
counts: decision?.counted || null,
|
|
2162
|
+
createdIds: decision?.createdIds || [],
|
|
2163
|
+
updatedIds: decision?.updatedIds || [],
|
|
2164
|
+
heldIds: decision?.heldIds || [],
|
|
2165
|
+
receipt: decision?.receipt
|
|
2166
|
+
? { status: decision.receipt.status, outcome: decision.receipt.outcome, reasonCode: decision.receipt.reasonCode }
|
|
2167
|
+
: null,
|
|
2168
|
+
credential: completion?.checked ? { checked: completion.checked, pending: completion.pending } : null,
|
|
2169
|
+
snapshot: snapshotMeta,
|
|
2170
|
+
scanned: window.events.length,
|
|
2171
|
+
fresh: freshCount,
|
|
2172
|
+
remaining: window.remaining,
|
|
2173
|
+
window: { fromSeq: window.fromSeq, throughSeq: window.throughSeq },
|
|
2174
|
+
wrote,
|
|
2175
|
+
})
|
|
2176
|
+
} catch (error) {
|
|
2177
|
+
// worker 模式:异常 = 退役条件 5(无交接);fork 模式的销毁留给 finally。
|
|
2178
|
+
if (workerMode && childId && handle) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
|
|
2179
|
+
if (jobId) safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'exception', error: String(error?.message || error) }))
|
|
2180
|
+
return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
|
|
2181
|
+
} finally {
|
|
2182
|
+
inFlight.delete(sessionId)
|
|
2183
|
+
if (workerMode) {
|
|
2184
|
+
// 持久 worker(§15.2 改动点 6):每窗 finally 只清 inFlight 与本轮局部资源——
|
|
2185
|
+
// per-window 重验监听随窗摘除;worker 本体、工具面与子绑定留给 epoch
|
|
2186
|
+
// (retireWorker 与插件停用负责销毁)。'fork' 路径的清理原样保留。
|
|
2187
|
+
try { offSession?.() } catch {}
|
|
2188
|
+
} else {
|
|
2189
|
+
try { await stopWorker() } catch {}
|
|
2190
|
+
try { workerTools?.dispose?.() } catch {}
|
|
2191
|
+
try { workerRestriction?.dispose?.() } catch {}
|
|
2192
|
+
try { if (childId) deleteSessionBinding(childId) } catch {}
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
export function isConsolidating(sessionId) {
|
|
2197
|
+
return inFlight.has(sessionId)
|
|
2198
|
+
}
|