@capybara-hq/kernel 0.1.0-rc.29 → 0.1.0-rc.30

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 (62) hide show
  1. package/bootstrap.json +27 -27
  2. package/dist/admin/admin.schemas.d.ts +7 -0
  3. package/dist/config/schema.d.ts +0 -2
  4. package/dist/config/schema.js +0 -16
  5. package/dist/conversations/conversations.controller.d.ts +11 -1
  6. package/dist/conversations/conversations.controller.js +25 -1
  7. package/dist/conversations/conversations.schemas.d.ts +8 -0
  8. package/dist/conversations/conversations.schemas.js +14 -0
  9. package/dist/conversations/conversations.service.d.ts +12 -0
  10. package/dist/conversations/conversations.service.js +10 -0
  11. package/dist/conversations/event-log.d.ts +14 -0
  12. package/dist/conversations/events.d.ts +12 -0
  13. package/dist/conversations/events.js +35 -3
  14. package/dist/db/kernel-schema.d.ts +5 -0
  15. package/dist/errors.d.ts +3 -0
  16. package/dist/errors.js +3 -0
  17. package/dist/evals/plan.d.ts +20 -15
  18. package/dist/evals/plan.js +29 -6
  19. package/dist/evals/reconstruct.d.ts +16 -1
  20. package/dist/evals/reconstruct.js +55 -1
  21. package/dist/evals/sets.service.d.ts +3 -2
  22. package/dist/evals/sets.service.js +16 -2
  23. package/dist/evals/step-replay.d.ts +6 -0
  24. package/dist/evals/step-replay.js +5 -0
  25. package/dist/evals/trajectory.d.ts +5 -1
  26. package/dist/evals/trajectory.js +3 -1
  27. package/dist/evals/worker.js +2 -1
  28. package/dist/identity/settings.d.ts +64 -0
  29. package/dist/identity/settings.js +86 -2
  30. package/dist/orgs/roles.d.ts +1 -1
  31. package/dist/orgs/roles.js +2 -0
  32. package/dist/orgs/settings.service.d.ts +17 -0
  33. package/dist/orgs/settings.service.js +31 -3
  34. package/dist/platform/ops/admin.ops.js +8 -2
  35. package/dist/platform/ops/conversations.ops.js +34 -0
  36. package/dist/platform/ops/evals.ops.js +12 -1
  37. package/dist/platform/ops/orgs.ops.js +1 -0
  38. package/dist/runtime/compaction-progress.d.ts +62 -0
  39. package/dist/runtime/compaction-progress.js +82 -0
  40. package/dist/runtime/compaction-settings.service.d.ts +16 -0
  41. package/dist/runtime/compaction-settings.service.js +42 -0
  42. package/dist/runtime/compaction.service.d.ts +50 -0
  43. package/dist/runtime/compaction.service.js +75 -0
  44. package/dist/runtime/context/compaction.d.ts +90 -12
  45. package/dist/runtime/context/compaction.js +256 -21
  46. package/dist/runtime/context/fit.d.ts +79 -0
  47. package/dist/runtime/context/fit.js +202 -0
  48. package/dist/runtime/model-call.d.ts +134 -5
  49. package/dist/runtime/model-call.js +766 -335
  50. package/dist/runtime/run-control.d.ts +6 -1
  51. package/dist/runtime/run-control.js +7 -0
  52. package/dist/runtime/run-queue.d.ts +14 -0
  53. package/dist/runtime/run-queue.js +75 -0
  54. package/dist/runtime/run-steps.d.ts +3 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.d.ts +14 -2
  57. package/dist/runtime/run-worker.js +160 -33
  58. package/dist/runtime/runtime.module.js +11 -0
  59. package/dist/runtime/stream.js +15 -0
  60. package/dist/tools/pipeline.js +6 -3
  61. package/package.json +1 -1
  62. package/src/migrations/0132_compact_runs.sql +6 -0
@@ -5,7 +5,8 @@ import { ApiError } from "../errors.js";
5
5
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
6
6
  import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
7
7
  import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
8
- import { acceptSummary, buildCompactionRequest, compactionBackoff, compactionPlan, shouldCompact, } from "./context/compaction.js";
8
+ import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, nextTranscriptChunk, shouldCompact, summarySavedTokens, } from "./context/compaction.js";
9
+ import { applyFit, clampOutput, effectiveReserve, estimateAfterFit, fitTarget, planFit, } from "./context/fit.js";
9
10
  import { guardToolPairs } from "./context/pairing.js";
10
11
  import { TOOLS_UNSUPPORTED_REMINDER, turnLimitReminder } from "./context/reminders.js";
11
12
  import { calibrate, estimateTokens } from "./context/tokens.js";
@@ -37,6 +38,15 @@ export function toolsUnavailableReminder(unavailable) {
37
38
  * also the message of the `model.hook_denied` error a denied `ctx.models.embed` call rejects with.
38
39
  */
39
40
  export const modelDeniedText = (plugin, reason) => `Model request blocked by the "${plugin}" policy hook: ${reason}`;
41
+ /**
42
+ * The `run.context_too_large` message (user-facing, not model-visible): the hard fit guard could
43
+ * not bring the request under `W - O - R` even after dropping all older history and truncating the
44
+ * latest turn, so the system prompt, tools and the latest message are themselves too large
45
+ * (context compaction spec §4.3 point 4).
46
+ */
47
+ export const contextTooLargeText = (model, target, estimate) => `The request is too large for the model "${model.displayName}" (estimated ${estimate} input tokens, ` +
48
+ `at most ${target} fit in its ${model.contextWindow}-token context window after the output cap and ` +
49
+ "reserve). Shorten the message or choose a model with a larger context window.";
40
50
  /** 可重试错误在同一模型上重试前的默认等待(供应商未给 retryAfterMs 时)。 */
41
51
  const DEFAULT_RETRY_DELAY_MS = 1000;
42
52
  /**
@@ -73,8 +83,64 @@ export class RunError extends Error {
73
83
  export const assistantIdemKey = (runId, step) => `assistant:${runId}:${step}`;
74
84
  /** 某步第 attempt 次模型调用的 model_call 幂等键(管线据此找到模型实际收到的工具)。 */
75
85
  export const modelCallIdemKey = (runId, step, attempt) => `model_call:${runId}:${step}:${attempt}`;
76
- /** 一步最多的模型调用尝试次数(主模型、同模型重试、兜底,见 `ladder`)。 */
86
+ /**
87
+ * The ladder's three rungs: the main model, one same-model retry and the fallback (see `ladder`).
88
+ * A step may make more calls than this: reactive `model.context_overflow` fix-ups retry on the same
89
+ * rung, all within {@link MAX_STEP_MODEL_CALLS}.
90
+ */
77
91
  export const MAX_MODEL_ATTEMPTS = 3;
92
+ /**
93
+ * The most `model_call` rows one step may write (context compaction spec §4.4): the ladder's three
94
+ * rungs plus up to two reactive-overflow fix-up retries. The ladder stops before a further attempt,
95
+ * so a persistent `model.context_overflow` cannot loop.
96
+ */
97
+ export const MAX_STEP_MODEL_CALLS = MAX_MODEL_ATTEMPTS + 2;
98
+ /**
99
+ * The progressively smaller fit targets of a reactive trim, as fractions of the model's window
100
+ * (context compaction spec §4.3 point 5 / §4.4 point 3). The trim fix-up tries them most
101
+ * aggressive first (70%, then 80%, then 90% of the window) and uses the first target a fit plan
102
+ * actually reaches, so the retry really shrinks a request the provider rejected. `null` when the
103
+ * request already fits every target (nothing to trim).
104
+ */
105
+ export const REACTIVE_TRIM_FACTORS = [0.9, 0.8, 0.7];
106
+ /**
107
+ * The agent's tools for one request, resolved now (connectors and extensions can change between
108
+ * steps): disabled tools and disabled sub-agent tools, a sub-agent's narrower roster, sandbox
109
+ * scoping and replay mode, with `Skill` offered when the log has a catalog snapshot or an
110
+ * invocation. The automatic step path and a manual compact run resolve them the same way, so the
111
+ * compaction sees the same history a step would.
112
+ */
113
+ export async function resolveAgentTools(deps, input, events) {
114
+ const resolved = await deps.tools.forAgent(input.orgId, {
115
+ disabledTools: input.agent.disabledTools,
116
+ subagentTools: input.agent.subagentTools,
117
+ subagents: input.agent.subagents,
118
+ child: input.parent !== undefined || input.parentRunId !== undefined || input.subagent === true,
119
+ forkChild: input.parent?.forSkill === true,
120
+ sandboxConversationId: input.parent?.rootConversationId ?? input.conversationId,
121
+ replay: input.conversationKind === "eval",
122
+ source: input.source,
123
+ skillLoad: skillLoadOffered(events.findLast((e) => e.type === "skills_catalog"), hasInvocation(events)),
124
+ });
125
+ return {
126
+ tools: resolved.tools,
127
+ toolSearch: resolved.toolSearch === true,
128
+ unavailable: resolved.unavailable,
129
+ };
130
+ }
131
+ /** The step's {@link StepTools} from resolved tools: a fresh attachment cache unless one is shared. */
132
+ export function stepToolsOf(resolved, input, deps) {
133
+ return {
134
+ list: resolved.tools,
135
+ toolSearch: resolved.toolSearch,
136
+ media: {
137
+ looked: new Set(),
138
+ info: new Map(),
139
+ bytes: new Map(),
140
+ run: input.mediaCache ?? new MediaCache(deps.config.get().attachments.requestMediaBytes),
141
+ },
142
+ };
143
+ }
78
144
  const idem = {
79
145
  assistant: assistantIdemKey,
80
146
  usage: (runId, step) => `usage:${runId}:${step}`,
@@ -87,8 +153,21 @@ const idem = {
87
153
  .slice(0, 16)}`,
88
154
  modelCall: modelCallIdemKey,
89
155
  hookDenied: (runId, step, attempt) => `hook_denied:${runId}:${step}:${attempt}`,
90
- /** Usage of a compaction call: `n` is the compaction attempt (consecutive failures + 1). */
91
- compactionUsage: (runId, step, n) => `usage_compaction:${runId}:${step}:${n}`,
156
+ /**
157
+ * Usage of a compaction call: `n` is the compaction attempt (consecutive failures + 1). A
158
+ * chunked compaction sends one call per chunk, so the chunk index (1-based) is part of the key
159
+ * (context compaction spec §4.5).
160
+ */
161
+ compactionUsage: (runId, step, n, chunk) => chunk === undefined
162
+ ? `usage_compaction:${runId}:${step}:${n}`
163
+ : `usage_compaction:${runId}:${step}:${n}:${chunk}`,
164
+ /**
165
+ * The outcome of one compaction attempt: `n` is the attempt (consecutive failures + 1). Retrying
166
+ * the same attempt after a crash writes nothing new; a manual compact run is keyed by its run id
167
+ * and step 0 (context compaction spec §4.7).
168
+ */
169
+ compactionSummary: (runId, step, n) => `compaction_summary:${runId}:${step}:${n}`,
170
+ compactionFailed: (runId, step, n) => `compaction_failed:${runId}:${step}:${n}`,
92
171
  mediaExcluded: (runId, step, attempt, part) => `media_excluded:${runId}:${step}:${attempt}:${part}`,
93
172
  };
94
173
  /** 外部 signal 已触发:本步按「中止」收尾。 */
@@ -133,7 +212,7 @@ wrapUpReason) {
133
212
  try {
134
213
  if (signal.aborted)
135
214
  throw new StepAborted();
136
- let events = await readAll(deps.eventLog, conversationId);
215
+ let events = await readAllEvents(deps.eventLog, conversationId);
137
216
  // an earlier execution of this run already sent this step (it streamed, then crashed or was
138
217
  // handed over): this one starts at offset 0, so viewers drop that attempt's draft first
139
218
  if (events.some((e) => e.type === "model_call" && e.runId === runId && e.payload.step === step)) {
@@ -151,29 +230,12 @@ wrapUpReason) {
151
230
  // 每步实时解析(连接器 / 插件状态可能在步骤之间变化),解析结果记在 model_call;收尾调用同样带工具
152
231
  // a skills catalog snapshot (Ruling M17; an empty one too) or a person's skill invocation in the
153
232
  // log → Skill is offered (see skillLoadOffered)
154
- const resolved = await deps.tools.forAgent(input.orgId, {
155
- disabledTools: input.agent.disabledTools,
156
- subagentTools: input.agent.subagentTools,
157
- subagents: input.agent.subagents,
158
- child: input.parent !== undefined || input.parentRunId !== undefined || input.subagent === true,
159
- forkChild: input.parent?.forSkill === true,
160
- sandboxConversationId: input.parent?.rootConversationId ?? input.conversationId,
161
- replay: input.conversationKind === "eval",
162
- source: input.source,
163
- skillLoad: skillLoadOffered(events.findLast((e) => e.type === "skills_catalog"), hasInvocation(events)),
164
- });
165
- const tools = {
166
- list: resolved.tools,
167
- toolSearch: resolved.toolSearch === true,
168
- media: {
169
- looked: new Set(),
170
- info: new Map(),
171
- bytes: new Map(),
172
- run: input.mediaCache ?? new MediaCache(deps.config.get().attachments.requestMediaBytes),
173
- },
174
- };
233
+ const resolved = await resolveAgentTools(deps, input, events);
234
+ const tools = stepToolsOf(resolved, input, deps);
175
235
  const beforeCompaction = events.length;
176
- events = await maybeCompact(deps, input, events, runtime, tools);
236
+ // the org's effective compaction settings, once for this step (org > platform > built-in)
237
+ const compaction = await deps.compactionSettings.resolve(input.orgId);
238
+ events = await maybeCompact(deps, input, events, runtime, compaction, tools);
177
239
  // a sub-agent checks its budget again after a compaction call, so the step's own request is
178
240
  // not a second call over the cap (review M5; the loop checks before each step); the budget
179
241
  // wrap-up is the one call allowed over it
@@ -224,7 +286,7 @@ wrapUpReason) {
224
286
  });
225
287
  }
226
288
  }
227
- const { outcome, ref } = await ladder(deps, input, events, runtime, tools, wrapUpReason, streamed);
289
+ const { outcome, ref } = await ladder(deps, input, events, runtime, compaction, tools, wrapUpReason, streamed);
228
290
  // assistant_message and usage in one append = one transaction, which also owes the usage's
229
291
  // usage.report delivery (transactional outbox spec §8.1)
230
292
  await appendCounted(deps, input, [
@@ -330,8 +392,8 @@ function lastToolsReminder(events, runId) {
330
392
  }
331
393
  return text;
332
394
  }
333
- /** 读会话的全部事件(读到当前 last_seq),按 seq 升序。 */
334
- async function readAll(eventLog, conversationId) {
395
+ /** 读会话的全部事件(读到当前 last_seq),按 seq 升序。A manual compact run reads it the same way. */
396
+ export async function readAllEvents(eventLog, conversationId) {
335
397
  const out = [];
336
398
  let after = 0;
337
399
  for (;;) {
@@ -345,32 +407,15 @@ async function readAll(eventLog, conversationId) {
345
407
  }
346
408
  /**
347
409
  * Appends one event and merges it into the step's local event list (an idempotent hit already in
348
- * the list is not added twice).
349
- *
350
- * Events written elsewhere after `readAll` (an interjection, a fork report the wait sweep wrote)
351
- * have a lower seq than this one: when the written seq is more than one above the local maximum,
352
- * the gap is read from the log and merged first (batch 5 review I2). So every event with
353
- * seq ≤ the request's `toSeq` is in hand when the request is built, exactly as `reconstruct`
354
- * (evals) reads the log; gap user_messages above `absorbedUpToSeq` are skipped by placement in
355
- * both.
410
+ * the list is not added twice). The gap merge is {@link mergeWritten}'s: events written elsewhere
411
+ * after `readAll` have a lower seq than this one, and a list that skipped them would claim to
412
+ * include them through the request's `toSeq`.
356
413
  */
357
414
  async function appendLocal(eventLog, conversationId, events, event) {
358
415
  const [written] = await eventLog.append(conversationId, [event]);
359
- if (!written || events.some((e) => e.seq === written.seq))
416
+ if (!written)
360
417
  return events;
361
- const localMax = events.reduce((m, e) => Math.max(m, e.seq), 0);
362
- const gap = [];
363
- let after = localMax;
364
- while (written.seq > after + 1) {
365
- const page = await eventLog.readAfter(conversationId, after, Math.min(READ_PAGE, written.seq - after - 1));
366
- const inGap = page.filter((e) => e.seq < written.seq);
367
- gap.push(...inGap);
368
- const last = inGap.at(-1);
369
- if (!last || inGap.length < page.length)
370
- break;
371
- after = last.seq;
372
- }
373
- return [...events, ...gap, written];
418
+ return mergeWritten(eventLog, conversationId, events, [written]);
374
419
  }
375
420
  /**
376
421
  * 某次尝试的模型参数:主模型尝试用 `agent.modelParams`,兜底尝试用 `agent.fallbackParams`,
@@ -383,12 +428,13 @@ function attemptParams(agent, info, fallback) {
383
428
  }
384
429
  /**
385
430
  * 发给模型的请求(纯函数):`buildModelRequest`(注入 `params` 与本步工具:模型不支持工具时不带;收尾调用带
386
- * `toolChoice: "none"`)→ `guardToolPairs`。输出上限:参数里有 `maxOutputTokens` 旋钮时取
387
- * `min(模型上限, 旋钮)`,否则 `min(模型上限, defaultMaxOutputTokens)`。
431
+ * `toolChoice: "none"`)→ `guardToolPairs` → the recorded `fit` plan (when given). 输出上限:参数里有
432
+ * `maxOutputTokens` 旋钮时取 `min(模型上限, 旋钮)`,否则 `min(模型上限, defaultMaxOutputTokens)`;记录了输出
433
+ * 上限的基线回放(`recordedMaxOutputTokens`)原样取记录值,旋钮不再覆盖。
388
434
  * 运行时({@link runModelStep})与由日志还原请求(`evals/reconstruct.ts`)共用这一份,二者不会漂移。
389
435
  */
390
436
  export function assembleModelRequest(input) {
391
- const { defaultMaxOutputTokens, tools, ...rest } = input;
437
+ const { defaultMaxOutputTokens, recordedMaxOutputTokens, tools, fit, ...rest } = input;
392
438
  const built = buildModelRequest({
393
439
  ...rest,
394
440
  tools: input.model.capabilities.tools ? [...tools] : [],
@@ -397,6 +443,11 @@ export function assembleModelRequest(input) {
397
443
  request.messages = guardToolPairs(request.messages);
398
444
  const knob = request.params.maxOutputTokens;
399
445
  request.maxOutputTokens = Math.min(input.model.maxOutputTokens, typeof knob === "number" ? knob : defaultMaxOutputTokens);
446
+ // the recorded cap already carries the clamp against the recorded window and estimate
447
+ if (recordedMaxOutputTokens !== undefined)
448
+ request.maxOutputTokens = recordedMaxOutputTokens;
449
+ if (fit !== undefined)
450
+ request.messages = applyFit(request, fit).messages;
400
451
  return built;
401
452
  }
402
453
  /**
@@ -518,22 +569,42 @@ function consecutiveCompactionFailures(events) {
518
569
  }
519
570
  return n;
520
571
  }
572
+ /** Estimated input tokens of a plain text (a user message's only content). */
573
+ function textTokens(text) {
574
+ return estimateTokens([{ role: "user", content: [{ type: "text", text }] }], []);
575
+ }
521
576
  /**
522
- * 压缩:校正后的估算达到阈值、且不在失败退避期内时,用主模型生成摘要(非流式消费)。
523
- * 通过 → `compaction_summary`;过短或出错 → `compaction_failed`(attempt 从 1 起,连续失败递增),
524
- * 本步按原样继续。主模型此刻解析不了时跳过压缩,交给降级梯子处理。
577
+ * Compaction: summarize the earlier conversation with the main model (consumed non-streaming) when
578
+ * the calibrated estimate crosses the trigger (context compaction spec §4.1). The hard line
579
+ * (`estimate + output > window`) ignores `enabled: false` and the failure backoff; the proactive
580
+ * trigger respects both. Accepted → `compaction_summary`; too short or an error →
581
+ * `compaction_failed` (attempt from 1, consecutive failures increment), and the step continues
582
+ * unchanged. When the main model cannot be resolved right now, compaction is skipped and the
583
+ * fallback ladder handles the step.
584
+ *
585
+ * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
586
+ * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
587
+ * than the agent's main model.
588
+ *
589
+ * The one execution both paths run: the automatic step path through {@link maybeCompact} and a
590
+ * manual compact run through `CompactionService.force`.
525
591
  */
526
- async function maybeCompact(deps, input, events, runtime, tools) {
527
- if (compactionBackoff(events))
528
- return events;
592
+ export async function runCompaction(deps, input, events, runtime, compaction, tools, opts = {}) {
593
+ /** Nothing was written (the compaction was skipped): the step's own path just continues. */
594
+ const skipped = (evs) => ({
595
+ events: evs,
596
+ summarySeq: null,
597
+ failed: false,
598
+ });
599
+ const modelRef = opts.ref ?? input.agent.model;
529
600
  let provider;
530
601
  let info;
531
602
  try {
532
- ({ provider, info } = await deps.registry.resolve(input.orgId, input.agent.model));
603
+ ({ provider, info } = await deps.registry.resolve(input.orgId, modelRef));
533
604
  }
534
605
  catch (err) {
535
- deps.log.warn("compaction skipped: model unavailable", { model: input.agent.model, err });
536
- return events;
606
+ deps.log.warn("compaction skipped: model unavailable", { model: modelRef, err });
607
+ return skipped(events);
537
608
  }
538
609
  try {
539
610
  await loadMedia(deps, input, events, info, tools);
@@ -541,23 +612,53 @@ async function maybeCompact(deps, input, events, runtime, tools) {
541
612
  catch (err) {
542
613
  if (!(err instanceof MediaUnavailableError))
543
614
  throw err;
544
- // 存储暂时不可用:本步跳过压缩,交给降级梯子(会按可重试错误处理)
615
+ // storage is temporarily unavailable: skip compaction for this step and leave it to the
616
+ // fallback ladder, which treats it as a retryable error
545
617
  deps.log.warn("compaction skipped: attachment storage unavailable", {
546
618
  conversationId: input.conversationId,
547
619
  err,
548
620
  });
549
- return events;
621
+ return skipped(events);
550
622
  }
551
- const { estimate: raw } = buildRequest(deps, events, input, info, attemptParams(input.agent, info, false).value, runtime, tools, false);
623
+ const { request: built, estimate: raw } = buildRequest(deps, events, input, info, attemptParams(input.agent, info, opts.fallback === true).value, runtime, tools, false);
552
624
  const estimate = calibrate(raw, lastActual(events));
553
- if (!shouldCompact(estimate, info, runtime.compactionThreshold))
554
- return events;
555
- const plan = compactionPlan(events, runtime.keepRecentTurns);
625
+ // The trigger's output cap is the step's own cap, min(agent max, model max) (spec §4.1), not the
626
+ // settings' maxOutputTokens — that one caps the summary call (spec §4.8).
627
+ const output = built.maxOutputTokens;
628
+ // The hard line ignores both gates: enabled: false turns proactive early compaction off only,
629
+ // and backoff only delays proactive attempts (context compaction spec §4.1). The reactive path
630
+ // (`force`) ignores the trigger entirely (spec §4.4).
631
+ if (!opts.force) {
632
+ if (estimate + output <= info.contextWindow && compactionBackoff(events))
633
+ return skipped(events);
634
+ if (!shouldCompact(estimate, info.contextWindow, { ...compaction, maxOutputTokens: output })) {
635
+ return skipped(events);
636
+ }
637
+ }
638
+ // the input room left for the kept tail: the window minus the output cap and the reserve
639
+ // (compactionInputBudget), minus the system prompt and tool definitions every request carries
640
+ const tailBudget = compactionInputBudget(info.contextWindow, output, compaction.reserveTokens) -
641
+ estimateTokens([], built.system, built.tools);
642
+ const plan = compactionPlan(events, compaction, tailBudget);
556
643
  if (!plan)
557
- return events;
644
+ return skipped(events);
558
645
  const { runId, step, signal, conversationId } = input;
559
- const ref = input.agent.model;
560
- const request = buildCompactionRequest(plan.transcript, info.id);
646
+ const ref = modelRef;
647
+ // §4.6 progress: from here the compaction is certain, so the conversation may show a row. It is
648
+ // display-only (Redis + a bus message, never the log); a lost update costs nothing.
649
+ const startedAt = Date.now();
650
+ const progressOf = (progress) => {
651
+ deps.compactionProgress?.update({
652
+ runId,
653
+ conversationId,
654
+ ...(input.agentId !== undefined && { agentId: input.agentId }),
655
+ progress,
656
+ });
657
+ };
658
+ progressOf({ phase: "preparing", step, startedAt });
659
+ // the summary call's output cap: the org's effective setting, never above the model's own cap
660
+ // (context compaction spec §4.8)
661
+ const summaryCap = Math.min(compaction.maxOutputTokens, info.maxOutputTokens);
561
662
  const attemptNo = consecutiveCompactionFailures(events) + 1;
562
663
  // hooks see compaction calls like step attempts (I-1): same scope, chat runs only
563
664
  const scope = hookScope(deps.hooks, input);
@@ -569,126 +670,308 @@ async function maybeCompact(deps, input, events, runtime, tools) {
569
670
  provider: ref.provider,
570
671
  model: ref.model,
571
672
  };
572
- if (hookBase && deps.hooks?.has("model.request")) {
573
- let verdict;
574
- try {
575
- verdict = await deps.hooks.run("model.request", { ...hookBase, request: hookRequestOf(request, deps.log) }, signal);
673
+ // §4.5: one summary call's input room is B = Wc - Cmax - R. The room the running summary takes
674
+ // in the next call (at least half of the output cap) and the request's fixed overhead (the
675
+ // instruction and the transcript wrapper) are subtracted from it, leaving the chunk size. A
676
+ // transcript over it is summarised chunk by chunk, each call sent the running summary before its
677
+ // chunk; the actual running summary can be up to the full output cap, so each call after the
678
+ // first shrinks its chunk to that estimate. A degenerate budget (a window smaller than the cap,
679
+ // the reserve, the overhead and the allowance, or one that leaves less than a usable chunk)
680
+ // leaves the single call as before: a chunk below the floor would fail the first call instead.
681
+ const budget = compactionInputBudget(info.contextWindow, summaryCap, compaction.reserveTokens);
682
+ const overhead = compactionRequestOverhead();
683
+ const allowance = Math.ceil(summaryCap / 2);
684
+ const baseChunkSize = compactionChunkSize(budget, summaryCap);
685
+ // the whole transcript is one call unless it is over a usable base chunk size
686
+ let remaining = baseChunkSize >= MIN_COMPACTION_CHUNK_TOKENS && textTokens(plan.transcript) > baseChunkSize
687
+ ? plan.transcript
688
+ : null;
689
+ /** Whether this compaction is chunked (real `i/N` progress only in this path). */
690
+ const chunked = remaining !== null;
691
+ /** The chunk count the current chunk size plans (updated when the running summary shrinks it). */
692
+ let plannedChunks = chunked ? chunkTranscript(plan.transcript, baseChunkSize).length : 0;
693
+ let lastChunkSize = baseChunkSize;
694
+ let failure = null;
695
+ /** The 1-based chunk whose call failed or was denied, when the compaction was chunked. */
696
+ let failedChunk = null;
697
+ let denial = null;
698
+ let summary = "";
699
+ /** Whether the compaction really took more than one call. */
700
+ let multiChunk = false;
701
+ /** The chunk calls made; the total is known only when the compaction ends. */
702
+ let attempted = 0;
703
+ const usages = [];
704
+ for (;;) {
705
+ let chunkText;
706
+ if (remaining === null) {
707
+ chunkText = plan.transcript;
576
708
  }
577
- catch (e) {
578
- // run() rejects only when the run's signal aborted: an abort, never a deny
579
- if (signal.aborted)
580
- throw new StepAborted();
581
- throw e;
709
+ else {
710
+ // this call's chunk: the previous call's summary may be longer than the allowance, so
711
+ // reserve its real estimate (the allowance is only the floor)
712
+ const held = Math.max(allowance, summary === "" ? 0 : textTokens(`[Earlier summary]\n${summary}\n\n`));
713
+ const size = Math.min(baseChunkSize, budget - overhead - held);
714
+ // A chunk below the floor would make nextTranscriptChunk clamp to one token: fail with a
715
+ // clear reason instead of a call storm (context compaction spec §4.5).
716
+ if (size < MIN_COMPACTION_CHUNK_TOKENS) {
717
+ failure = `the running summary leaves too little room for a chunk (${Math.max(0, size)} tokens, at least ${MIN_COMPACTION_CHUNK_TOKENS} needed)`;
718
+ failedChunk = attempted + 1;
719
+ break;
720
+ }
721
+ const next = nextTranscriptChunk(remaining, size);
722
+ if (next === null)
723
+ break;
724
+ chunkText = next.chunk;
725
+ remaining = next.rest.length === 0 ? null : next.rest;
726
+ if (remaining !== null)
727
+ multiChunk = true;
728
+ // the real total, recomputed only when the running summary shrank this call's chunk
729
+ if (size !== lastChunkSize) {
730
+ lastChunkSize = size;
731
+ plannedChunks =
732
+ attempted + 1 + (remaining === null ? 0 : chunkTranscript(remaining, size).length);
733
+ }
582
734
  }
583
- if (!verdict.allowed) {
584
- // compaction fails (generic reason in the log, raw detail only in the audit row, R12); the
585
- // step continues and its own request meets the hooks next
586
- const site = {
587
- orgId: input.orgId,
588
- conversationId,
589
- runId,
590
- ...(input.accountId !== undefined && { accountId: input.accountId }),
591
- ...(input.agentId !== undefined && { agentId: input.agentId }),
592
- idemKey: `hook_denied_compaction:${runId}:${step}:${attemptNo}`,
593
- };
594
- const denied = hookDeniedEvent(site, "model.request", verdict, { step, attempt: 1 });
595
- const entry = hookDeniedAudit(site, denied.payload, verdict);
596
- entry.detail = { ...entry.detail, purpose: "compaction" };
597
- const failed = {
598
- type: "compaction_failed",
599
- runId,
600
- payload: {
601
- attempt: attemptNo,
602
- reason: `compaction request blocked by the "${verdict.plugin}" policy hook (${verdict.cause})`,
603
- },
604
- };
605
- deps.log.warn("compaction blocked by a policy hook", {
606
- conversationId,
607
- plugin: verdict.plugin,
608
- cause: verdict.cause,
609
- });
610
- const written = await deps.stepLog.appendAudited(conversationId, [failed], entry);
611
- if (written.length > 0) {
612
- await deps.eventLog.notify(conversationId, Math.max(...written.map((e) => e.seq)));
735
+ attempted++;
736
+ const chunkNo = attempted;
737
+ const current = {
738
+ phase: "summarizing",
739
+ step,
740
+ startedAt,
741
+ ...(chunked ? { chunk: chunkNo, chunks: plannedChunks } : {}),
742
+ chars: 0,
743
+ };
744
+ progressOf(current);
745
+ // call 1 summarises chunk 1; call i carries the running summary before its chunk, which the
746
+ // instruction merges (compactionPlan formats a previous summary the same way)
747
+ const callInput = summary === "" ? chunkText : `[Earlier summary]\n${summary}\n\n${chunkText}`;
748
+ const request = buildCompactionRequest(callInput, info.id, summaryCap);
749
+ if (hookBase && deps.hooks?.has("model.request")) {
750
+ let verdict;
751
+ try {
752
+ verdict = await deps.hooks.run("model.request", { ...hookBase, request: hookRequestOf(request, deps.log) }, signal);
753
+ }
754
+ catch (e) {
755
+ // run() rejects only when the run's signal aborted: an abort, never a deny
756
+ if (signal.aborted) {
757
+ // an aborted attempt leaves no partial summary: drop the progress key now rather than
758
+ // leaving the writer-local throttle entry behind until the TTL (folded review Minor)
759
+ deps.compactionProgress?.clear(runId);
760
+ throw new StepAborted();
761
+ }
762
+ throw e;
763
+ }
764
+ if (!verdict.allowed) {
765
+ denial = { verdict, chunk: chunkNo };
766
+ break;
613
767
  }
614
- return mergeLocal(events, written);
615
768
  }
616
- }
617
- let failure = null;
618
- let summary = "";
619
- let usage = null;
620
- const sentAt = Date.now();
621
- try {
622
- let partial = "";
623
- const out = await consumeModelStream(provider, request, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
624
- if (ev.type === "text_delta")
769
+ const sentAt = Date.now();
770
+ try {
771
+ let partial = "";
772
+ const out = await consumeModelStream(provider, request, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
773
+ if (ev.type !== "text_delta")
774
+ return;
625
775
  partial += ev.text;
626
- });
627
- usage = out.usage;
628
- if (hookBase && deps.hooks) {
629
- fireObserve(deps.hooks, "model.response", {
630
- ...hookBase,
631
- outcome: "ok",
632
- content: out.content,
633
- stopReason: out.stopReason,
634
- usage: out.usage,
635
- latencyMs: Date.now() - sentAt,
636
- }, signal, deps.log);
776
+ // throttled by the sink (≤ once per 200 ms); real characters, never a percentage
777
+ progressOf({
778
+ phase: "summarizing",
779
+ step,
780
+ startedAt,
781
+ ...(chunked ? { chunk: chunkNo, chunks: plannedChunks } : {}),
782
+ chars: partial.length,
783
+ });
784
+ });
785
+ usages.push({ chunk: multiChunk ? chunkNo : undefined, usage: out.usage });
786
+ if (hookBase && deps.hooks) {
787
+ fireObserve(deps.hooks, "model.response", {
788
+ ...hookBase,
789
+ outcome: "ok",
790
+ content: out.content,
791
+ stopReason: out.stopReason,
792
+ usage: out.usage,
793
+ latencyMs: Date.now() - sentAt,
794
+ }, signal, deps.log);
795
+ }
796
+ const final = out.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
797
+ // store only the <summary> block: the <analysis> scratchpad must not enter later requests
798
+ summary = extractSummary(final || partial);
799
+ // an intermediate call with nothing to carry forward would silently drop every chunk before
800
+ // it: fail the compaction instead (spec §4.5), no partial summary
801
+ if (remaining !== null && summary === "") {
802
+ failure = "a chunk produced no summary";
803
+ failedChunk = multiChunk ? chunkNo : null;
804
+ break;
805
+ }
806
+ // the last call's text is the summary, accepted against the full transcript (spec §4.5)
807
+ if (remaining === null && !acceptSummary(summary, plan.transcript)) {
808
+ failure = `summary too short (${summary.length} chars)`;
809
+ failedChunk = multiChunk ? chunkNo : null;
810
+ }
637
811
  }
638
- const final = out.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
639
- summary = (final || partial).trim();
640
- if (!acceptSummary(summary, plan.transcript)) {
641
- failure = `summary too short (${summary.length} chars)`;
812
+ catch (err) {
813
+ if (err instanceof StepAborted) {
814
+ // aborted mid-call: clear the progress key here (the success and failure paths clear at
815
+ // the end; the abort path throws past them)
816
+ deps.compactionProgress?.clear(runId);
817
+ throw err;
818
+ }
819
+ if (hookBase && deps.hooks) {
820
+ fireObserve(deps.hooks, "model.response", {
821
+ ...hookBase,
822
+ outcome: "failed",
823
+ content: [],
824
+ stopReason: null,
825
+ usage: null,
826
+ latencyMs: Date.now() - sentAt,
827
+ errorCode: classify(err).code,
828
+ }, signal, deps.log);
829
+ }
830
+ failure = err instanceof Error ? err.message : String(err);
831
+ failedChunk = multiChunk ? chunkNo : null;
832
+ break;
642
833
  }
834
+ if (failure !== null || denial !== null)
835
+ break;
836
+ // the whole transcript was this one call, or its last chunk is done
837
+ if (remaining === null)
838
+ break;
643
839
  }
644
- catch (err) {
645
- if (err instanceof StepAborted)
646
- throw err;
647
- if (hookBase && deps.hooks) {
648
- fireObserve(deps.hooks, "model.response", {
649
- ...hookBase,
650
- outcome: "failed",
651
- content: [],
652
- stopReason: null,
653
- usage: null,
654
- latencyMs: Date.now() - sentAt,
655
- errorCode: classify(err).code,
656
- }, signal, deps.log);
840
+ // only a compaction that still has something to write shows the writing phase: a failed or denied
841
+ // one jumps straight to its failure event (folded review Minor)
842
+ if (failure === null && denial === null) {
843
+ progressOf({ phase: "writing", step, startedAt });
844
+ }
845
+ /** The chunk a failure stopped at, for the reason (empty when the compaction was not chunked). */
846
+ const chunkNote = (chunk) => (chunk === null ? "" : ` (chunk ${chunk})`);
847
+ /** One usage event per completed call (spec §4.5); a chunked call carries its chunk index. */
848
+ const usageEvents = () => usages.map(({ chunk, usage }) => ({
849
+ type: "usage",
850
+ runId,
851
+ idemKey: idem.compactionUsage(runId, step, attemptNo, chunk),
852
+ payload: {
853
+ step,
854
+ provider: ref.provider,
855
+ model: ref.model,
856
+ ...usage,
857
+ purpose: "compaction",
858
+ ...(chunk !== undefined ? { chunk, chunks: attempted } : {}),
859
+ },
860
+ }));
861
+ if (denial !== null) {
862
+ // compaction fails (generic reason in the log, raw detail only in the audit row, R12); the
863
+ // step continues and its own request meets the hooks next
864
+ const verdict = denial.verdict;
865
+ const site = {
866
+ orgId: input.orgId,
867
+ conversationId,
868
+ runId,
869
+ ...(input.accountId !== undefined && { accountId: input.accountId }),
870
+ ...(input.agentId !== undefined && { agentId: input.agentId }),
871
+ idemKey: `hook_denied_compaction:${runId}:${step}:${attemptNo}`,
872
+ };
873
+ const denied = hookDeniedEvent(site, "model.request", verdict, { step, attempt: 1 });
874
+ const entry = hookDeniedAudit(site, denied.payload, verdict);
875
+ entry.detail = { ...entry.detail, purpose: "compaction" };
876
+ const failed = {
877
+ type: "compaction_failed",
878
+ runId,
879
+ idemKey: idem.compactionFailed(runId, step, attemptNo),
880
+ payload: {
881
+ attempt: attemptNo,
882
+ reason: `compaction request blocked by the "${verdict.plugin}" policy hook (${verdict.cause})${chunkNote(multiChunk ? denial.chunk : null)}`,
883
+ },
884
+ };
885
+ deps.log.warn("compaction blocked by a policy hook", {
886
+ conversationId,
887
+ plugin: verdict.plugin,
888
+ cause: verdict.cause,
889
+ });
890
+ // the chunk calls that completed before the denial are still billed and reported
891
+ const billed = usages.length > 0 ? await appendCounted(deps, input, usageEvents()) : [];
892
+ const written = await deps.stepLog.appendAudited(conversationId, [failed], entry);
893
+ if (written.length > 0) {
894
+ await deps.eventLog.notify(conversationId, Math.max(...written.map((e) => e.seq)));
657
895
  }
658
- failure = err instanceof Error ? err.message : String(err);
896
+ const merged = await mergeWritten(deps.eventLog, conversationId, events, [
897
+ ...billed,
898
+ ...written,
899
+ ]);
900
+ deps.compactionProgress?.clear(runId);
901
+ return { events: merged, summarySeq: null, failed: true };
902
+ }
903
+ if (failure !== null) {
904
+ deps.log.warn("compaction failed", { conversationId, reason: failure });
659
905
  }
660
906
  const event = failure === null
661
907
  ? {
662
908
  type: "compaction_summary",
663
909
  runId,
664
- payload: { coversUpToSeq: plan.coversUpToSeq, text: summary },
910
+ // the manual compact run's run id is in it; a crash-retried attempt writes nothing twice
911
+ idemKey: idem.compactionSummary(runId, step, attemptNo),
912
+ payload: {
913
+ coversUpToSeq: plan.coversUpToSeq,
914
+ text: summary,
915
+ // what compaction saved: the estimated transcript input minus the stored summary
916
+ // output (context compaction spec §4.9)
917
+ savedTokens: summarySavedTokens(plan.transcript, summary),
918
+ },
665
919
  }
666
920
  : {
667
921
  type: "compaction_failed",
668
922
  runId,
669
- payload: { attempt: attemptNo, reason: failure },
923
+ idemKey: idem.compactionFailed(runId, step, attemptNo),
924
+ payload: { attempt: attemptNo, reason: `${failure}${chunkNote(failedChunk)}` },
670
925
  };
671
- if (failure !== null) {
672
- deps.log.warn("compaction failed", { conversationId, reason: failure });
673
- }
674
- // the compaction call's usage (I-1): logged with the outcome in one append (one transaction), marked
675
- // `purpose: "compaction"` so step consumers (calibration, trajectory steps, replay plans) skip it
676
- const batch = [event];
677
- if (usage !== null) {
678
- batch.push({
679
- type: "usage",
680
- runId,
681
- idemKey: idem.compactionUsage(runId, step, attemptNo),
682
- payload: { step, provider: ref.provider, model: ref.model, ...usage, purpose: "compaction" },
683
- });
684
- }
926
+ // the compaction calls' usage (I-1): logged with the outcome in one append (one transaction),
927
+ // marked `purpose: "compaction"` so step consumers (calibration, trajectory steps, replay plans)
928
+ // skip it; a chunked compaction writes one per call, each keyed by its chunk
929
+ const batch = [event, ...usageEvents()];
685
930
  const written = await appendCounted(deps, input, batch);
686
- return mergeLocal(events, written);
931
+ const merged = await mergeWritten(deps.eventLog, conversationId, events, written);
932
+ deps.compactionProgress?.clear(runId);
933
+ return {
934
+ events: merged,
935
+ summarySeq: failure === null ? (written.find((e) => e.type === "compaction_summary")?.seq ?? null) : null,
936
+ failed: failure !== null,
937
+ };
938
+ }
939
+ /**
940
+ * The automatic path's compaction: {@link runCompaction} under the trigger's gates, returning only
941
+ * the step's event list (the step does not care whether a summary was written).
942
+ */
943
+ async function maybeCompact(deps, input, events, runtime, compaction, tools, opts = {}) {
944
+ return (await runCompaction(deps, input, events, runtime, compaction, tools, opts)).events;
687
945
  }
688
- /** Merges written events into the local list (idempotent hits already in it are not added twice). */
689
- function mergeLocal(events, written) {
690
- const fresh = written.filter((w) => !events.some((e) => e.seq === w.seq));
691
- return fresh.length === 0 ? events : [...events, ...fresh];
946
+ /**
947
+ * Merges events we just wrote into the step's local list, reading any gap first (the guarantee
948
+ * {@link appendLocal} gives): another writer may have appended an event between the local maximum
949
+ * and a seq we wrote, and a request built from a list that skipped it would claim (through its
950
+ * `toSeq`) to include an event it does not carry. Idempotent hits already in the list are not added
951
+ * twice; the result is ordered by seq.
952
+ */
953
+ async function mergeWritten(eventLog, conversationId, events, written) {
954
+ const fresh = written
955
+ .filter((w) => !events.some((e) => e.seq === w.seq))
956
+ .sort((a, b) => a.seq - b.seq);
957
+ if (fresh.length === 0)
958
+ return events;
959
+ const out = [...events];
960
+ let after = events.reduce((m, e) => Math.max(m, e.seq), 0);
961
+ for (const w of fresh) {
962
+ while (w.seq > after + 1) {
963
+ const page = await eventLog.readAfter(conversationId, after, Math.min(READ_PAGE, w.seq - after - 1));
964
+ const inGap = page.filter((e) => e.seq > after && e.seq < w.seq);
965
+ out.push(...inGap);
966
+ const last = inGap.at(-1);
967
+ if (!last || inGap.length < page.length)
968
+ break;
969
+ after = last.seq;
970
+ }
971
+ out.push(w);
972
+ after = w.seq;
973
+ }
974
+ return out.sort((a, b) => a.seq - b.seq);
692
975
  }
693
976
  /**
694
977
  * 降级梯子:主模型 → 主模型重试一次(等 `retryAfterMs ?? 1000`,可被中止)→ `agent.fallback`(若有)。
@@ -701,7 +984,7 @@ function mergeLocal(events, written) {
701
984
  * not configured in the org: spec B §5.3) goes straight to `agent.fallback` when there is one,
702
985
  * without the same-model retry.
703
986
  */
704
- async function ladder(deps, input, events, runtime, tools, wrapUpReason, streamed) {
987
+ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpReason, streamed) {
705
988
  const { conversationId, runId, step, signal, sink, agent } = input;
706
989
  const wrapUp = wrapUpReason !== null;
707
990
  const turnReminder = wrapUpReason === "budget"
@@ -721,13 +1004,15 @@ async function ladder(deps, input, events, runtime, tools, wrapUpReason, streame
721
1004
  let last;
722
1005
  /** The agent's model did not resolve (`agent.model_unavailable`): only the fallback is left. */
723
1006
  let mainUnavailable = false;
1007
+ /** A reactive overflow used up this step's fix-ups: only the fallback (a different window) is left. */
1008
+ let skipToFallback = false;
724
1009
  let attempt = 0;
725
1010
  // hooks fire only for chat runs that have a registry (eval replays omit it, P-18)
726
1011
  const scope = hookScope(deps.hooks, input);
727
- /** 本次尝试发出的请求里带了字节的附件(供应商拒收时写 media_excluded)。 */
1012
+ /** The attachments whose bytes the last sent request carried (a provider rejection excludes them). */
728
1013
  let sentMedia = [];
729
1014
  for (const rung of rungs) {
730
- if (mainUnavailable && !rung.fallback)
1015
+ if ((mainUnavailable || skipToFallback) && !rung.fallback)
731
1016
  continue;
732
1017
  if (last && !rung.fallback && (last.retryAfterMs ?? 0) > MAX_RETRY_AFTER_MS) {
733
1018
  deps.log.warn("model retry skipped: suggested wait exceeds cap", {
@@ -738,194 +1023,340 @@ async function ladder(deps, input, events, runtime, tools, wrapUpReason, streame
738
1023
  });
739
1024
  continue;
740
1025
  }
741
- attempt++;
742
- if (last) {
743
- sink({ kind: "step_reset", runId, step });
744
- streamed.text = "";
745
- if (!rung.fallback)
746
- await abortableSleep(last.retryAfterMs ?? DEFAULT_RETRY_DELAY_MS, signal);
747
- }
748
- sentMedia = [];
749
- /** When the request went out (model.response fires only for sent requests). */
750
- let sentAt;
751
- /** Whether this attempt resolved its model (a failure before it is a resolve failure). */
752
- let resolved = false;
753
- try {
754
- const { provider, info } = await deps.registry.resolve(input.orgId, rung.ref);
755
- resolved = true;
756
- if (tools.list.length > 0 && !info.capabilities.tools) {
757
- evs = await appendLocal(deps.eventLog, conversationId, evs, {
758
- type: "reminder",
759
- runId,
760
- idemKey: idem.toolsUnsupported(runId, step),
761
- payload: { step, text: TOOLS_UNSUPPORTED_REMINDER },
762
- });
1026
+ // reactive `model.context_overflow` fix-ups, at most one of each per rung (context compaction
1027
+ // spec §4.4): media exclusion, forced compaction, then a progressive trim
1028
+ let mediaFixup = false;
1029
+ let compactFixup = false;
1030
+ let trimFixup = false;
1031
+ /** Force a compaction call before this rung's next attempt. */
1032
+ let forceCompact = false;
1033
+ /** Apply the progressive reactive trim to this rung's next attempt. */
1034
+ let trimPending = false;
1035
+ /** This attempt is a same-rung overflow fix-up (no same-model retry delay). */
1036
+ let sameRung = false;
1037
+ for (;;) {
1038
+ // a step writes at most MAX_STEP_MODEL_CALLS model_call rows, then stops: never a loop
1039
+ if (attempt >= MAX_STEP_MODEL_CALLS)
1040
+ break;
1041
+ attempt++;
1042
+ if (last) {
1043
+ sink({ kind: "step_reset", runId, step });
1044
+ streamed.text = "";
1045
+ if (!rung.fallback && !sameRung) {
1046
+ await abortableSleep(last.retryAfterMs ?? DEFAULT_RETRY_DELAY_MS, signal);
1047
+ }
763
1048
  }
764
- if (turnReminder !== null) {
765
- evs = await appendLocal(deps.eventLog, conversationId, evs, {
766
- type: "reminder",
767
- runId,
768
- idemKey: idem.reminder(runId, step),
769
- payload: { step, text: turnReminder },
1049
+ sameRung = false;
1050
+ sentMedia = [];
1051
+ /** Whether this attempt applies the reactive trim. */
1052
+ const trimForAttempt = trimPending;
1053
+ trimPending = false;
1054
+ /** When the request went out (model.response fires only for sent requests). */
1055
+ let sentAt;
1056
+ /** Whether this attempt resolved its model (a failure before it is a resolve failure). */
1057
+ let resolved = false;
1058
+ try {
1059
+ const { provider, info } = await deps.registry.resolve(input.orgId, rung.ref);
1060
+ resolved = true;
1061
+ if (forceCompact) {
1062
+ forceCompact = false;
1063
+ // the rung's model, not the agent's: a fallback may have a smaller window (spec §4.4)
1064
+ evs = await maybeCompact(deps, input, evs, runtime, compaction, tools, {
1065
+ force: true,
1066
+ ref: rung.ref,
1067
+ fallback: rung.fallback,
1068
+ });
1069
+ }
1070
+ if (tools.list.length > 0 && !info.capabilities.tools) {
1071
+ evs = await appendLocal(deps.eventLog, conversationId, evs, {
1072
+ type: "reminder",
1073
+ runId,
1074
+ idemKey: idem.toolsUnsupported(runId, step),
1075
+ payload: { step, text: TOOLS_UNSUPPORTED_REMINDER },
1076
+ });
1077
+ }
1078
+ if (turnReminder !== null) {
1079
+ evs = await appendLocal(deps.eventLog, conversationId, evs, {
1080
+ type: "reminder",
1081
+ runId,
1082
+ idemKey: idem.reminder(runId, step),
1083
+ payload: { step, text: turnReminder },
1084
+ });
1085
+ }
1086
+ const params = attemptParams(agent, info, rung.fallback);
1087
+ await loadMedia(deps, input, evs, info, tools);
1088
+ const { request, meta, estimate } = buildRequest(deps, evs, input, info, params.value, runtime, tools, wrapUp);
1089
+ // the hard fit guard (context compaction spec §4.3): the output cap is first clamped to what
1090
+ // the window leaves after the input, the reserve to what the clamped cap leaves, and a request
1091
+ // over the resulting target is trimmed deterministically. The plan is recorded and replayed
1092
+ // byte-for-byte; a request the system prompt, tools and latest turn cannot bring under the
1093
+ // target fails before any provider call.
1094
+ request.maxOutputTokens = clampOutput(info.contextWindow, request.maxOutputTokens, estimate);
1095
+ const reserve = effectiveReserve(info.contextWindow, request.maxOutputTokens, compaction.reserveTokens);
1096
+ const target = fitTarget(info.contextWindow, request.maxOutputTokens, reserve);
1097
+ const planned = trimForAttempt
1098
+ ? reactiveTrimPlan(evs, request, info, request.maxOutputTokens, reserve, estimate)
1099
+ : planFit({
1100
+ events: evs,
1101
+ request,
1102
+ model: info,
1103
+ maxOutputTokens: request.maxOutputTokens,
1104
+ reserveTokens: reserve,
1105
+ estimate,
1106
+ });
1107
+ let sentRequest = request;
1108
+ let sentEstimate = estimate;
1109
+ if (planned !== null) {
1110
+ const after = estimateAfterFit(request, estimate, planned);
1111
+ // a reactive trim is best effort (the estimate may be wrong; the provider is the backstop);
1112
+ // the ordinary hard-fit guard stays strict and fails before any provider call
1113
+ if (!trimForAttempt && after > target) {
1114
+ throw new RunError("run.context_too_large", contextTooLargeText(info, target, after));
1115
+ }
1116
+ sentRequest = applyFit(request, planned);
1117
+ sentEstimate = after;
1118
+ }
1119
+ sentMedia = (meta.media ?? []).flatMap((m) => m.outcome === "bytes" ? [m.attachmentId] : []);
1120
+ // model.request before model_call: a denied request is never logged as sent nor sent (a denial
1121
+ // logged before a crash is sticky: runStep checks it before compaction)
1122
+ if (scope && deps.hooks?.has("model.request")) {
1123
+ let verdict;
1124
+ try {
1125
+ verdict = await deps.hooks.run("model.request", {
1126
+ ...scope,
1127
+ purpose: "step",
1128
+ step,
1129
+ attempt,
1130
+ provider: rung.ref.provider,
1131
+ model: rung.ref.model,
1132
+ request: hookRequestOf(sentRequest, deps.log),
1133
+ }, signal);
1134
+ }
1135
+ catch (e) {
1136
+ // run() rejects only when the run's signal aborted: an abort, never a deny
1137
+ if (signal.aborted)
1138
+ throw new StepAborted();
1139
+ throw e;
1140
+ }
1141
+ if (!verdict.allowed) {
1142
+ await recordHookDenial(deps, {
1143
+ orgId: input.orgId,
1144
+ conversationId,
1145
+ runId,
1146
+ ...(input.accountId !== undefined && { accountId: input.accountId }),
1147
+ ...(input.agentId !== undefined && { agentId: input.agentId }),
1148
+ idemKey: idem.hookDenied(runId, step, attempt),
1149
+ }, "model.request", verdict, { step, attempt });
1150
+ throw new RunError("run.hook_denied", modelDeniedText(verdict.plugin, verdict.reason));
1151
+ }
1152
+ }
1153
+ // 请求里的工具定义(含目录里的)按指纹存进 tool_specs,与 model_call 同一事务
1154
+ // (请求可由日志 + tool_specs 还原)
1155
+ const sent = new Set([...meta.tools, ...(meta.catalog ?? [])].map((t) => t.specHash));
1156
+ const written = await deps.stepLog.appendWithSpecs(conversationId, tools.list.filter((x) => sent.has(x.specHash)), [
1157
+ {
1158
+ type: "model_call",
1159
+ runId,
1160
+ idemKey: idem.modelCall(runId, step, attempt),
1161
+ payload: {
1162
+ step,
1163
+ attempt,
1164
+ provider: rung.ref.provider,
1165
+ model: rung.ref.model,
1166
+ fallback: rung.fallback,
1167
+ request: {
1168
+ ...meta,
1169
+ maxOutputTokens: request.maxOutputTokens,
1170
+ ...(params.dropped.length > 0 && { droppedParams: params.dropped }),
1171
+ ...(planned !== null && { fit: planned }),
1172
+ // the request actually sent (post-fit): calibration and the trigger read this value
1173
+ estimatedInputTokens: sentEstimate,
1174
+ },
1175
+ },
1176
+ },
1177
+ ]);
1178
+ await deps.eventLog.notify(conversationId, Math.max(...written.map((e) => e.seq)));
1179
+ sentAt = Date.now();
1180
+ const outcome = await consumeModelStream(provider, sentRequest, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1181
+ if (ev.type === "text_delta") {
1182
+ streamed.text += ev.text;
1183
+ sink({ kind: "text", runId, step, text: ev.text });
1184
+ }
1185
+ else {
1186
+ sink({ kind: "thinking", runId, step, text: ev.text });
1187
+ }
770
1188
  });
771
- }
772
- const params = attemptParams(agent, info, rung.fallback);
773
- await loadMedia(deps, input, evs, info, tools);
774
- const { request, meta, estimate } = buildRequest(deps, evs, input, info, params.value, runtime, tools, wrapUp);
775
- sentMedia = (meta.media ?? []).flatMap((m) => m.outcome === "bytes" ? [m.attachmentId] : []);
776
- // model.request before model_call: a denied request is never logged as sent nor sent (a denial
777
- // logged before a crash is sticky: runStep checks it before compaction)
778
- if (scope && deps.hooks?.has("model.request")) {
779
- let verdict;
780
- try {
781
- verdict = await deps.hooks.run("model.request", {
1189
+ // the draft's last write, before the assistant_message is logged
1190
+ sink({ kind: "stream_end", runId, step });
1191
+ if (scope && deps.hooks) {
1192
+ fireObserve(deps.hooks, "model.response", {
782
1193
  ...scope,
783
1194
  purpose: "step",
784
1195
  step,
785
1196
  attempt,
786
1197
  provider: rung.ref.provider,
787
1198
  model: rung.ref.model,
788
- request: hookRequestOf(request, deps.log),
789
- }, signal);
790
- }
791
- catch (e) {
792
- // run() rejects only when the run's signal aborted: an abort, never a deny
793
- if (signal.aborted)
794
- throw new StepAborted();
795
- throw e;
796
- }
797
- if (!verdict.allowed) {
798
- await recordHookDenial(deps, {
799
- orgId: input.orgId,
800
- conversationId,
801
- runId,
802
- ...(input.accountId !== undefined && { accountId: input.accountId }),
803
- ...(input.agentId !== undefined && { agentId: input.agentId }),
804
- idemKey: idem.hookDenied(runId, step, attempt),
805
- }, "model.request", verdict, { step, attempt });
806
- throw new RunError("run.hook_denied", modelDeniedText(verdict.plugin, verdict.reason));
1199
+ outcome: "ok",
1200
+ content: outcome.content,
1201
+ stopReason: outcome.stopReason,
1202
+ usage: outcome.usage,
1203
+ latencyMs: Date.now() - sentAt,
1204
+ }, signal, deps.log);
807
1205
  }
1206
+ return { outcome, ref: rung.ref };
808
1207
  }
809
- // 请求里的工具定义(含目录里的)按指纹存进 tool_specs,与 model_call 同一事务
810
- // (请求可由日志 + tool_specs 还原)
811
- const sent = new Set([...meta.tools, ...(meta.catalog ?? [])].map((t) => t.specHash));
812
- const written = await deps.stepLog.appendWithSpecs(conversationId, tools.list.filter((x) => sent.has(x.specHash)), [
813
- {
814
- type: "model_call",
815
- runId,
816
- idemKey: idem.modelCall(runId, step, attempt),
817
- payload: {
1208
+ catch (err) {
1209
+ if (err instanceof StepAborted)
1210
+ throw err;
1211
+ if (signal.aborted)
1212
+ throw new StepAborted();
1213
+ // a hook denial is final (not retried, not reclassified)
1214
+ if (err instanceof RunError)
1215
+ throw err;
1216
+ const f = classify(err);
1217
+ if (scope && deps.hooks && sentAt !== undefined) {
1218
+ fireObserve(deps.hooks, "model.response", {
1219
+ ...scope,
1220
+ purpose: "step",
818
1221
  step,
819
1222
  attempt,
820
1223
  provider: rung.ref.provider,
821
1224
  model: rung.ref.model,
822
- fallback: rung.fallback,
823
- request: {
824
- ...meta,
825
- maxOutputTokens: request.maxOutputTokens,
826
- ...(params.dropped.length > 0 && { droppedParams: params.dropped }),
827
- estimatedInputTokens: estimate,
828
- },
829
- },
830
- },
831
- ]);
832
- await deps.eventLog.notify(conversationId, Math.max(...written.map((e) => e.seq)));
833
- sentAt = Date.now();
834
- const outcome = await consumeModelStream(provider, request, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
835
- if (ev.type === "text_delta") {
836
- streamed.text += ev.text;
837
- sink({ kind: "text", runId, step, text: ev.text });
838
- }
839
- else {
840
- sink({ kind: "thinking", runId, step, text: ev.text });
1225
+ outcome: "failed",
1226
+ content: [],
1227
+ stopReason: null,
1228
+ usage: null,
1229
+ latencyMs: Date.now() - sentAt,
1230
+ errorCode: f.code,
1231
+ }, signal, deps.log);
841
1232
  }
842
- });
843
- // the draft's last write, before the assistant_message is logged
844
- sink({ kind: "stream_end", runId, step });
845
- if (scope && deps.hooks) {
846
- fireObserve(deps.hooks, "model.response", {
847
- ...scope,
848
- purpose: "step",
849
- step,
850
- attempt,
851
- provider: rung.ref.provider,
852
- model: rung.ref.model,
853
- outcome: "ok",
854
- content: outcome.content,
855
- stopReason: outcome.stopReason,
856
- usage: outcome.usage,
857
- latencyMs: Date.now() - sentAt,
858
- }, signal, deps.log);
859
- }
860
- return { outcome, ref: rung.ref };
861
- }
862
- catch (err) {
863
- if (err instanceof StepAborted)
864
- throw err;
865
- if (signal.aborted)
866
- throw new StepAborted();
867
- // a hook denial is final (not retried, not reclassified)
868
- if (err instanceof RunError)
869
- throw err;
870
- const f = classify(err);
871
- if (scope && deps.hooks && sentAt !== undefined) {
872
- fireObserve(deps.hooks, "model.response", {
873
- ...scope,
874
- purpose: "step",
1233
+ deps.log.warn("model call attempt failed", {
1234
+ conversationId,
1235
+ runId,
875
1236
  step,
876
1237
  attempt,
877
- provider: rung.ref.provider,
878
- model: rung.ref.model,
879
- outcome: "failed",
880
- content: [],
881
- stopReason: null,
882
- usage: null,
883
- latencyMs: Date.now() - sentAt,
884
- errorCode: f.code,
885
- }, signal, deps.log);
886
- }
887
- deps.log.warn("model call attempt failed", {
888
- conversationId,
889
- runId,
890
- step,
891
- attempt,
892
- code: f.code,
893
- retryable: f.retryable,
894
- error: f.message,
895
- });
896
- if (!resolved &&
897
- !rung.fallback &&
898
- agent.fallback &&
899
- err instanceof ApiError &&
900
- !(err instanceof ProviderListError) &&
901
- err.code === "agent.model_unavailable") {
902
- mainUnavailable = true;
903
- last = f;
904
- continue;
905
- }
906
- if (!f.retryable) {
907
- if (REJECTS_MEDIA.has(f.code) && sentMedia.length > 0) {
908
- // 记录失败不能掩盖原来的失败码:只记 warn,本次运行照常以原错误失败
909
- try {
910
- await excludeMedia(deps, input, attempt, sentMedia);
1238
+ code: f.code,
1239
+ retryable: f.retryable,
1240
+ error: f.message,
1241
+ });
1242
+ if (!resolved &&
1243
+ !rung.fallback &&
1244
+ agent.fallback &&
1245
+ err instanceof ApiError &&
1246
+ !(err instanceof ProviderListError) &&
1247
+ err.code === "agent.model_unavailable") {
1248
+ mainUnavailable = true;
1249
+ last = f;
1250
+ break;
1251
+ }
1252
+ if (f.code === "model.context_overflow") {
1253
+ // reactive fix-ups, one of each per rung (context compaction spec §4.4). Each retries this
1254
+ // rung in the same step, so it consumes one attempt.
1255
+ if (sentMedia.length > 0 && !mediaFixup) {
1256
+ mediaFixup = true;
1257
+ // record the rejection and merge it in: the retry rebuilds from the log and the bytes
1258
+ // become "rejected" placeholders. A failed write cannot change the log, so retrying
1259
+ // the same bytes would overflow again: skip the media retry and fall through to the
1260
+ // forced compaction instead.
1261
+ let recorded = false;
1262
+ try {
1263
+ evs = await mergeWritten(deps.eventLog, conversationId, evs, await excludeMedia(deps, input, attempt, sentMedia));
1264
+ recorded = true;
1265
+ }
1266
+ catch (e) {
1267
+ deps.log.warn("cannot record media_excluded", {
1268
+ conversationId,
1269
+ runId,
1270
+ step,
1271
+ err: e,
1272
+ });
1273
+ }
1274
+ if (recorded) {
1275
+ last = f;
1276
+ sameRung = true;
1277
+ continue;
1278
+ }
911
1279
  }
912
- catch (e) {
913
- deps.log.warn("cannot record media_excluded", { conversationId, runId, step, err: e });
1280
+ if (!compactFixup) {
1281
+ compactFixup = true;
1282
+ forceCompact = true;
1283
+ last = f;
1284
+ sameRung = true;
1285
+ continue;
1286
+ }
1287
+ if (!trimFixup) {
1288
+ trimFixup = true;
1289
+ trimPending = true;
1290
+ last = f;
1291
+ sameRung = true;
1292
+ continue;
914
1293
  }
1294
+ // exhausted: a fallback model (a different window) is the only rung worth trying
1295
+ if (!rung.fallback && agent.fallback) {
1296
+ skipToFallback = true;
1297
+ last = f;
1298
+ break;
1299
+ }
1300
+ throw new RunError(f.code, f.message);
915
1301
  }
916
- throw new RunError(f.code, f.message);
1302
+ if (!f.retryable) {
1303
+ if (REJECTS_MEDIA.has(f.code) && sentMedia.length > 0) {
1304
+ // recording the failure must not hide the original code: log only, and fail the run
1305
+ // with the original error as before
1306
+ try {
1307
+ await excludeMedia(deps, input, attempt, sentMedia);
1308
+ }
1309
+ catch (e) {
1310
+ deps.log.warn("cannot record media_excluded", {
1311
+ conversationId,
1312
+ runId,
1313
+ step,
1314
+ err: e,
1315
+ });
1316
+ }
1317
+ }
1318
+ throw new RunError(f.code, f.message);
1319
+ }
1320
+ last = f;
1321
+ break;
917
1322
  }
918
- last = f;
919
1323
  }
920
1324
  }
921
1325
  const f = last;
922
1326
  throw new RunError(f.code, f.message);
923
1327
  }
1328
+ /**
1329
+ * The deterministic fit plan for a reactive trim (context compaction spec §4.3 point 5 / §4.4): the
1330
+ * request is trimmed to fit 70%, then 80%, then 90% of the model's window, applying the first target
1331
+ * a plan actually reaches. Most aggressive first: the provider rejected a request the estimate
1332
+ * thought fit, so the retry must really shrink it, not leave the optimistic request unchanged.
1333
+ * Returns null only when the request already fits every target (nothing to trim). The plan is
1334
+ * ordinary and replays byte-for-byte like any other.
1335
+ */
1336
+ function reactiveTrimPlan(events, request, model, maxOutputTokens, reserveTokens, estimate) {
1337
+ for (let i = REACTIVE_TRIM_FACTORS.length - 1; i >= 0; i--) {
1338
+ const window = Math.max(1, Math.floor(REACTIVE_TRIM_FACTORS[i] * model.contextWindow));
1339
+ const plan = planFit({
1340
+ events,
1341
+ request,
1342
+ model: { ...model, contextWindow: window },
1343
+ maxOutputTokens,
1344
+ reserveTokens,
1345
+ estimate,
1346
+ });
1347
+ if (plan !== null)
1348
+ return plan;
1349
+ }
1350
+ return null;
1351
+ }
924
1352
  /** 不可重试、且可能由请求里的媒体引起的失败:带了媒体字节时写 `media_excluded`(Ruling M8)。 */
925
- const REJECTS_MEDIA = new Set(["model.invalid_request", "model.context_overflow"]);
1353
+ const REJECTS_MEDIA = new Set(["model.invalid_request"]);
926
1354
  /**
927
1355
  * 供应商拒收了带媒体的请求:把这些附件记进 `media_excluded`(每条最多 {@link MEDIA_EXCLUDED_MAX_IDS} 个),
928
- * 之后的请求一律换成占位,会话不会因同一个附件永久卡住(可由日志推出)。本次运行照常失败。
1356
+ * 之后的请求一律换成占位,会话不会因同一个附件永久卡住(可由日志推出)。
1357
+ *
1358
+ * The reactive path merges the returned events into the step's local list and retries in the same
1359
+ * step (context compaction spec §4.4); the non-retryable path lets the run fail as before.
929
1360
  */
930
1361
  async function excludeMedia(deps, input, attempt, ids) {
931
1362
  const { conversationId, runId, step } = input;
@@ -947,7 +1378,7 @@ async function excludeMedia(deps, input, attempt, ids) {
947
1378
  step,
948
1379
  attachmentIds: ids,
949
1380
  });
950
- await deps.eventLog.append(conversationId, events);
1381
+ return deps.eventLog.append(conversationId, events);
951
1382
  }
952
1383
  function classify(err) {
953
1384
  if (isModelError(err)) {