dsh-compaction-weave 0.0.0-stage → 0.3.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.
Files changed (92) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +145 -0
  4. package/README.md +148 -2
  5. package/cordis.patch.yml +19 -0
  6. package/docs/architecture.md +84 -0
  7. package/docs/benchmarks/published-0.3.2-rc.1-tests.json +576 -0
  8. package/docs/benchmarks/rc2-documentation.json +41 -0
  9. package/docs/benchmarks/rc2-linux-tests.json +590 -0
  10. package/docs/benchmarks/rc2-live-and-cost.json +746 -0
  11. package/docs/benchmarks/rc3-host-compatibility.json +2314 -0
  12. package/docs/benchmarks/rc4-tests.json +617 -0
  13. package/docs/benchmarks/review35-compression.json +117 -0
  14. package/docs/benchmarks/v0.3.2-live-four-way.json +3495 -0
  15. package/docs/benchmarks/v0.3.2-tests.json +590 -0
  16. package/docs/configuration.md +131 -0
  17. package/docs/development.md +95 -0
  18. package/docs/en/architecture.md +75 -0
  19. package/docs/en/configuration.md +131 -0
  20. package/docs/en/development.md +92 -0
  21. package/docs/en/feedback.md +47 -0
  22. package/docs/en/principles.md +235 -0
  23. package/docs/en/testing.md +368 -0
  24. package/docs/en/troubleshooting.md +60 -0
  25. package/docs/feedback.md +47 -0
  26. package/docs/images/principles-context.en.svg +77 -0
  27. package/docs/images/principles-context.zh.svg +77 -0
  28. package/docs/images/principles-pipeline.en.svg +93 -0
  29. package/docs/images/principles-pipeline.zh.svg +93 -0
  30. package/docs/images/principles-recovery.en.svg +46 -0
  31. package/docs/images/principles-recovery.zh.svg +46 -0
  32. package/docs/principles.md +235 -0
  33. package/docs/test-results.json +634 -0
  34. package/docs/testing.md +358 -0
  35. package/docs/troubleshooting.md +60 -0
  36. package/lib/abort.js +13 -0
  37. package/lib/action-state.js +60 -0
  38. package/lib/atomic-replace.js +18 -0
  39. package/lib/attachments.js +76 -0
  40. package/lib/audit-reject.js +161 -0
  41. package/lib/audit.js +939 -0
  42. package/lib/cache-policy.js +71 -0
  43. package/lib/client.js +696 -0
  44. package/lib/command-compact.js +38 -0
  45. package/lib/command-heartbeat.js +61 -0
  46. package/lib/config.js +596 -0
  47. package/lib/constraint-scope.js +37 -0
  48. package/lib/continuation-budget.js +69 -0
  49. package/lib/continuation-pending.js +57 -0
  50. package/lib/continuation-progress.js +46 -0
  51. package/lib/continuation.js +287 -0
  52. package/lib/engine-entry.js +103 -0
  53. package/lib/engine.js +2485 -0
  54. package/lib/failure-diagnostics.js +220 -0
  55. package/lib/history-source.js +74 -0
  56. package/lib/history.js +712 -0
  57. package/lib/idle-compaction.js +64 -0
  58. package/lib/index.js +611 -0
  59. package/lib/instruction-source.js +163 -0
  60. package/lib/journal.js +164 -0
  61. package/lib/manual-error.js +179 -0
  62. package/lib/memory-policy.js +383 -0
  63. package/lib/meter.js +387 -0
  64. package/lib/observation-mask.js +390 -0
  65. package/lib/proactive.js +108 -0
  66. package/lib/progress-facts.js +347 -0
  67. package/lib/progress-state.js +30 -0
  68. package/lib/prompt.js +194 -0
  69. package/lib/reconstruct.js +72 -0
  70. package/lib/reference-input.js +107 -0
  71. package/lib/region.js +972 -0
  72. package/lib/source-provenance.js +58 -0
  73. package/lib/source-recovery.js +22 -0
  74. package/lib/source-refs.js +137 -0
  75. package/lib/state.js +46 -0
  76. package/lib/storage-path.js +42 -0
  77. package/lib/summary-budget.js +187 -0
  78. package/lib/summary-config.js +308 -0
  79. package/lib/summary-progress.js +56 -0
  80. package/lib/summary-retry.js +27 -0
  81. package/lib/summary-timeout.js +68 -0
  82. package/lib/summary.js +476 -0
  83. package/lib/tools.js +341 -0
  84. package/lib/transaction-host.js +252 -0
  85. package/lib/transaction.js +285 -0
  86. package/lib/validate.js +503 -0
  87. package/lib/version.js +3 -0
  88. package/lib/window.js +120 -0
  89. package/lib/work-report.js +55 -0
  90. package/locale/en.json +6 -0
  91. package/locale/zh.json +6 -0
  92. package/package.json +71 -4
package/lib/summary.js ADDED
@@ -0,0 +1,476 @@
1
+ import {summaryRetryPolicy,retryableSummaryError,waitForSummaryRetry,CONTENT_RETRY_CODES} from './summary-retry.js';
2
+ import {beginDiagnosticAttempt,finishDiagnosticAttempt,trackAuditDiagnostic} from './failure-diagnostics.js';
3
+ import { combineSignals } from './abort.js';
4
+ import { buildSummaryRequest, assertSummaryCapacity, observeSummaryOverflow } from './summary-budget.js';
5
+ // L3 + L4:摘要调用。
6
+ //
7
+ // 抄的是 bili 的 `compress.externalSummary` 思路——摘要可以走另一个模型,
8
+ // 而且**失败要能降级**,不能因为摘要模型挂了就整个压缩失败。
9
+ //
10
+ // 与官方 `summarizeWithLlm` 的关键差异:
11
+ // 1. 目标是「按优先级排的链」,逐个尝试,第一个成功就用(bili 的做法)。
12
+ // 2. 每次尝试有独立超时(官方是整条链路共用一个 signal)。
13
+ // 3. 失败原因分类记录,便于用户看清"为什么这次没压成"。
14
+ // 4. 摘要指令作为**最后一条 user 消息**追加,前面的对话前缀保持原样,
15
+ // 这样 provider 的 KV cache 还能复用(这点官方做对了,照抄)。
16
+
17
+ import { SummaryAssembler, summaryText } from './meter.js';
18
+ import { SummaryProgress } from './summary-progress.js';
19
+ import { buildCompactionInstruction, detectLanguage } from './prompt.js';
20
+ import { unwrapJsonSectionMap } from './validate.js';
21
+
22
+ const COMPACTION_PURPOSE = 'compaction';
23
+
24
+ /**
25
+ * 从会话的持久路由里拿 provider/model,用于「摘要跟着主对话走」。
26
+ * @param {object} agent
27
+ */
28
+ export function latestDurableTarget(agent) {
29
+ const header = typeof agent?.session?.requestHeader === 'function' ? agent.session.requestHeader() : undefined;
30
+ const config = header?.config;
31
+ if (config && typeof config === 'object') {
32
+ const provider = typeof config.provider === 'string' ? config.provider : undefined;
33
+ const model = typeof config.model === 'string' ? config.model : undefined;
34
+ if (provider && model) {
35
+ return {
36
+ provider,
37
+ model,
38
+ reasoningEffort: config.reasoningEffort,
39
+ temperature: config.temperature,
40
+ stop: config.stop,
41
+ };
42
+ }
43
+ }
44
+ return undefined;
45
+ }
46
+
47
+ /**
48
+ * agent 自己声明的目标。
49
+ * @param {object} agent
50
+ */
51
+ export function agentTarget(agent) {
52
+ const options = agent?.options;
53
+ if (!options || typeof options !== 'object') return undefined;
54
+ const provider = typeof options.provider === 'string' ? options.provider : undefined;
55
+ const model = typeof options.model === 'string' ? options.model : undefined;
56
+ if (!provider || !model) return undefined;
57
+ return { provider, model, reasoningEffort: options.reasoningEffort, temperature: options.temperature, stop: options.stop };
58
+ }
59
+
60
+ /**
61
+ * 组装按优先级排的摘要目标链。
62
+ *
63
+ * @param {object} args
64
+ * @param {{summarizationProvider: string|null, summarizationModel: string|null}} args.config
65
+ * @param {object} args.agent
66
+ * @returns {{targets: {provider:string, model:string, reasoningEffort?:any, temperature?:any, stop?:any}[], source: string}}
67
+ */
68
+ export function resolveSummaryTargets({ config, agent }) {
69
+ const targets = [];
70
+ const seen = new Set();
71
+ const durable = latestDurableTarget(agent);
72
+ const declared = agentTarget(agent);
73
+ const push = (target, source) => {
74
+ if (!target) return false;
75
+ const key = `${target.provider}/${target.model}`;
76
+ if (seen.has(key)) return false;
77
+ seen.add(key);
78
+ targets.push({ ...target, source });
79
+ return true;
80
+ };
81
+
82
+ if (config.summarizationProvider && config.summarizationModel) {
83
+ const configured = { provider: config.summarizationProvider, model: config.summarizationModel };
84
+ // The configured route has priority, but must retain the active controls
85
+ // when it names that exact route. Deduplication must not erase MAX.
86
+ push({ ...configured, ...reusableControls(configured, declared), ...reusableControls(configured, durable) }, 'config');
87
+ }
88
+ push(durable, 'session');
89
+ push(declared, 'agent');
90
+
91
+ return { targets, source: targets[0]?.source ?? 'none' };
92
+ }
93
+
94
+ /**
95
+ * 只在同一个 provider/model 上复用采样参数——跨路由复用 reasoningEffort 会把
96
+ * 一个不支持的档位塞给另一个模型,直接 400。
97
+ */
98
+ function reusableControls(target, primary) {
99
+ if (!primary) return {};
100
+ if (target.provider !== primary.provider || target.model !== primary.model) return {};
101
+ const out = {};
102
+ if (primary.reasoningEffort !== undefined) out.reasoningEffort = primary.reasoningEffort;
103
+ if (primary.temperature !== undefined) out.temperature = primary.temperature;
104
+ if (primary.stop !== undefined) out.stop = primary.stop;
105
+ return out;
106
+ }
107
+
108
+ /**
109
+ * 调一次摘要。
110
+ *
111
+ * @param {object} args
112
+ * @param {object} args.ctx
113
+ * @param {object} args.agent
114
+ * @param {{messages: readonly any[], tools?: readonly any[]}} args.input
115
+ * @param {{provider:string, model:string}} args.target
116
+ * @param {{maxTokens:number, timeoutMs:number, language:'auto'|'zh'|'en', previousSummary?:string|null, primary?:any}} args.options
117
+ * @param {AbortSignal} args.signal
118
+ * @returns {Promise<{summary: readonly any[], rawText: string, provider: string, model: string, maxTokens: number, language: 'zh'|'en', usage: any}>}
119
+ */
120
+ export async function summarizeWithTarget(args) {
121
+ const { ctx, agent, input, target, options, signal } = args;
122
+
123
+ const request = buildSummaryRequest(input, options);
124
+ assertSummaryCapacity(request, options.capacity, target);
125
+ const { messages, language } = request;
126
+
127
+ const llmOptions = {
128
+ provider: target.provider,
129
+ model: target.model,
130
+ messages,
131
+ maxTokens: options.maxTokens,
132
+ purpose: COMPACTION_PURPOSE,
133
+ ...(typeof agent?.session?.id === 'string' ? { sessionId: agent.session.id } : {}),
134
+ ...reusableControls(target, options.primary),
135
+ ...(!options.isolatedTranscript && typeof agent?.session?.toolHistory === 'function' ? { toolHistory: agent.session.toolHistory() } : {}),
136
+ ...(Array.isArray(input.tools) && input.tools.length > 0 ? { tools: [...input.tools] } : {}),
137
+ };
138
+
139
+ const timeoutMs = Math.max(5000, options.timeoutMs);
140
+ const assembler = new SummaryAssembler();
141
+ const progress = new SummaryProgress();
142
+ const streamDiagnostics = () => ({...progress.snapshot(),chunks:assembler.chunkCount,textChars:assembler.text.length,reasoningChars:assembler.reasoningChars});
143
+ const timeoutError = cause => {
144
+ const diagnostics = streamDiagnostics();
145
+ const fields = Object.entries(diagnostics).map(([key,value])=>`${key}=${value === null ? 'none' : value}`).join(', ');
146
+ return Object.assign(new Error(
147
+ `summarization timed out after ${timeoutMs}ms (${fields})`,
148
+ cause === undefined ? undefined : {cause},
149
+ ), {code:'SUMMARY_TIMEOUT',timeoutMs,target:`${target.provider}/${target.model}`,diagnostics});
150
+ };
151
+ // One deadline owns both the plugin's rejection and adapter cancellation.
152
+ // Two independent timers can otherwise reject before the stream signal aborts.
153
+ const timeoutController = new AbortController();
154
+ const timeoutSignal = timeoutController.signal;
155
+ const combinedSignals = combineSignals([signal, timeoutSignal]);
156
+ const combined = combinedSignals.signal;
157
+ llmOptions.signal = combined;
158
+ const checkDeadline = () => {
159
+ // Synchronous persistence/adapter work and hot microtasks can defer the
160
+ // timer. Check the same monotonic deadline before dispatch or another read,
161
+ // not only after a response arrives. Caller cancellation keeps its reason.
162
+ if (progress.elapsed() >= timeoutMs && !signal?.aborted && !timeoutSignal.aborted) timeoutController.abort(timeoutError());
163
+ combined?.throwIfAborted?.();
164
+ };
165
+
166
+ // ⚠️ 传 `signal` 只是**请求**适配器自己停下来,不是保证。
167
+ // 适配器完全可以忽略这个字段、照旧把流吐完(第三方/自建后端都可能),
168
+ // 于是 `for await` 会在超时之后继续等,最终拿到一个迟到几秒的结果并当成成功。
169
+ // 这里必须自己在插件层建硬截止:
170
+ //
171
+ // - `abortPromise` 在超时/调用方取消时立刻 reject,把 await 抢回来;
172
+ // - 流结束后再确认一次"这还算不算数",迟到的结果一律拒收;
173
+ // - 抢回来之后把迭代器 `return()` 掉,别把底层请求留在后台。
174
+ let timer;
175
+ let onAbort;
176
+ const abortPromise = new Promise((_, reject) => {
177
+ const fire = (reason) => reject(reason);
178
+ timer = setTimeout(() => {
179
+ timeoutController.abort(timeoutError());
180
+ }, timeoutMs);
181
+ // ⚠️ 这个 promise 的拒绝必须**从创建那一刻起就有人接住**。
182
+ // 它只在 `Promise.race` 里被 await;如果初始化阶段就抛错(`ctx.llm.stream`
183
+ // 同步 throw、或者 `[Symbol.asyncIterator]()` 抛),race 根本没跑起来,
184
+ // 计时器到点后这个拒绝就成了 unhandledRejection —— 一次已经被 catch 住的
185
+ // 摘要失败,仍会在几秒后把进程带走。挂一个空的 catch 只是"标记已处理",
186
+ // 真正的判定仍由上面的 race 负责。
187
+ // ⚠️ 不要 `unref()`。这是个**必须按时触发**的截止计时器:unref 之后
188
+ // 事件循环里没有别的活儿时 Node 会直接退出,留下的表现是
189
+ // "unsettled top-level await" —— 超时根本没发生,硬截止就成了摆设。
190
+ if (combined?.aborted) {
191
+ fire(combined.reason ?? Object.assign(new Error('summarization aborted'), { code: 'ABORTED' }));
192
+ } else if (typeof combined?.addEventListener === 'function') {
193
+ onAbort = () => fire(combined.reason ?? Object.assign(new Error('summarization aborted'), { code: 'ABORTED' }));
194
+ combined.addEventListener('abort', onAbort, { once: true });
195
+ }
196
+ });
197
+
198
+ // ⚠️ 上面刚建的 abortPromise 在这里立刻标记为"已处理"。
199
+ // 它在 `Promise.race` 里被 await 时自然有人接;但下面流初始化可能同步抛错,
200
+ // 一旦抛出,race 就没有机会消费这个拒绝,计时器到点后它变成 unhandledRejection。
201
+ // 这条 `catch` 只是把 promise 标记为已处理 —— 判定结果仍然由 race 决定。
202
+ abortPromise.catch(() => {});
203
+
204
+ // ⚠️ 流与迭代器的初始化必须放进 try 里。宿主 `llm.stream` 走 waterfall,
205
+ // 中间的监听器允许同步 throw;`[Symbol.asyncIterator]()` 也可能抛。
206
+ // 放在 try 外面时,这两处一抛就直接跳过下面的 finally,计时器与 abort 监听器
207
+ // 都不会被清理,几秒后那次超时以未处理拒绝的形式炸出来。
208
+ let iterator;
209
+ let completed = false;
210
+ let requestStarted = false;
211
+ let streamFailure;
212
+ try {
213
+ await options.beforeRequest?.({target,maxTokens:options.maxTokens,requestBytes:request.inputUnits});
214
+ checkDeadline();
215
+ // Invocation can dispatch immediately or throw after dispatch. From this
216
+ // point on, missing usage is unknown, never proof that nothing was sent.
217
+ requestStarted = true;
218
+ iterator = ctx.llm.stream(llmOptions)[Symbol.asyncIterator]();
219
+ for (;;) {
220
+ checkDeadline();
221
+ const step = await Promise.race([iterator.next(), abortPromise]);
222
+ checkDeadline();
223
+ if (step.done) break;
224
+ progress.observe(assembler.push(step.value));
225
+ }
226
+ completed = true;
227
+ } catch (error) {
228
+ streamFailure=error;
229
+ if (error?.code === 'SUMMARY_TIMEOUT' || (timeoutSignal.aborted && !signal?.aborted)) {
230
+ const wrapped = error?.code === 'SUMMARY_TIMEOUT'
231
+ ? error
232
+ : timeoutError(error);
233
+ throw wrapped;
234
+ }
235
+ throw error;
236
+ } finally {
237
+ if (timer !== undefined) clearTimeout(timer);
238
+ if (onAbort !== undefined) combined?.removeEventListener?.('abort', onAbort);
239
+ combinedSignals.dispose();
240
+ if (!completed && iterator && typeof iterator.return === 'function') {
241
+ // 抢回控制权之后主动收尾:不 await(底层可能永远不结束),只求把
242
+ // 取消信号传下去,别让请求挂在后台继续烧额度。
243
+ try {
244
+ Promise.resolve(iterator.return()).catch(() => {});
245
+ } catch {
246
+ /* 迭代器已经死了 */
247
+ }
248
+ }
249
+ const failedFinish=['error','aborted'].includes(assembler.finish?.kind);
250
+ // Adapters can synthesize zero usage for a terminal service error. That
251
+ // cannot establish zero spend after dispatch; preserve positive reported
252
+ // usage, but account an all-zero failed attempt as unknown.
253
+ const unknownFailureUsage=(streamFailure||failedFinish)&&assembler.usage&&Object.values(assembler.usage).every(value=>value===0);
254
+ await options.afterRequest?.({target,usage:unknownFailureUsage?null:assembler.usage??null,completed,requestStarted,diagnostics:streamDiagnostics(),errorCode:timeoutSignal.aborted?'SUMMARY_TIMEOUT':streamFailure?.code??assembler.finish?.failure?.code??(streamFailure||failedFinish?'ERROR':null)});
255
+ }
256
+
257
+ // 迟到结果拒收:走到这里说明流跑完了,但可能是在超时之后才跑完的。
258
+ // 宿主拿到 `signal.aborted` 之后不该再提交任何东西(`SUMMARY_TIMEOUT` 也好、
259
+ // 调用方取消也好),否则"插件层硬截止"就只是个摆设。
260
+ if (timeoutSignal.aborted && !signal?.aborted) {
261
+ throw timeoutError();
262
+ }
263
+ if (signal?.aborted) {
264
+ throw Object.assign(new Error('summarization was cancelled'), { code: 'ABORTED', cause: signal.reason });
265
+ }
266
+ assembler.throwIfFailed();
267
+
268
+ const rawText = unwrapJsonSectionMap(assembler.text, { language });
269
+ const summary = rawText !== assembler.text ? [{ type: 'text', text: rawText }] : summaryText(assembler.blocks());
270
+ return {
271
+ summary,
272
+ rawText,
273
+ provider: target.provider,
274
+ model: target.model,
275
+ maxTokens: options.maxTokens,
276
+ // 把实际选中的语言带出去:调用方要按同一套小节标题做提交前校验,
277
+ // 自己再猜一遍(或按配置里的 `auto` 猜)会校验错模板。
278
+ language,
279
+ usage: assembler.usage,
280
+ diagnostics: streamDiagnostics(),
281
+ };
282
+ }
283
+
284
+ function sampleTextFor(messages) {
285
+ const parts = [];
286
+ for (let i = messages.length - 1; i >= 0 && parts.length < 12; i -= 1) {
287
+ const message = messages[i];
288
+ const content = message?.content;
289
+ if (typeof content === 'string') {
290
+ parts.push(content);
291
+ continue;
292
+ }
293
+ if (!Array.isArray(content)) continue;
294
+ for (const block of content) {
295
+ if (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
296
+ parts.push(block.text);
297
+ }
298
+ }
299
+ }
300
+ return parts.join('\n');
301
+ }
302
+
303
+ /**
304
+ * 依次尝试目标链;第一个成功即返回。
305
+ * 全失败时抛一个聚合错误,里面带上每一条的失败原因。
306
+ *
307
+ * @param {object} args
308
+ * @param {object} args.ctx
309
+ * @param {object} args.agent
310
+ * @param {{messages: readonly any[], tools?: readonly any[]}} args.input
311
+ * @param {{targets: readonly any[], source: string}} args.chain
312
+ * @param {{maxTokens:number, timeoutMs:number, language:'auto'|'zh'|'en', previousSummary?:string|null}} args.options
313
+ * @param {AbortSignal} args.signal
314
+ */
315
+ export async function summarizeWithChain(args) {
316
+ const { chain } = args;
317
+ if (!Array.isArray(chain.targets) || chain.targets.length === 0) {
318
+ const error = new Error(
319
+ 'no provider/model available for summarization: set both summarizationProvider and summarizationModel, ' +
320
+ 'route one request on this session, or set both agent provider/model options',
321
+ );
322
+ error.code = 'NO_SUMMARY_TARGET';
323
+ throw error;
324
+ }
325
+
326
+ const targets = args.options?.singleTarget === true ? chain.targets.slice(0,1) : chain.targets;
327
+ const primary = targets[0];
328
+ const failures = [];
329
+
330
+ const retry=summaryRetryPolicy(args.options);
331
+ const limit=retry.count+1;
332
+ const attempts=targets.map(target=>({target,feedback:null}));
333
+ let lastError;
334
+ for(let index=0;index<attempts.length && index<limit;index++) {
335
+ const {target,feedback}=attempts[index];
336
+ args.signal?.throwIfAborted?.();
337
+ const retryDelayMs=index>0?await waitForSummaryRetry(retry.delayMs,index,args.signal):0;
338
+ const record=beginDiagnosticAttempt(target,{maxTokens:args.options?.maxTokens,timeoutMs:args.options?.timeoutMs,retryCount:retry.count,retryDelayMs});
339
+ let localFailure=false,nextFeedback=feedback;
340
+ try {
341
+ const result=await summarizeWithTarget({ctx:args.ctx,agent:args.agent,input:args.input,target,signal:args.signal,
342
+ options:{...args.options,primary,repairFeedback:feedback,
343
+ beforeRequest:async meta=>{try{await args.options?.beforeRequest?.(meta);}catch(error){localFailure=true;throw error;}},
344
+ afterRequest:async meta=>{finishDiagnosticAttempt(record,meta);try{await args.options?.afterRequest?.(meta);}catch(error){localFailure=true;throw error;}},
345
+ }});
346
+ // ⚠️ 内容验收必须发生在**目标链内部**,不能等回到调用方再查。
347
+ //
348
+ // 三个摘要目标是按能力排的:主模型写不出合规摘要时,下一个目标(通常
349
+ // 更大或更守规矩)本来还有机会。但校验写在链外时,第一个目标吐出
350
+ // `Done.` 就直接把整次压缩判死 —— 降级链形同虚设,用户看到的是
351
+ // "压缩失败",而不是"换了个模型成功了"。
352
+ //
353
+ // 校验器由调用方注入(它才知道这次该按中文还是英文的小节标题查)。
354
+ const modelRawText = result.rawText;
355
+ const verdict = typeof args.options?.validate === 'function' ? await args.options.validate(result) : null;
356
+ if (verdict && verdict.ok === false) {
357
+ // Diagnostics are best effort and cannot affect acceptance or timing.
358
+ try { trackAuditDiagnostic(Promise.resolve(args.options?.onRejected?.({result, verdict, modelRawText, attempt:index+1}))).catch(() => {}); } catch {}
359
+ // A deterministic reconstruction is a NEW candidate, never approval
360
+ // of the rejected prose. Validate it from scratch, including shrinkage.
361
+ if (typeof args.options?.reconstruct === 'function') {
362
+ let rejectedResult = result, rejectedVerdict = verdict, rejectedText = modelRawText;
363
+ for (let repair = 0; repair < 8; repair++) {
364
+ const rebuilt = args.options.reconstruct({result: rejectedResult, verdict: rejectedVerdict, modelRawText: rejectedText});
365
+ if (!rebuilt) break;
366
+ const draft = rebuilt.rawText;
367
+ if (draft === rejectedText || Buffer.byteLength(draft,'utf8') - Buffer.byteLength(modelRawText,'utf8') > 8192) break;
368
+ const rebuiltVerdict = await args.options.validate(rebuilt);
369
+ if (rebuiltVerdict?.ok === true) {
370
+ args.signal?.throwIfAborted?.();
371
+ finishDiagnosticAttempt(record,{outcome:'accepted-after-reconstruction',diagnostics:result.diagnostics});
372
+ return rebuilt;
373
+ }
374
+ rejectedResult = rebuilt; rejectedVerdict = rebuiltVerdict; rejectedText = draft;
375
+ }
376
+ if (rejectedResult !== result) try { trackAuditDiagnostic(Promise.resolve(args.options?.onRejected?.({result:rejectedResult, verdict:rejectedVerdict, modelRawText, attempt:'reconstruction'}))).catch(() => {}); } catch {}
377
+ }
378
+ if (CONTENT_RETRY_CODES.has(verdict.code)) nextFeedback={code:verdict.code,message:verdict.message,issues:verdict.audit?.lost??[]};
379
+ const invalid = new Error(verdict.message ?? 'the summary did not pass content validation');
380
+ invalid.code = verdict.code ?? 'SUMMARY_INVALID';
381
+ throw invalid;
382
+ }
383
+ args.signal?.throwIfAborted?.();
384
+ finishDiagnosticAttempt(record,{outcome:'accepted',diagnostics:result.diagnostics});
385
+ return result;
386
+ } catch(error) {
387
+ finishDiagnosticAttempt(record,{outcome:'failed',error});
388
+ if(args.signal?.aborted || localFailure || error?.code==='CONTINUATION_CALL_BUDGET')throw error;
389
+ lastError=error;
390
+ if(error?.code==='SUMMARY_TIMEOUT') {
391
+ error.timeoutMs??=args.options?.timeoutMs;error.target??=`${target.provider}/${target.model}`;
392
+ }
393
+ observeSummaryOverflow(args.options?.capacity,target,error);
394
+ failures.push({target:`${target.provider}/${target.model}`,code:error?.code??'ERROR',message:error?.message??String(error)});
395
+ const retryable=retryableSummaryError(error);
396
+ // A changed-input window repair remains the caller's responsibility.
397
+ // Storage/cancellation/budget errors never enter this network retry loop.
398
+ if(retryable) {
399
+ if(!nextFeedback && CONTENT_RETRY_CODES.has(error?.code))nextFeedback={code:error.code,message:error.message,issues:[]};
400
+ attempts.push({target,feedback:nextFeedback});
401
+ } else if(!isWindowError(error) && error?.code!=='UNSUPPORTED_CONTENT')break;
402
+ }
403
+ }
404
+ if(lastError?.code==='SUMMARY_TIMEOUT') {
405
+ lastError.failures=failures;lastError.failureCodes=failures.map(f=>f.code);lastError.recoverable=false;
406
+ lastError.summaryAttempts=failures.length;lastError.summaryAttemptLimit=limit;lastError.summaryRetryExhausted=true;
407
+ throw lastError;
408
+ }
409
+
410
+ // 如果**每一个**目标都是因为内容不合规而失败,那就不该报"所有目标都失败了"。
411
+ // 这两件事对用户和对上层的含义完全不同:
412
+ // - "所有目标都失败" → 像是网络/额度问题,值得重试;
413
+ // - "没有一个目标写出合规摘要" → 是提示词/模型能力问题,重试同样的东西没用,
414
+ // 应该保留原上下文并让用户知道是内容不合格。
415
+ const onlyStructure = failures.length > 0 && failures.every((f) => STRUCTURE_CODES.has(f.code));
416
+ const error = new Error(
417
+ onlyStructure
418
+ ? `no summarization target produced an acceptable summary: ${failures.map((f) => `${f.target} → ${f.code}: ${f.message}`).join(' | ')}`
419
+ : `all summarization targets failed: ${failures.map((f) => `${f.target} → ${f.code}: ${f.message}`).join(' | ')}`,
420
+ );
421
+ const contentCodes = new Set(['PROGRESS_FACT_CONFLICT', 'SUMMARY_NOT_SMALLER', 'CONSTRAINT_LOST', 'CONSTRAINT_POLARITY_LOST', 'AUDIT_UNAVAILABLE']);
422
+ const commonCode = failures[0]?.code;
423
+ error.code = commonCode && contentCodes.has(commonCode) && failures.every(f => f.code === commonCode) ? commonCode : onlyStructure ? 'SUMMARY_STRUCTURE_INVALID' : 'SUMMARY_ALL_FAILED';
424
+ error.failures = failures;
425
+ error.cause = lastError;
426
+ error.summaryAttempts = failures.length;
427
+ error.summaryAttemptLimit = limit;
428
+ error.summaryRetryExhausted = failures.length >= limit && retryableSummaryError(lastError);
429
+ // ⚠️ 聚合之后必须把"是否值得少压一点再试"这个信息**带出来**。
430
+ // 否则调用方只看到一个笼统的 SUMMARY_ALL_FAILED,只能整体放弃 —— 那正是
431
+ // "渐进收敛写了却永远不可达"的原因:真正能靠缩小跨度救回来的窗口溢出,
432
+ // 被聚合错误抹平成了不可恢复失败。
433
+ error.recoverable = !error.summaryRetryExhausted && failures.some(
434
+ (f) =>
435
+ f.code === 'MAX_TOKENS' ||
436
+ f.code === 'UNSUPPORTED_CONTENT' ||
437
+ // ⚠️ 必须查 code。适配器把窗口溢出报成 `CONTEXT_WINDOW_EXCEEDED` 时,
438
+ // message 往往是"request failed"这种不含关键词的通用文案,只看 message
439
+ // 会把最该重试的一类失败判成不可恢复。
440
+ f.code === 'CONTEXT_WINDOW_EXCEEDED' ||
441
+ isWindowMessage(f.message),
442
+ );
443
+ error.failureCodes = failures.map((f) => f.code);
444
+ throw error;
445
+ }
446
+
447
+ const WINDOW_ERROR_RE = /context length|context window|too long|maximum context|CONTEXT_WINDOW_EXCEEDED/i;
448
+
449
+ // 内容不合规(不是"请求失败")。这类失败换一个目标模型值得再试一次:
450
+ // 同一条提示词,一个模型只回 `Done.`,另一个可能老老实实写满九节。
451
+ const STRUCTURE_CODES = new Set([
452
+ 'CONTINUATION_STRUCTURE',
453
+ 'CONTINUATION_TOOL_OUTPUT',
454
+ 'CONTINUATION_TOO_LARGE',
455
+ 'SUMMARY_STRUCTURE_INVALID',
456
+ 'CHECKPOINT_COVERAGE_INCOMPLETE',
457
+ 'EMPTY_SUMMARY',
458
+ 'CONSTRAINT_POLARITY_LOST',
459
+ ]);
460
+
461
+ function isWindowMessage(message) {
462
+ return typeof message === 'string' && WINDOW_ERROR_RE.test(message);
463
+ }
464
+
465
+ function isWindowError(error) {
466
+ if (isWindowMessage(error?.message)) return true;
467
+ if (error?.code === 'CONTEXT_WINDOW_EXCEEDED') return true;
468
+ // 有些适配器把上游原文塞进 cause 链,往下找两层。
469
+ let cause = error?.cause;
470
+ for (let depth = 0; depth < 3 && cause; depth += 1) {
471
+ if (isWindowMessage(cause.message)) return true;
472
+ if (cause.code === 'CONTEXT_WINDOW_EXCEEDED') return true;
473
+ cause = cause.cause;
474
+ }
475
+ return false;
476
+ }