dsh-memu-memory 1.3.6 → 1.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/AGENTS.md +2 -1
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +4 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/memory-semantics.md +10 -7
  8. package/docs/troubleshooting.md +132 -7
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/client.js +296 -122
  11. package/lib/consolidation-ledger.js +6 -2
  12. package/lib/consolidation-worker.js +7 -0
  13. package/lib/inbound.js +24 -9
  14. package/lib/inject.js +379 -215
  15. package/lib/lexicon.js +5 -0
  16. package/lib/local-embedding-manager.js +4 -0
  17. package/lib/local-vector-service.js +65 -1
  18. package/lib/memory.js +711 -175
  19. package/lib/paths.js +24 -0
  20. package/lib/private.js +284 -127
  21. package/lib/rpc.js +144 -45
  22. package/lib/snippet.js +49 -28
  23. package/lib/state.js +185 -26
  24. package/lib/tools.js +150 -31
  25. package/lib/webui/standalone.css +28 -1
  26. package/lib/webui.js +25 -1
  27. package/lib/worker-pool.js +260 -26
  28. package/package.json +1 -1
  29. package/scripts/check-i18n.mjs +19 -0
  30. package/scripts/recall-bench.mjs +4 -4
  31. package/scripts/simulate-injection.mjs +3 -0
  32. package/tests/activity-wiring.test.mjs +52 -0
  33. package/tests/client-render.test.mjs +207 -0
  34. package/tests/consolidation-feed.test.mjs +26 -0
  35. package/tests/consolidation-fork.test.mjs +618 -33
  36. package/tests/consolidation-snapshot.test.mjs +2 -1
  37. package/tests/cross-library-recall.test.mjs +156 -0
  38. package/tests/cue.test.mjs +15 -2
  39. package/tests/hybrid-recall.test.mjs +488 -0
  40. package/tests/inbound.test.mjs +49 -4
  41. package/tests/inject-conflict.test.mjs +70 -9
  42. package/tests/inject-guide.test.mjs +13 -1
  43. package/tests/inject.test.mjs +10 -0
  44. package/tests/injection-budget.test.mjs +101 -0
  45. package/tests/injection-chain.test.mjs +37 -0
  46. package/tests/injection-rollback.test.mjs +172 -9
  47. package/tests/issue2-chain.test.mjs +169 -0
  48. package/tests/lexicon-inject.test.mjs +33 -5
  49. package/tests/lexicon-ui.test.mjs +99 -2
  50. package/tests/managed-memory.test.mjs +625 -1
  51. package/tests/media.test.mjs +1 -1
  52. package/tests/new-session-gate.test.mjs +280 -25
  53. package/tests/open-loop-date.test.mjs +11 -1
  54. package/tests/recall-intent.test.mjs +52 -3
  55. package/tests/simulate-injection.test.mjs +4 -4
  56. package/tests/snippet.test.mjs +33 -1
  57. package/tests/state.test.mjs +8 -3
  58. package/tests/tool-schema.test.mjs +52 -0
  59. package/tests/tools.test.mjs +394 -0
  60. package/tests/webui.test.mjs +16 -2
  61. package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/private.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { createUserMessage } from '@deepseek-ai/dsh-llm'
2
2
  import crypto from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
3
5
  import { getSessionBinding, getLibrary, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex, effectiveScope } from './state.js'
4
6
  import { domainOf, privateRemember, isMemoryEligible, visibleToSession } from './memory.js'
5
7
  import { loadPromptForDomain, CONSOLIDATION_CONTRACTS } from './prompts.js'
@@ -173,6 +175,10 @@ export const CONSOLIDATION_MIN_HUMAN_TURNS = 3
173
175
  // A checkpoint is measured in session events, and six of them are pure turn/step
174
176
  // wrappers. 300 events therefore bought only ~50 turns of transcript. 500 keeps
175
177
  // the same seed size in practice but cuts one fork for a 200-turn catch-up.
178
+ // 2026-11-15:窗口定回 500,配套把整理预算抬到 600s(见 CONSOLIDATION_WAIT_POLICY)——
179
+ // 慢推理模型(GLM-5.3-Flash)下 500 事件需要更长的单窗时间,靠加时长而非砍窗解决;
180
+ // 剩余区间留在 pending,下一扫继续(selectConsolidationWindow 按游标推进),
181
+ // 重试窗减半到 250。
176
182
  export const CONSOLIDATION_WINDOW_EVENTS = 500
177
183
  // worker 模式按回合扩展窗口:500 事件切在回合中间时,向后补到该回合的 turn/end。
178
184
  // worker 的包是 turn-log 记录(单条最多 4000 字符),扩展窗口不会放大模型上下文;
@@ -923,7 +929,7 @@ async function inheritedAgentOptions(ctx, sessionId, events) {
923
929
  try { agents = ctx.get?.('agents') || null } catch {}
924
930
  const probe = (agent) => {
925
931
  try {
926
- const fromRequest = agentOptionsFromConfig(agent?.session?.requestHeader?.()?.config)
932
+ const fromRequest = liveAgentOptions(agent)
927
933
  if (fromRequest) return fromRequest
928
934
  } catch {}
929
935
  return agentOptionsFromConfig(agent?.options)
@@ -987,12 +993,12 @@ const inFlight = new Map()
987
993
  const WORKER_STOP_GRACE_MS = 5_000
988
994
 
989
995
  // 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
990
- // 的 file:line 当成诊断契约(当前 lib/private.js:893),修改位置时同步更新该诊断映射,
996
+ // 的 file:line 当成诊断契约(当前 lib/private.js:988),修改位置时同步更新该诊断映射,
991
997
  // 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
992
- import { warn } from './paths.js'
998
+ import { warn, dataDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
993
999
  import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
994
1000
  import {
995
- beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey,
1001
+ beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey, sessionState,
996
1002
  recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
997
1003
  readCarryCandidates, setCarryCandidates,
998
1004
  } from './consolidation-ledger.js'
@@ -1003,12 +1009,61 @@ import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOO
1003
1009
  import {
1004
1010
  acquireWorker, attachWorkerTools, buildHandoffPack, buildIncrementPack, loadWorkerIncrement,
1005
1011
  recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
1012
+ resolveConsolidationCwd, measurePacket, packetBudgetFit, createConsolidationMeasurement,
1006
1013
  } from './worker-pool.js'
1007
1014
  import { tokenize, buildCorpus, bm25 } from './text-retrieval.js'
1008
1015
  import { isGoneSessionError } from './cycle.js'
1009
1016
  import { autoLinkPrivateMemories } from './private-links.js'
1010
1017
  import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
1011
1018
 
1019
+ function liveAgentOptions(agent) {
1020
+ const options = agent?.options
1021
+ let request = null
1022
+ try { request = agentOptionsFromConfig(agent?.session?.requestHeader?.()?.config) } catch {}
1023
+ if (!request) return agentOptionsFromConfig(options)
1024
+ const sameRoute = (!options?.provider || options.provider.trim() === request.provider) && (!options?.model || options.model.trim() === request.model)
1025
+ if (sameRoute && Number.isSafeInteger(options?.maxTokens) && options.maxTokens > 0) return { ...request, maxTokens: options.maxTokens }
1026
+ return request
1027
+ }
1028
+
1029
+ async function consolidationExecutionContext(ctx, sessionId, settings, events, inheritedOptions = null) {
1030
+ const mode = settings.consolidationModelMode || 'inherit'
1031
+ let inherited = inheritedOptions
1032
+ if (mode !== 'host' && mode !== 'custom' && !inherited) {
1033
+ try {
1034
+ const agent = ctx.get?.('agents')?.get?.(sessionId)
1035
+ inherited = liveAgentOptions(agent)
1036
+ } catch {}
1037
+ if (!inherited) {
1038
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1039
+ if (events[i]?.type !== 'request/header') continue
1040
+ inherited = agentOptionsFromConfig(events[i]?.data?.header?.config)
1041
+ if (inherited) break
1042
+ }
1043
+ }
1044
+ }
1045
+ const { options } = resolveConsolidationAgentOptions(settings, inherited)
1046
+ const configuredEffort = settings.consolidationReasoningEffort
1047
+ let effort = configuredEffort && configuredEffort !== 'inherit' ? configuredEffort : options?.reasoningEffort ?? null
1048
+ if (options && effort && isEffortRefused([options.provider, options.model, effort].join('|'))) effort = null
1049
+ let maxTokens = options?.maxTokens ?? null
1050
+ const settingsKey = crypto.createHash('sha256').update(JSON.stringify({
1051
+ mode, runner: settings.consolidationRunner || 'fork',
1052
+ provider: options?.provider ?? null, model: options?.model ?? null, maxTokens, effort,
1053
+ })).digest('hex')
1054
+ let defaultsComparable = maxTokens !== null && effort !== null
1055
+ if (options && !defaultsComparable) {
1056
+ try {
1057
+ const info = await ctx.get?.('llm')?.resolveModelInfo?.(options.provider, options.model)
1058
+ defaultsComparable = !!info && typeof info === 'object'
1059
+ if (maxTokens === null && Number.isSafeInteger(info?.defaultMaxTokens) && info.defaultMaxTokens > 0) maxTokens = info.defaultMaxTokens
1060
+ if (effort === null && typeof info?.reasoning?.defaultEffort === 'string') effort = info.reasoning.defaultEffort
1061
+ } catch {}
1062
+ }
1063
+ const key = crypto.createHash('sha256').update(JSON.stringify({ settingsKey, maxTokens, effort })).digest('hex')
1064
+ return { key, settingsKey, defaultsComparable, maxTokens }
1065
+ }
1066
+
1012
1067
  // 账本异常必须可见;调用方只有拿到明确的持久租约才可启动 worker。
1013
1068
  // 其余读写失败返回保守结果,不得据此推进已确认边界。
1014
1069
  function safeLedger(action, fallback = null) {
@@ -1042,18 +1097,89 @@ function snapshotMetaOf(snapshot) {
1042
1097
  // session is that a closed one has to be read back from disk first.
1043
1098
  // 一次整理要等多长时间,取决于它要读多少转录:fork 的种子是整段会话,worker 读完才
1044
1099
  // 开始写。实测(2026-11-02,935 条事件的会话):第一次 180 s 到点时刚写完 3 条、
1045
- // 退避重试 131 s 完成——即约 0.14–0.2 s/事件。这里按 0.35 s/事件(≈2 倍余量)推预算,
1046
- // 并夹在 [420 s, 600 s]:慢推理模型(GLM-5.3-Flash 实测)单次 worker 回合就能吃满
1047
- // 180 s 旧下限且一个工具都没调(1.2.7 后内部评测复现),下限抬到 7 分钟给长思考留
1048
- // 余量;600 s 封顶不变,卡死的 fork 仍会在 10 分钟内被收掉。显式传 maxWaitMs 的
1049
- // 调用(含工具/测试)原样生效。
1100
+ // 退避重试 131 s 完成——即约 0.14–0.2 s/事件。这里按 0.35 s/事件(≈2 倍余量)推预算。
1101
+ // 2026-11-15:下限抬到 600 s 与封顶齐平——预算恒为 600 s(10 分钟)。慢推理模型
1102
+ // (GLM-5.3-Flash 实测)单次 worker 回合就能吃满旧下限且一个工具都没调,500 事件窗
1103
+ // 需要完整的 10 分钟余量;卡死的 fork 仍会在 10 分钟到点后被收掉,租约跟随预算 +90s。
1104
+ // 显式传 maxWaitMs 的调用(含工具/测试)原样生效。
1050
1105
  export const CONSOLIDATION_WAIT_POLICY = Object.freeze({
1051
1106
  baseMs: 120_000,
1052
1107
  perEventMs: 350,
1053
- minMs: 420_000,
1108
+ minMs: 600_000,
1054
1109
  maxMs: 600_000,
1055
1110
  })
1056
1111
 
1112
+ // 2026-11-15 扫雷:整理 fork 的思考强度被模型拒绝的学习表(provider|model|effort)。
1113
+ // 实测:wb/glm-5.3-flash 不支持 medium,带档起 fork 必失败(fork-turn-failed),
1114
+ // 同一快照失败 2 次后被 snapshot-failed-too-many 冻结数天。这里学习一次拒绝,
1115
+ // 之后同组合不再带 effort 起 fork。
1116
+ // 2026-11-18 起持久化到数据目录:进程重启曾把表清零,而反代服务商的签名各不相同
1117
+ // (raccoon/sn-deepseek-v4-1-flash-1017 拒 medium 实测),于是每次重启后的第一次
1118
+ // 手动整理都会再吃一次 fork-turn-failed——用户看到的就是"反代服务商老是失败"。
1119
+ // 拒绝不是转录有病、也不是服务商不可达,是参数不匹配,落盘完全安全。
1120
+ // 按当前 home 惰性加载;干净缓存只查 Set,失败的读/写留到下一次调用重试。
1121
+ const effortRefusalCaches = new Map()
1122
+
1123
+ function effortRefusalCache() {
1124
+ const file = path.resolve(dataDir(), 'effort-refusals.json')
1125
+ if (!effortRefusalCaches.has(file)) {
1126
+ effortRefusalCaches.set(file, { file, keys: new Set(), loaded: false, dirty: false })
1127
+ }
1128
+ return effortRefusalCaches.get(file)
1129
+ }
1130
+
1131
+ function readEffortRefusals(file) {
1132
+ const result = readJsonStrict(file)
1133
+ if (result.missing) return []
1134
+ if (!result.ok) throw result.error || new Error('cannot read effort refusals')
1135
+ const raw = result.value
1136
+ if (raw?.version !== 1 || !Array.isArray(raw.keys) || !raw.keys.every(key => typeof key === 'string')) {
1137
+ throw new Error('invalid effort refusals schema')
1138
+ }
1139
+ return raw.keys
1140
+ }
1141
+
1142
+ function syncEffortRefusals(cache) {
1143
+ try {
1144
+ if (cache.dirty) {
1145
+ withFileLock(cache.file, () => {
1146
+ // 必须在锁内重读:其它进程可能已写入本缓存尚未见过的键。
1147
+ // 读错/坏 schema 直接退出,绝不把它当空表覆盖;写失败仍保留 dirty。
1148
+ const keys = new Set([...readEffortRefusals(cache.file), ...cache.keys])
1149
+ writeJson(cache.file, { version: 1, keys: [...keys] })
1150
+ cache.keys = keys
1151
+ cache.loaded = true
1152
+ cache.dirty = false
1153
+ })
1154
+ } else if (!cache.loaded) {
1155
+ cache.keys = new Set(readEffortRefusals(cache.file))
1156
+ cache.loaded = true
1157
+ }
1158
+ } catch (error) {
1159
+ warn('consolidation effort refusals: ' + String(error?.message || error))
1160
+ }
1161
+ }
1162
+
1163
+ /** 从 fork 失败信息里识别『该模型不支持这个思考强度』并给出学习键。 */
1164
+ export function effortRefusalOf(failure) {
1165
+ const m = /provider "([^"]+)" model "([^"]+)" does not support reasoning effort "([^"]+)"/.exec(String(failure || ''))
1166
+ return m ? { provider: m[1], model: m[2], effort: m[3], key: [m[1], m[2], m[3]].join('|') } : null
1167
+ }
1168
+ export function markEffortRefused(key) {
1169
+ const cache = effortRefusalCache()
1170
+ const k = String(key)
1171
+ if (!cache.keys.has(k)) {
1172
+ cache.keys.add(k)
1173
+ cache.dirty = true
1174
+ }
1175
+ syncEffortRefusals(cache)
1176
+ }
1177
+ export function isEffortRefused(key) {
1178
+ const cache = effortRefusalCache()
1179
+ syncEffortRefusals(cache)
1180
+ return cache.keys.has(String(key))
1181
+ }
1182
+
1057
1183
  export function consolidationWaitBudget(eventCount, policy = CONSOLIDATION_WAIT_POLICY) {
1058
1184
  const count = Number.isFinite(Number(eventCount)) ? Math.max(0, Math.floor(Number(eventCount))) : 0
1059
1185
  const raw = policy.baseMs + count * policy.perEventMs
@@ -1118,9 +1244,12 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1118
1244
  let workerEpochAbort = null
1119
1245
  const assistantTexts = []
1120
1246
  let childId = null
1247
+ let accounting = null
1248
+ let executionContext = null
1121
1249
  // 每次整理都要在活动日志里留一条:谁触发(手动/空闲)、fork 有没有建、结果是完成、
1122
1250
  // 超时还是失败。否则"点了没反应"只能靠翻会话文件才知道发生了什么。
1123
1251
  const finish = (result) => {
1252
+ result = { ...result, runner: workerMode ? 'worker' : 'fork', measurement: accounting?.measurement || null }
1124
1253
  const ok = result?.ok === true
1125
1254
  const skipped = Boolean(result?.skipped)
1126
1255
  const skipText = !skipped
@@ -1149,6 +1278,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1149
1278
  return result
1150
1279
  }
1151
1280
  try {
1281
+ const settings = getSettings()
1282
+ workerMode = settings.consolidationRunner === 'worker'
1283
+ accounting = createConsolidationMeasurement(workerMode ? 'worker' : 'fork')
1152
1284
  // 僵尸租约先回收:进程被杀之后 inflight 会留在账本里,不能让一条死记录永久挡住这个会话。
1153
1285
  safeLedger(() => {
1154
1286
  const recovered = recoverStaleJobs()
@@ -1171,8 +1303,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1171
1303
  if (typeof agents?.create !== 'function') {
1172
1304
  return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-agents-service', settled: false, error: 'host has no agents.create; historical consolidation is unavailable' })
1173
1305
  }
1174
- const buildForkSeed = await loadBuildForkSeed()
1175
- if (!buildForkSeed) {
1306
+ const buildForkSeed = workerMode ? null : await loadBuildForkSeed()
1307
+ if (!workerMode && !buildForkSeed) {
1176
1308
  return finish({ ok: false, sessionId, code: 'unavailable', reasonCode: 'no-fork-seed', settled: false, error: 'dsh-session buildForkSeed is unavailable' })
1177
1309
  }
1178
1310
 
@@ -1233,7 +1365,6 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1233
1365
  reasonCode: value.reason, assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
1234
1366
  })
1235
1367
  }
1236
- const settings = getSettings()
1237
1368
  // 事件/回合水位:积压到一定规模就直接整理,不再等评分。它和空闲触发是
1238
1369
  // 两条腿:空闲保证收尾,水位保证一场持续几小时的会话不会攒到几千条才动。
1239
1370
  const backlog = candidateEvents.length >= CONSOLIDATION_BACKLOG_EVENTS
@@ -1293,9 +1424,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1293
1424
  // 前半段先结算,剩余留给下一次。
1294
1425
  const sleepAttempt = Number(binding.sleepAttempts || 0)
1295
1426
  const windowLimit = sleepAttempt > 0 ? Math.floor(CONSOLIDATION_WINDOW_EVENTS / 2) : CONSOLIDATION_WINDOW_EVENTS
1296
- // 执行器选择提前到窗口选择处(A5 需要按 runner 决定是否回合对齐);settings 复用至模型路由。
1297
- const settings = getSettings()
1298
- workerMode = settings.consolidationRunner === 'worker'
1427
+ // Runner and model route use the same settings snapshot captured before awaits.
1299
1428
  // A5:worker 模式按回合取窗(切在回合中间时向后补到 turn/end,避免同一回合
1300
1429
  // 被连续两窗整条重发);fork 路径窗口定义不变。
1301
1430
  let window = workerMode
@@ -1319,11 +1448,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1319
1448
  const carry = safeLedger(() => readCarryCandidates(sessionId), [])
1320
1449
  const domain = domainOf(binding)
1321
1450
  const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
1322
- const seedEvents = compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
1451
+ const seedEvents = workerMode ? null : compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
1323
1452
  memoryCatalogEvent({ ...binding, sessionId }),
1324
1453
  memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
1325
1454
  ])
1326
- if (seedEvents.length === 0) {
1455
+ if (!workerMode && seedEvents.length === 0) {
1327
1456
  return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
1328
1457
  }
1329
1458
 
@@ -1339,10 +1468,31 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1339
1468
  // 不受上限约束——否则冻结回放/用户重试都会被永久卡在同一个窗口。新消息会改变
1340
1469
  // 快照哈希,自动路径也重新获得机会。
1341
1470
  if (!force && previous?.outcome === 'failed' && Number(previous.failures) >= CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT) {
1342
- return finish({
1343
- ok: true, sessionId, skipped: 'snapshot-failed', settled: true, reasonCode: 'snapshot-failed-too-many',
1344
- snapshot: snapshotMeta, failures: Number(previous.failures) || 0,
1345
- })
1471
+ // 2026-11-15:冻结原因若是思考强度被模型拒(账本 lastError 可见),就地学习组合并
1472
+ // 清连击,本次直接放行 fork(fork 起点读不到拒绝表就会带档失败——放行前先学习,
1473
+ // effort 应用处读到拒绝表即不带档)。已冻结的会话由此自愈,不必等手动 force。
1474
+ const failureState = safeLedger(() => sessionState(sessionId), null)
1475
+ const lastError = failureState?.lastError ?? null
1476
+ const staleRefusal = effortRefusalOf(lastError)
1477
+ const newRefusal = staleRefusal && !isEffortRefused(staleRefusal.key)
1478
+ const legacyOutputLimit = (previous.reasonCode ?? failureState?.lastReasonCode) === 'fork-turn-failed'
1479
+ && /^the fork turn ended max-tokens(?::|$)/.test(String(lastError || ''))
1480
+ const outputLimited = previous.reasonCode === 'model-output-limit' || legacyOutputLimit
1481
+ const execution = outputLimited ? await consolidationExecutionContext(ctx, sessionId, settings, events) : null
1482
+ const changedExecution = execution && (!previous.executionSettingsKey || execution.settingsKey !== previous.executionSettingsKey
1483
+ || execution.defaultsComparable && execution.key !== previous.executionKey)
1484
+ if (!newRefusal && !changedExecution) {
1485
+ return finish({
1486
+ ok: true, sessionId, skipped: 'snapshot-failed', settled: !outputLimited, reasonCode: 'snapshot-failed-too-many',
1487
+ snapshot: snapshotMeta, failures: Number(previous.failures) || 0, lastError,
1488
+ })
1489
+ }
1490
+ if (newRefusal) {
1491
+ warn('consolidation unfrozen: ' + staleRefusal.key + ' was refused by the model; retrying this window without the effort')
1492
+ markEffortRefused(staleRefusal.key)
1493
+ }
1494
+ if (changedExecution) warn('consolidation output-limit retry: execution configuration changed or needs its first fingerprint')
1495
+ safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: previous.ids || [] }))
1346
1496
  }
1347
1497
 
1348
1498
  // 工具面必须可验证:父会话这一轮真实发给模型的工具表里若没有记忆写工具,
@@ -1357,7 +1507,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1357
1507
  }
1358
1508
 
1359
1509
  jobId = 'cons-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
1360
- const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding }))
1510
+ // 2026-11-15 扫雷:租约跟随本次预算(+90s 余量),不再固定 15 分钟——
1511
+ // 走不到超时路径就死的任务(插件重启 / fork 被外力杀掉)不会调 failJob,
1512
+ // 固定 15 分钟租约让该会话的重试一直撞 lease-held;预算封顶 600s,
1513
+ // 租约最迟在真死后 ~90s 由 recoverStaleJobs 回收,而不是再等 9 分钟。
1514
+ const begun = safeLedger(() => beginJob({ sessionId, jobId, snapshot, binding, leaseMs: budgetMs + 90_000 }))
1361
1515
  if (!begun) {
1362
1516
  return finish({
1363
1517
  ok: false, sessionId, settled: false, retryable: true, reasonCode: 'ledger-unavailable',
@@ -1367,7 +1521,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1367
1521
  if (begun.ok !== true) {
1368
1522
  return finish({
1369
1523
  ok: false, sessionId, running: true, settled: false, reasonCode: 'lease-held',
1370
- error: 'this session already holds a consolidation lease (' + String(begun.jobId) + ' until ' + new Date(begun.leaseUntil).toISOString() + '); the previous run is still unaccounted for',
1524
+ 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',
1371
1525
  })
1372
1526
  }
1373
1527
 
@@ -1400,11 +1554,6 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1400
1554
  const resolved = resolveConsolidationAgentOptions(settings, inherited)
1401
1555
  let agentOptions = resolved.options
1402
1556
  let modelMode = resolved.reason
1403
- // 1.3.1:整理思考强度可独立于父会话;'inherit' 保持旧行为。
1404
- const effort = settings.consolidationReasoningEffort
1405
- if (agentOptions && effort && effort !== 'inherit') {
1406
- agentOptions = { ...agentOptions, reasoningEffort: effort }
1407
- }
1408
1557
  if (!agentOptions) {
1409
1558
  // no-inherited-route 与旧失败路径逐字节一致(inherit 模式语义不变);host/custom
1410
1559
  // 的坏配置各自带 reasonCode,整理提醒能直接说清是哪个配置面写错了。
@@ -1432,23 +1581,74 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1432
1581
  }
1433
1582
  }
1434
1583
 
1584
+ // 最终 route(含 custom 回退)确定后再覆盖档位、过滤实际生效的组合。
1585
+ // inherit 也可能从父 options 带入被拒档位;只克隆子 options,不改父对象或其它参数。
1586
+ const effort = settings.consolidationReasoningEffort
1587
+ if (effort && effort !== 'inherit') agentOptions = { ...agentOptions, reasoningEffort: effort }
1588
+ const effectiveEffort = agentOptions.reasoningEffort
1589
+ if (effectiveEffort && isEffortRefused([agentOptions.provider, agentOptions.model, effectiveEffort].join('|'))) {
1590
+ warn('consolidation reasoning effort ' + effectiveEffort + ' previously refused by ' + agentOptions.provider + '/' + agentOptions.model + ' — starting the worker/fork without it')
1591
+ agentOptions = { ...agentOptions }
1592
+ delete agentOptions.reasoningEffort
1593
+ }
1594
+
1435
1595
  // 执行器分叉(T1,设计文档 §10.2):workerMode 已在窗口选择处确定(A5)。
1436
1596
  // 默认 'fork'(现状路径,逐字节不变);显式 'worker' 走持久整理 worker(lib/worker-pool.js)。
1597
+ executionContext = await consolidationExecutionContext(ctx, sessionId, settings, events, modelMode === 'inherit' ? agentOptions : null)
1437
1598
  let workerAcquired = null
1438
1599
  let workerEpochRecord = null
1439
1600
  let workerIncrement = null
1601
+ let dispatchText = null
1602
+ let dispatchKind = 'fork'
1440
1603
  if (workerMode) {
1441
- // 先读增量再 acquire:退役条件 2(预算合格制)需要本窗增量的字符量(§4.5)。
1442
- // binding 是入口捕获对象,不带 sessionId 字段——worker-pool 的入参用展开补齐。
1443
1604
  const workerBinding = { ...binding, sessionId }
1444
1605
  workerIncrement = loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
1445
- workerAcquired = await acquireWorker(ctx, workerBinding, {
1446
- incrementChars: workerIncrement.chars,
1447
- settings,
1448
- probe,
1449
- agentOptions,
1450
- header,
1451
- })
1606
+ if (!workerIncrement.text.trim()) {
1607
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'empty-increment', retryable: true }))
1608
+ return finish({ ok: false, sessionId, settled: false, retryable: true, reasonCode: 'empty-increment', error: 'no readable worker increment; the range stays pending' })
1609
+ }
1610
+ const current = getSessionBinding(sessionId) || binding
1611
+ const privatePrompt = buildPrivateConsolidationPrompt(sessionId)
1612
+ const common = {
1613
+ sessionId, binding: workerBinding, snapshot, probe, jobId,
1614
+ reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly), mustCover,
1615
+ contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1616
+ incrementRecords: workerIncrement.records,
1617
+ incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
1618
+ digest: workerIncrement.digest, catalog: memoryCatalogEvent(workerBinding),
1619
+ sceneTime: current.sceneTime || binding.sceneTime || null,
1620
+ pendingNote: Boolean(current.consolidationPending), pendingHash: current.consolidationPending?.snapshotHash || null,
1621
+ carry: mustCover, lastSleepSeq: binding.lastSleepSeq ?? null,
1622
+ }
1623
+ const buildPacket = (acquired) => {
1624
+ dispatchKind = acquired.birth ? 'handoff' : 'increment'
1625
+ const pack = acquired.birth ? buildHandoffPack({
1626
+ ...common, includeTail: acquired.handoff !== false, writtenRows: acquired.handoff === false ? [] : null,
1627
+ }) : buildIncrementPack(common)
1628
+ return acquired.birth ? [privatePrompt, '', pack].join('\n') : pack
1629
+ }
1630
+ const acquireOptions = { settings, probe, agentOptions, header }
1631
+ workerAcquired = await acquireWorker(ctx, workerBinding, acquireOptions)
1632
+ if (workerAcquired.ok) {
1633
+ dispatchText = buildPacket(workerAcquired)
1634
+ let packet = measurePacket(dispatchText, dispatchKind)
1635
+ if (!packetBudgetFit(workerAcquired.epoch, packet, settings) && !workerAcquired.birth) {
1636
+ // The final text, not just the pending increment, must fit. Rebuild at
1637
+ // most once, since a handoff includes extra identity/settled-tail text.
1638
+ await retireWorker(ctx, workerAcquired.forkId, 'packet-budget', { handoff: true })
1639
+ workerAcquired = await acquireWorker(ctx, workerBinding, { ...acquireOptions, afterEpochIndex: workerAcquired.epoch.index })
1640
+ if (workerAcquired.ok) {
1641
+ dispatchText = buildPacket(workerAcquired)
1642
+ packet = measurePacket(dispatchText, dispatchKind)
1643
+ }
1644
+ }
1645
+ if (workerAcquired.ok && !packetBudgetFit(workerAcquired.epoch, packet, settings)) {
1646
+ accounting.measurement.packet = { ...packet, dispatched: false }
1647
+ await retireWorker(ctx, workerAcquired.forkId, 'packet-too-large', { handoff: false })
1648
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'packet-too-large', retryable: true, error: 'the complete first packet exceeds the worker epoch budget' }))
1649
+ 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)' })
1650
+ }
1651
+ }
1452
1652
  if (!workerAcquired.ok) {
1453
1653
  safeLedger(() => failJob({ sessionId, jobId, reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed', retryable: true, error: workerAcquired.error || null }))
1454
1654
  return finish({
@@ -1463,16 +1663,19 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1463
1663
  workerRestriction = workerAcquired.restriction
1464
1664
  workerEpochRecord = workerAcquired.epoch
1465
1665
  workerEpochAbort = workerAcquired.epochAbort || null
1666
+ accounting = createConsolidationMeasurement('worker', { sessionId: childId, afterSeq: workerAcquired.eventCursor ?? workerEpochRecord.lastEventSeq })
1466
1667
  } else {
1467
1668
  childId = 'memu-consolidate-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
1468
1669
  // 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
1469
1670
  // 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
1470
1671
  // 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
1672
+ // 保留仍存在的会话 cwd;旧目录失效时回退 dataDir,避免宿主拒绝启动回合。
1673
+ const forkCwd = resolveConsolidationCwd(header.cwd)
1471
1674
  try {
1472
1675
  handle = await agents.create({
1473
1676
  sessionId: childId,
1474
1677
  meta: {
1475
- cwd: header.cwd,
1678
+ cwd: forkCwd,
1476
1679
  parentSession: sessionId,
1477
1680
  isSeeded: true,
1478
1681
  // Without this the fork is treated as an ordinary user conversation by
@@ -1508,9 +1711,17 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1508
1711
  }
1509
1712
  workerRestriction = await restrictWorkerTools(agents, childId, sessionId)
1510
1713
  }
1511
- // worker 模式:本窗 worker 产出体积(assistant 正文 + 工具参数/结果)由下面挂的
1512
- // per-window 监听顺手累计,窗口结束后并入 epoch.chars(recordEpochProgress)。
1513
- let workerOutputChars = 0
1714
+ // Counters are shared by fork/worker; only the latter persists an epoch.
1715
+ if (!workerMode) {
1716
+ accounting = createConsolidationMeasurement('fork', { sessionId: childId })
1717
+ const brief = buildWorkerBrief({
1718
+ snapshot, probe, jobId, mustCover, autoReceipt: true,
1719
+ contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1720
+ reason: force ? 'manual' : 'auto', singleOnly: Boolean(binding.consolidationSingleOnly),
1721
+ })
1722
+ dispatchText = [buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n')
1723
+ }
1724
+ accounting.measurement.packet = measurePacket(dispatchText, dispatchKind)
1514
1725
 
1515
1726
  // 先记"已开始"再等结果:一个大会话的 fork 可能跑好几分钟,没有这条记录,
1516
1727
  // 侧边栏和日志页在等待期间只会显示上一次的结果,用户会以为按钮没生效。
@@ -1526,7 +1737,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1526
1737
  + (window.remaining > 0 ? ' · 还余 ' + window.remaining : '')
1527
1738
  + ' · 预算 ' + Math.round(budgetMs / 1000) + 's · 快照 ' + snapshot.hash,
1528
1739
  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,
1529
- modelMode,
1740
+ modelMode, runner: workerMode ? 'worker' : 'fork', measurement: accounting.measurement,
1530
1741
  probe: { source: probe.source, hasWrite: probe.hasWrite, ptc: probe.ptcObserved === true },
1531
1742
  ...workerToolsMeta(workerTools) },
1532
1743
  })
@@ -1554,6 +1765,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1554
1765
  try {
1555
1766
  offSession = ctx.on('session/event', (session, event) => {
1556
1767
  if (session === childSession) {
1768
+ if (!accounting.observe(event)) return
1557
1769
  if (event?.type === 'turn/end') { turnEnd = event; return }
1558
1770
  if (event?.type === 'assistant/message') {
1559
1771
  const blocks = event?.data?.message?.content
@@ -1561,7 +1773,6 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1561
1773
  for (const block of blocks) {
1562
1774
  if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
1563
1775
  assistantTexts.push(block.text)
1564
- if (workerMode) workerOutputChars += block.text.length
1565
1776
  }
1566
1777
  }
1567
1778
  }
@@ -1569,11 +1780,6 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1569
1780
  }
1570
1781
  // 工具动作是写入的落点:每出现一次就重验一次父授权,变了立刻停掉这条 fork。
1571
1782
  if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
1572
- if (workerMode) {
1573
- workerOutputChars += event?.type === 'tool/call'
1574
- ? String(event?.data?.arguments ?? '').length
1575
- : JSON.stringify(event?.data?.message?.content ?? '').length
1576
- }
1577
1783
  revalidate('worker-write')
1578
1784
  workerToolRounds += 1
1579
1785
  if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
@@ -1583,7 +1789,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1583
1789
  } else {
1584
1790
  const guidance = workerRoundGuidance(workerToolRounds)
1585
1791
  if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
1586
- try { handle?.agent?.followup?.(noticeMessage(guidance.text, '整理收尾提示')) } catch {}
1792
+ try {
1793
+ const queued = handle.agent.followup(noticeMessage(guidance.text, '整理收尾提示'))
1794
+ accounting.dispatch(guidance.text, 'wrapup')
1795
+ Promise.resolve(queued).catch(() => warn('consolidation wrapup followup failed'))
1796
+ } catch { warn('consolidation wrapup followup failed') }
1587
1797
  }
1588
1798
  }
1589
1799
  return
@@ -1646,77 +1856,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1646
1856
  })
1647
1857
  }
1648
1858
 
1649
- // 任务书 + followup(§15.2 改动点 4):fork 每窗发整份任务书;worker 模式初生发
1650
- // 交接包(= 初生包,§5.1),续窗只发增量包(目录头/契约/场景时间每窗都发,
1651
- // 已写入摘要只在初生/交接包携带——worker 上下文里刚写过,续窗发是冗余)。
1652
- if (workerMode && workerAcquired) {
1653
- const sceneTimeNow = (() => {
1654
- try { return getSessionBinding(sessionId)?.sceneTime || binding.sceneTime || null } catch { return binding.sceneTime || null }
1655
- })()
1656
- const contract = receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true })
1657
- const catalog = memoryCatalogEvent({ ...binding, sessionId })
1658
- // 上一窗是否结清(§4.4):结算成功时清除,超时时落 consolidationPending;
1659
- // binding 是入口捕获的旧对象,必须重读。
1660
- const pendingNote = (() => {
1661
- try { return Boolean(getSessionBinding(sessionId)?.consolidationPending) } catch { return false }
1662
- })()
1663
- const pendingHash = (() => {
1664
- try { return getSessionBinding(sessionId)?.consolidationPending?.snapshotHash || null } catch { return null }
1665
- })()
1666
- if (workerAcquired.birth) {
1667
- const pack = buildHandoffPack({
1668
- sessionId,
1669
- binding: { ...binding, sessionId },
1670
- snapshot,
1671
- probe,
1672
- jobId,
1673
- reason: force ? 'manual' : 'auto',
1674
- singleOnly: Boolean(binding.consolidationSingleOnly),
1675
- mustCover,
1676
- contract,
1677
- incrementRecords: workerIncrement.records,
1678
- incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
1679
- digest: workerIncrement.digest,
1680
- catalog,
1681
- sceneTime: sceneTimeNow,
1682
- pendingNote,
1683
- pendingHash,
1684
- // 「不做 handoff」= 不带旧 epoch 的连续性材料(尾部 + 已写入摘要);
1685
- // 身份任务书与目录头照发(§8:冷启动新包)。
1686
- includeTail: workerAcquired.handoff !== false,
1687
- writtenRows: workerAcquired.handoff === false ? [] : null,
1688
- lastSleepSeq: binding.lastSleepSeq ?? null,
1689
- })
1690
- handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', pack].join('\n'), '整理这场对话的私有记忆'))
1691
- } else {
1692
- const pack = buildIncrementPack({
1693
- binding: { ...binding, sessionId },
1694
- incrementRecords: workerIncrement.records,
1695
- incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
1696
- digest: workerIncrement.digest,
1697
- catalog,
1698
- carry: mustCover,
1699
- contract,
1700
- sceneTime: sceneTimeNow,
1701
- pendingNote,
1702
- pendingHash,
1703
- })
1704
- handle.agent.followup(noticeMessage(pack, '整理这场对话的私有记忆'))
1705
- }
1706
- } else {
1707
- const brief = buildWorkerBrief({
1708
- snapshot,
1709
- probe,
1710
- contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
1711
- reason: force ? 'manual' : 'auto',
1712
- jobId,
1713
- mustCover,
1714
- autoReceipt: true,
1715
- // 上一轮 batch 参数 JSON 畸形:这一轮只让模型逐条 remember,降低再次整段失败的概率。
1716
- singleOnly: Boolean(binding.consolidationSingleOnly),
1717
- })
1718
- handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n'), '整理这场对话的私有记忆'))
1719
- }
1859
+ // Measure exactly the final followup text, including all separators/briefs.
1860
+ handle.agent.followup(noticeMessage(dispatchText, '整理这场对话的私有记忆'))
1861
+ accounting.dispatch(dispatchText, dispatchKind)
1720
1862
  // followup only queues. whenIdle says the driver stopped; turn/end says
1721
1863
  // whether that turn actually succeeded, so both are checked below.
1722
1864
  idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
@@ -1732,8 +1874,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1732
1874
  // 结算成功后的超时清零在 completeJob 之后单独落一次。
1733
1875
  if (workerMode) {
1734
1876
  workerEpochRecord = recordEpochProgress({ sessionId }, {
1735
- incrementChars: workerIncrement.chars,
1736
- workerOutputChars,
1877
+ measurement: accounting.measurement,
1737
1878
  idleAt: outcome === 'done' ? Date.now() : null,
1738
1879
  }) || workerEpochRecord
1739
1880
  }
@@ -1748,14 +1889,30 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1748
1889
  // 只用逐条 remember,并让重试路径接住(consolidateAll 已有 2 次重试)。
1749
1890
  const batchJsonInvalid = /memu_private_remember_batch/.test(String(failure))
1750
1891
  && /JSON|Expected ','|after array element/.test(String(failure))
1751
- const reasonCode = batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
1892
+ const outputLimited = turnEnd?.data?.reason?.kind === 'max-tokens'
1893
+ const execution = outputLimited ? executionContext : null
1894
+ const reasonCode = outputLimited ? 'model-output-limit' : batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
1895
+ const outputLimitError = outputLimited
1896
+ ? failure + '; 输出预算不足(含思考/剩余上下文限制),请调整宿主最大输出 token 或使用模型支持的思考档位;待处理范围未结算'
1897
+ : failure
1898
+ // 思考强度不被支持 = 配置与模型不匹配,失败发生在回合起点、代价极小:
1899
+ // 学习该组合(下次 fork 不带档)并把本次标记可重试,让下一次扫描很快接住。
1900
+ const effortRefusal = effortRefusalOf(failure)
1901
+ if (effortRefusal) {
1902
+ markEffortRefused(effortRefusal.key)
1903
+ // 同时清掉该快照的失败连击:失败是配置不匹配(已学习),不是这段转录有病——
1904
+ // 不清零的话 snapshot-failed-too-many 闸门会让自动重试永远进不来。
1905
+ safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: 'failed', ids: [] }))
1906
+ }
1752
1907
  if (batchJsonInvalid) setSessionBinding(sessionId, { consolidationSingleOnly: true })
1753
1908
  // worker 模式:回合失败即退役条件 5,不带病工作、不做交接(§4.5)。
1754
1909
  if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
1755
- safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable: batchJsonInvalid, error: failure }))
1910
+ const retryable = outputLimited || batchJsonInvalid || Boolean(effortRefusal)
1911
+ safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable, error: outputLimitError, executionKey: execution?.key || null, executionSettingsKey: execution?.settingsKey || null, executionDefaultsComparable: execution?.defaultsComparable ?? true }))
1756
1912
  return finish({
1757
- ok: false, error: 'consolidation fork failed: ' + failure, sessionId, childId,
1758
- settled: false, timedOut: false, retryable: batchJsonInvalid, reasonCode,
1913
+ ok: false, error: 'consolidation fork failed: ' + outputLimitError, sessionId, childId,
1914
+ settled: false, timedOut: false, retryable, reasonCode,
1915
+ ...(outputLimited ? { configuredMaxTokens: agentOptions.maxTokens ?? execution.maxTokens } : {}),
1759
1916
  })
1760
1917
  }
1761
1918
  // 父授权重验:写入可能已经落了一部分,但凭证只有在授权还成立时才算数。