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

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 (63) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplace-fetch.d.ts +5 -2
  3. package/dist/catalog/marketplace-fetch.js +4 -1
  4. package/dist/catalog/requests.service.d.ts +6 -5
  5. package/dist/catalog/requests.service.js +7 -6
  6. package/dist/config/load.d.ts +6 -0
  7. package/dist/config/load.js +26 -0
  8. package/dist/config/schema.js +5 -5
  9. package/dist/conversations/events.d.ts +10 -0
  10. package/dist/conversations/events.js +23 -1
  11. package/dist/devices/devices.controller.js +3 -2
  12. package/dist/devices/devices.service.d.ts +17 -5
  13. package/dist/devices/devices.service.js +24 -13
  14. package/dist/devices/dto.d.ts +7 -6
  15. package/dist/devices/dto.js +6 -5
  16. package/dist/errors.d.ts +6 -1
  17. package/dist/errors.js +6 -1
  18. package/dist/evals/reconstruct.js +18 -8
  19. package/dist/extensions/bootstrap.d.ts +1 -1
  20. package/dist/extensions/bootstrap.js +7 -1
  21. package/dist/extensions/installs.js +4 -1
  22. package/dist/lifecycle/kernel-lifecycle.js +1 -3
  23. package/dist/net/public-address.d.ts +14 -4
  24. package/dist/net/public-address.js +22 -12
  25. package/dist/net/safe-fetch.d.ts +2 -1
  26. package/dist/net/safe-fetch.js +16 -4
  27. package/dist/packages/npm.d.ts +28 -9
  28. package/dist/packages/npm.js +30 -19
  29. package/dist/packages/provenance.d.ts +3 -1
  30. package/dist/packages/provenance.js +7 -3
  31. package/dist/platform/ops/devices.ops.js +1 -1
  32. package/dist/platform/ops/platform.ops.d.ts +3 -1
  33. package/dist/platform/ops/platform.ops.js +11 -13
  34. package/dist/runtime/context/build.d.ts +10 -1
  35. package/dist/runtime/context/build.js +44 -10
  36. package/dist/runtime/context/compaction.d.ts +27 -8
  37. package/dist/runtime/context/compaction.js +133 -58
  38. package/dist/runtime/context/fit.d.ts +54 -22
  39. package/dist/runtime/context/fit.js +116 -40
  40. package/dist/runtime/model-call.d.ts +0 -8
  41. package/dist/runtime/model-call.js +185 -83
  42. package/dist/sandbox/review/classifier.d.ts +2 -0
  43. package/dist/sandbox/review/classifier.js +12 -1
  44. package/dist/sandbox/review/index.d.ts +3 -3
  45. package/dist/sandbox/review/index.js +3 -3
  46. package/dist/sandbox/review/review.service.d.ts +12 -4
  47. package/dist/sandbox/review/review.service.js +88 -19
  48. package/dist/sandbox/review/rules.d.ts +6 -0
  49. package/dist/sandbox/review/rules.js +1013 -95
  50. package/dist/sandbox/review/types.d.ts +21 -4
  51. package/dist/sandbox/review/types.js +41 -5
  52. package/dist/sandbox/sandbox.service.d.ts +8 -7
  53. package/dist/sandbox/sandbox.service.js +16 -16
  54. package/dist/setup/kernel-checks.js +3 -2
  55. package/dist/setup/oauth-token-probe.d.ts +1 -8
  56. package/dist/setup/oauth-token-probe.js +0 -16
  57. package/dist/tools/builtins/sandbox/common.d.ts +1 -1
  58. package/dist/tools/builtins/sandbox/common.js +1 -1
  59. package/dist/tools/builtins/tool-search.js +4 -3
  60. package/dist/tools/oauth/discovery.d.ts +38 -16
  61. package/dist/tools/oauth/discovery.js +59 -33
  62. package/dist/tools/pipeline.js +17 -13
  63. package/package.json +1 -1
@@ -54,13 +54,18 @@ function mediaMode(b, model) {
54
54
  return "bytes";
55
55
  return isText(b.mediaType) ? "inline" : "placeholder";
56
56
  }
57
- /** 最近摘要之后、会进请求的消息里,该模型需要字节的媒体块(按 seq 与块顺序)。 */
57
+ /**
58
+ * 最近摘要之后、会进请求的消息里,该模型需要字节的媒体块(按 seq 与块顺序);也包括随摘要再次发送的
59
+ * 用户消息(摘要的 `openingSeqs`,{@link summaryOpeners})。
60
+ */
58
61
  function mediaBlocks(events, model) {
59
62
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
60
- const after = latestSummary(sorted)?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
63
+ const summary = latestSummary(sorted);
64
+ const after = summary?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
65
+ const openers = new Set(summaryOpeners(sorted, summary));
61
66
  const out = [];
62
67
  for (const e of sorted) {
63
- if (e.seq <= after)
68
+ if (e.seq <= after && !openers.has(e))
64
69
  continue;
65
70
  if (e.type !== "user_message" && e.type !== "assistant_message")
66
71
  continue;
@@ -313,6 +318,17 @@ export function resolveMedia(content, model, ctx) {
313
318
  }
314
319
  return { blocks: out, tokens, outcomes };
315
320
  }
321
+ /**
322
+ * The user messages a summary re-renders after its text (context compaction spec §4.2, revision
323
+ * 2026-11-15): exactly the ones its `openingSeqs` names, in seq order, decided when the summary was
324
+ * written. A summary without the field (every older log) re-renders nothing. `events` sorted by seq.
325
+ */
326
+ export function summaryOpeners(events, summary) {
327
+ const seqs = new Set(summary?.payload.openingSeqs ?? []);
328
+ if (seqs.size === 0)
329
+ return [];
330
+ return events.filter((e) => e.type === "user_message" && seqs.has(e.seq));
331
+ }
316
332
  /** 最近一条 `compaction_summary` 事件(按 seq);没有则 null。 */
317
333
  export function latestSummary(events) {
318
334
  let found = null;
@@ -334,7 +350,8 @@ export function summaryText(summary) {
334
350
  * 第二个块是工具目录(见 {@link BuildModelRequestInput.toolSearch});
335
351
  * - 之后的 `skills_catalog` 在所在位置渲染为 system 变更提醒;被压缩摘要覆盖的,若摘要时生效的目录与 system 里的
336
352
  * 不同,紧随摘要补一条完整的当前目录;
337
- * - messages:最近一条摘要(若有)作为首条 user 消息,其后按 seq 回放 `coversUpToSeq` 之后的
353
+ * - messages:最近一条摘要(若有)作为首条 user 消息(摘要切在用户轮次内部时,该轮的开头消息按普通
354
+ * user_message 的渲染接在摘要文本之后、同一条消息里:摘要的 `openingSeqs`,{@link summaryOpeners}),其后按 seq 回放 `coversUpToSeq` 之后的
338
355
  * `user_message` / `assistant_message`(content 原样,含 opaque;aborted 的也回放;媒体引用按
339
356
  * {@link resolveMedia} 换成 base64 或文字占位)/ `reminder`
340
357
  * (`role: "system"`,放在它所在的位置)/ `tools_changed` (`role: "system"`, the text of {@link toolsChangedText}, at its position) /
@@ -473,15 +490,29 @@ export function buildModelRequest(input) {
473
490
  }
474
491
  racedPending = racedPending.filter((x) => x.seq > toSeq);
475
492
  };
476
- /** Run context spec §4: the sender lines, by the messages after the summary boundary. */
477
- const senders = senderLines(events, after);
493
+ /**
494
+ * Context compaction spec §4.2 (revision 2026-11-15): the user messages that started the run the
495
+ * summary cuts into, covered by it, are sent again right after the summary text (exactly the
496
+ * summary's `openingSeqs`).
497
+ */
498
+ const openers = summaryOpeners(events, summary);
499
+ const openerSet = new Set(openers);
500
+ /**
501
+ * Run context spec §4: the sender lines, by the messages after the summary boundary (and the
502
+ * re-sent opening messages first, which then count as the messages before them).
503
+ */
504
+ const firstOpener = openers[0];
505
+ const senders = firstOpener !== undefined
506
+ ? senderLines(events.filter((e) => e.seq > after || openerSet.has(e)), firstOpener.seq - 1)
507
+ : senderLines(events, after);
478
508
  /**
479
509
  * A user message's blocks: its sender line first when the sender changed (a separate block, so
480
510
  * `content[0]` stays the typed text), then a scheduled task's header (scheduled tasks spec §12,
481
- * from the marker in the log), then its own blocks, then its fork report when it has one.
511
+ * from the marker in the log), then its own blocks, then its fork report when it has one (never
512
+ * for the re-sent opening message: its report follows the rules of a covered invocation).
482
513
  */
483
- const userBlocks = (u) => {
484
- const report = forkReports.get(u.seq);
514
+ const userBlocks = (u, withReport = true) => {
515
+ const report = withReport ? forkReports.get(u.seq) : undefined;
485
516
  const line = senders.get(u.seq);
486
517
  const schedule = u.payload.schedule;
487
518
  const blocks = blocksOf(u.payload.content);
@@ -549,7 +580,10 @@ export function buildModelRequest(input) {
549
580
  if (summary) {
550
581
  messages.push({
551
582
  role: "user",
552
- content: [{ type: "text", text: summaryText(summary.payload.text) }],
583
+ content: [
584
+ { type: "text", text: summaryText(summary.payload.text) },
585
+ ...openers.flatMap((o) => userBlocks(o, false)),
586
+ ],
553
587
  });
554
588
  // run context spec §5: snapshots covered by the summary are not rendered; the context in
555
589
  // effect at the summary's boundary follows it whole
@@ -10,8 +10,9 @@ export declare const COMPACTION_MARKER = "CAPYBARA_COMPACTION";
10
10
  */
11
11
  export declare const COMPACTION_MAX_OUTPUT_TOKENS = 20000;
12
12
  /**
13
- * The input room a request leaves below the window: the output cap and the safety reserve are never
14
- * spent on input (context compaction spec §4.1).
13
+ * The input room one summary call leaves below the compaction model's window (context compaction
14
+ * spec §4.5, `B = Wc - Cmax - R`): the summary call's own output cap and the safety reserve are never
15
+ * spent on its input. A step's request plans with {@link planningBounds} instead.
15
16
  */
16
17
  export declare function compactionInputBudget(window: number, maxOutput: number, reserve: number): number;
17
18
  /**
@@ -36,9 +37,10 @@ export declare function compactionChunkSize(budget: number, maxOutputTokens: num
36
37
  export declare const MIN_COMPACTION_CHUNK_TOKENS = 256;
37
38
  /**
38
39
  * Compaction trigger (context compaction spec §4.1): the calibrated estimate reaches the lower of
39
- * `threshold × window` and the input budget, or it reaches the hard line `estimate + output >
40
- * window`, which fires even when proactive early compaction is turned off (`enabled: false`).
41
- * `settings.maxOutputTokens` here carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
40
+ * `threshold × window` and the input target `W - O_p - R_p` (the planning bounds,
41
+ * {@link planningBounds}), or it reaches the hard line `estimate + O_p > window`, which fires even
42
+ * when proactive early compaction is turned off (`enabled: false`). `settings.maxOutputTokens` here
43
+ * carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
42
44
  */
43
45
  export declare function shouldCompact(estimate: number, window: number, settings: CompactionSettings): boolean;
44
46
  /**
@@ -48,14 +50,31 @@ export declare function shouldCompact(estimate: number, window: number, settings
48
50
  *
49
51
  * The kept tail shrinks turn by turn, down to the latest user turn, until its estimated tokens fit
50
52
  * `budget` — the input room left after the output cap, the reserve, the system prompt and the tool
51
- * definitions. A single turn over the budget is still kept (the hard fit guard handles the rest).
52
- * `coversUpToSeq` is the largest seq before the first kept user_message. Returns null when there is
53
- * nothing to summarize.
53
+ * definitions. When the latest user turn alone does not fit (context compaction spec §4.2, revision
54
+ * 2026-11-15), the boundary moves inside it, to tool-pair boundaries oldest first, until the tail
55
+ * fits or only the latest tool pair (the latest assistant message with tool calls, and what follows
56
+ * it) is left; the summary then covers the turn's user message, which request building shows again
57
+ * right after the summary (build.ts). A latest turn without a tool pair is kept whole (the hard fit
58
+ * guard handles the rest). `coversUpToSeq` is the largest seq before the first kept event. Returns
59
+ * null when there is nothing to summarize.
54
60
  */
55
61
  export declare function compactionPlan(events: ConversationEvent[], settings: CompactionSettings, budget: number): {
56
62
  coversUpToSeq: number;
57
63
  transcript: string;
58
64
  } | null;
65
+ /**
66
+ * The user messages that started run `runId`, among those a summary covering up to
67
+ * `coversUpToSeq` covers (context compaction spec §4.2, revision 2026-11-15): recorded in the
68
+ * summary as `openingSeqs` when it is written, so request building re-renders exactly these after
69
+ * the summary text and a request never depends on later events. The opening messages are the user
70
+ * messages the run's first model call absorbed (`absorbedUpToSeq` of that call, or of the request
71
+ * about to be built when the run has made none yet) that no earlier turn answered or absorbed:
72
+ * after the latest assistant message and model call before the run's `run_started`.
73
+ * Several when the person sent several before the first call. None for a run that no message
74
+ * started (a finished background task or a sub-agent's delivery woke it, a manual compact run),
75
+ * and a covered interjection (after the first call) is never one. Sorted by seq.
76
+ */
77
+ export declare function openingSeqs(events: readonly ConversationEvent[], runId: string, coversUpToSeq: number, absorbedUpToSeq?: number): number[];
59
78
  /**
60
79
  * The text to store as the compaction summary (context compaction spec §4.2.1): the `<summary>`
61
80
  * block when the model returned one, since the `<analysis>` scratchpad must never be sent in a
@@ -1,6 +1,7 @@
1
1
  import { renderBackgroundFinished } from "../../background/render.js";
2
2
  import { renderSubagentDelivery } from "../subagents/render.js";
3
3
  import { latestSummary } from "./build.js";
4
+ import { planningBounds } from "./fit.js";
4
5
  import { scheduleHeader, senderTranscriptLabel } from "./run-context.js";
5
6
  import { estimateTokens } from "./tokens.js";
6
7
  import { toolsChangedText } from "./tool-changes.js";
@@ -45,8 +46,9 @@ const COMPACTION_INSTRUCTION = [
45
46
  "Output the <analysis> block followed by the <summary> block and nothing else.",
46
47
  ].join("\n");
47
48
  /**
48
- * The input room a request leaves below the window: the output cap and the safety reserve are never
49
- * spent on input (context compaction spec §4.1).
49
+ * The input room one summary call leaves below the compaction model's window (context compaction
50
+ * spec §4.5, `B = Wc - Cmax - R`): the summary call's own output cap and the safety reserve are never
51
+ * spent on its input. A step's request plans with {@link planningBounds} instead.
50
52
  */
51
53
  export function compactionInputBudget(window, maxOutput, reserve) {
52
54
  return window - maxOutput - reserve;
@@ -83,18 +85,18 @@ export function compactionChunkSize(budget, maxOutputTokens) {
83
85
  export const MIN_COMPACTION_CHUNK_TOKENS = 256;
84
86
  /**
85
87
  * Compaction trigger (context compaction spec §4.1): the calibrated estimate reaches the lower of
86
- * `threshold × window` and the input budget, or it reaches the hard line `estimate + output >
87
- * window`, which fires even when proactive early compaction is turned off (`enabled: false`).
88
- * `settings.maxOutputTokens` here carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
88
+ * `threshold × window` and the input target `W - O_p - R_p` (the planning bounds,
89
+ * {@link planningBounds}), or it reaches the hard line `estimate + O_p > window`, which fires even
90
+ * when proactive early compaction is turned off (`enabled: false`). `settings.maxOutputTokens` here
91
+ * carries `O`, the request's output cap (§4.1), not the summary cap (§4.8).
89
92
  */
90
93
  export function shouldCompact(estimate, window, settings) {
91
- const output = settings.maxOutputTokens;
94
+ const { output, target } = planningBounds(window, settings.maxOutputTokens, settings.reserveTokens);
92
95
  if (estimate + output > window)
93
96
  return true;
94
97
  if (!settings.enabled)
95
98
  return false;
96
- return (estimate >=
97
- Math.min(settings.threshold * window, compactionInputBudget(window, output, settings.reserveTokens)));
99
+ return estimate >= Math.min(settings.threshold * window, target);
98
100
  }
99
101
  /**
100
102
  * The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
@@ -103,9 +105,13 @@ export function shouldCompact(estimate, window, settings) {
103
105
  *
104
106
  * The kept tail shrinks turn by turn, down to the latest user turn, until its estimated tokens fit
105
107
  * `budget` — the input room left after the output cap, the reserve, the system prompt and the tool
106
- * definitions. A single turn over the budget is still kept (the hard fit guard handles the rest).
107
- * `coversUpToSeq` is the largest seq before the first kept user_message. Returns null when there is
108
- * nothing to summarize.
108
+ * definitions. When the latest user turn alone does not fit (context compaction spec §4.2, revision
109
+ * 2026-11-15), the boundary moves inside it, to tool-pair boundaries oldest first, until the tail
110
+ * fits or only the latest tool pair (the latest assistant message with tool calls, and what follows
111
+ * it) is left; the summary then covers the turn's user message, which request building shows again
112
+ * right after the summary (build.ts). A latest turn without a tool pair is kept whole (the hard fit
113
+ * guard handles the rest). `coversUpToSeq` is the largest seq before the first kept event. Returns
114
+ * null when there is nothing to summarize.
109
115
  */
110
116
  export function compactionPlan(events, settings, budget) {
111
117
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
@@ -117,6 +123,8 @@ export function compactionPlan(events, settings, budget) {
117
123
  if (e.type === "user_message")
118
124
  userIdx.push(i);
119
125
  });
126
+ const atPair = pairBoundaries(candidate);
127
+ const tail = tailTokens(candidate);
120
128
  const keep = settings.keepRecentTurns;
121
129
  let boundary;
122
130
  if (keep <= 0)
@@ -125,21 +133,35 @@ export function compactionPlan(events, settings, budget) {
125
133
  boundary = 0;
126
134
  else
127
135
  boundary = userIdx[userIdx.length - keep];
128
- boundary = keepToolPairs(candidate, userIdx, boundary);
129
- // size-aware tail: drop earlier kept turns until the rest fits the budget, but never drop the
130
- // latest user turn (a turn over the budget is trimmed by the hard fit guard, spec §4.3)
131
- if (userIdx.length > 0 &&
132
- boundary < candidate.length &&
133
- tailTokens(candidate, boundary) > budget) {
134
- let chosen = boundary;
136
+ boundary = keepToolPairs(atPair, userIdx, boundary);
137
+ if (boundary < candidate.length && tail[boundary] > budget) {
138
+ // size-aware tail: drop earlier kept turns until the rest fits the budget
135
139
  for (const start of userIdx) {
136
140
  if (start <= boundary)
137
141
  continue;
138
- chosen = keepToolPairs(candidate, userIdx, start);
139
- if (tailTokens(candidate, chosen) <= budget)
142
+ boundary = keepToolPairs(atPair, userIdx, start);
143
+ if (tail[boundary] <= budget)
140
144
  break;
141
145
  }
142
- boundary = chosen;
146
+ // the latest user turn alone is over the budget: cut inside it at a tool-pair boundary,
147
+ // oldest first, never past the latest tool pair (spec §4.2, revision 2026-11-15)
148
+ if (tail[boundary] > budget) {
149
+ let limit = -1;
150
+ for (let i = candidate.length - 1; i > boundary && limit < 0; i--) {
151
+ const e = candidate[i];
152
+ if (e.type === "assistant_message" && e.payload.content.some((b) => b.type === "tool_call"))
153
+ limit = i;
154
+ }
155
+ let chosen = boundary;
156
+ for (let j = boundary + 1; j <= limit; j++) {
157
+ if (!atPair[j])
158
+ continue;
159
+ chosen = j;
160
+ if (tail[j] <= budget)
161
+ break;
162
+ }
163
+ boundary = chosen;
164
+ }
143
165
  }
144
166
  const lines = [];
145
167
  for (const e of candidate.slice(0, boundary)) {
@@ -158,27 +180,67 @@ export function compactionPlan(events, settings, budget) {
158
180
  return { coversUpToSeq, transcript: parts.join("\n\n") };
159
181
  }
160
182
  /**
161
- * Estimated input tokens of the kept tail (the events rendered as the transcript renders them, then
162
- * estimated with the request estimator).
183
+ * The user messages that started run `runId`, among those a summary covering up to
184
+ * `coversUpToSeq` covers (context compaction spec §4.2, revision 2026-11-15): recorded in the
185
+ * summary as `openingSeqs` when it is written, so request building re-renders exactly these after
186
+ * the summary text and a request never depends on later events. The opening messages are the user
187
+ * messages the run's first model call absorbed (`absorbedUpToSeq` of that call, or of the request
188
+ * about to be built when the run has made none yet) that no earlier turn answered or absorbed:
189
+ * after the latest assistant message and model call before the run's `run_started`.
190
+ * Several when the person sent several before the first call. None for a run that no message
191
+ * started (a finished background task or a sub-agent's delivery woke it, a manual compact run),
192
+ * and a covered interjection (after the first call) is never one. Sorted by seq.
163
193
  */
164
- function tailTokens(candidate, from) {
165
- let tokens = 0;
166
- for (const e of candidate.slice(from)) {
167
- const line = transcriptLine(e);
168
- if (!line)
169
- continue;
170
- tokens += estimateTokens([{ role: "user", content: [{ type: "text", text: line }] }], []);
194
+ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Number.POSITIVE_INFINITY) {
195
+ const sorted = [...events].sort((a, b) => a.seq - b.seq);
196
+ const start = sorted.findLast((e) => e.type === "run_started" && e.runId === runId);
197
+ if (start?.type !== "run_started")
198
+ return [];
199
+ const trigger = start.payload.trigger;
200
+ if (trigger !== undefined && trigger !== "message" && trigger !== "schedule")
201
+ return [];
202
+ const first = sorted.find((e) => e.type === "model_call" && e.runId === runId && e.seq > start.seq);
203
+ const upTo = first?.type === "model_call"
204
+ ? Math.min(first.payload.request.absorbedUpToSeq ?? first.seq, first.seq)
205
+ : absorbedUpToSeq;
206
+ let floor = Number.NEGATIVE_INFINITY;
207
+ for (const e of sorted) {
208
+ if (e.seq >= start.seq)
209
+ break;
210
+ if (e.type === "assistant_message")
211
+ floor = Math.max(floor, e.seq);
212
+ else if (e.type === "model_call") {
213
+ floor = Math.max(floor, e.payload.request.absorbedUpToSeq ?? e.seq);
214
+ }
171
215
  }
172
- return tokens;
216
+ return sorted
217
+ .filter((e) => e.type === "user_message" && e.seq > floor && e.seq <= upTo && e.seq <= coversUpToSeq)
218
+ .map((e) => e.seq);
173
219
  }
174
220
  /**
175
- * 边界不得切开工具调用与其结果:工具运行期间到达的插话(user_message)记在 assistant 的 tool_call 与
176
- * tool_result 之间,若它成了边界,assistant 进摘要而结果留在原文,构建请求时结果因找不到调用被丢弃。
177
- * 做法:边界之前仍「未结束」(结果在边界之后)的调用存在时,把边界退到最早那条未结束 assistant 之前的
178
- * 最近一个 user_message(没有则 0,即不压缩这段),重复直到没有被切开的调用。结果从未写入的调用不算
179
- * (它们由配对守卫补 unknown,与边界无关)。
221
+ * Estimated input tokens of the kept tail from each index (`out[i]` for the events from `i` on,
222
+ * `out[length]` = 0): the events rendered as the transcript renders them, then estimated with the
223
+ * request estimator.
180
224
  */
181
- function keepToolPairs(candidate, userIdx, boundary) {
225
+ function tailTokens(candidate) {
226
+ const out = new Array(candidate.length + 1).fill(0);
227
+ for (let i = candidate.length - 1; i >= 0; i--) {
228
+ const line = transcriptLine(candidate[i]);
229
+ const own = line
230
+ ? estimateTokens([{ role: "user", content: [{ type: "text", text: line }] }], [])
231
+ : 0;
232
+ out[i] = out[i + 1] + own;
233
+ }
234
+ return out;
235
+ }
236
+ /**
237
+ * The tool-pair boundaries (`out[j]` for a cut before index `j`, `out[length]` = true): no tool
238
+ * call before `j` has its result at or after `j`. A tool that ran during an interjection
239
+ * (user_message) has the message between its call and its result, so that message is no
240
+ * boundary: cutting there would leave the result without its call, and request building drops such
241
+ * a result. Calls whose result was never written do not count (the pairing guard pads them).
242
+ */
243
+ function pairBoundaries(candidate) {
182
244
  const key = (runId, callId) => `${runId ?? ""}\u0000${callId}`;
183
245
  const resultAt = new Map();
184
246
  candidate.forEach((e, i) => {
@@ -188,30 +250,43 @@ function keepToolPairs(candidate, userIdx, boundary) {
188
250
  if (!resultAt.has(k))
189
251
  resultAt.set(k, i);
190
252
  });
191
- for (;;) {
192
- let earliestOpen = -1;
193
- for (let i = 0; i < boundary && earliestOpen < 0; i++) {
194
- const e = candidate[i];
195
- if (e.type !== "assistant_message")
253
+ // open[j] > 0: some call before j has its result at or after j (a difference array)
254
+ const open = new Array(candidate.length + 2).fill(0);
255
+ candidate.forEach((e, i) => {
256
+ if (e.type !== "assistant_message")
257
+ return;
258
+ for (const b of e.payload.content) {
259
+ if (b.type !== "tool_call")
196
260
  continue;
197
- for (const b of e.payload.content) {
198
- if (b.type !== "tool_call")
199
- continue;
200
- const at = resultAt.get(key(e.runId, b.id));
201
- if (at !== undefined && at >= boundary) {
202
- earliestOpen = i;
203
- break;
204
- }
205
- }
261
+ const at = resultAt.get(key(e.runId, b.id));
262
+ if (at === undefined || at <= i)
263
+ continue;
264
+ open[i + 1] = open[i + 1] + 1;
265
+ open[at + 1] = open[at + 1] - 1;
206
266
  }
207
- if (earliestOpen < 0)
208
- return boundary;
209
- let next = 0;
210
- for (const u of userIdx)
211
- if (u < earliestOpen)
212
- next = u;
213
- boundary = next;
267
+ });
268
+ const out = [];
269
+ let depth = 0;
270
+ for (let j = 0; j <= candidate.length; j++) {
271
+ depth += open[j];
272
+ out.push(depth === 0);
273
+ }
274
+ return out;
275
+ }
276
+ /**
277
+ * A turn boundary that would split a tool call from its result moves back to the latest
278
+ * user_message before it that is a tool-pair boundary (none: 0, nothing of this part is
279
+ * summarised).
280
+ */
281
+ function keepToolPairs(atPair, userIdx, boundary) {
282
+ if (atPair[boundary])
283
+ return boundary;
284
+ for (let k = userIdx.length - 1; k >= 0; k--) {
285
+ const u = userIdx[k];
286
+ if (u < boundary && atPair[u])
287
+ return u;
214
288
  }
289
+ return 0;
215
290
  }
216
291
  function transcriptLine(e) {
217
292
  switch (e.type) {
@@ -24,19 +24,25 @@ export interface FitPlan {
24
24
  /** The note an oversized block carries once truncated (model-visible, English; spec §4.3). */
25
25
  export declare const FIT_TRUNCATION_NOTE = "[content truncated to fit the model's context window]";
26
26
  /**
27
- * The output cap actually sent (`O'`, spec §4.3 point 2): the configured cap, lowered so the
28
- * provider-visible total (`input + O'`) fits the window. At least one output token is always left.
29
- * When the window is smaller than the requested cap this is what keeps the plan's target reachable.
27
+ * The planning bounds of a window (context compaction spec §4.1, revision 2026-11-15): every plan
28
+ * (the trigger, the compaction tail, the fit guard, the reactive trim) uses `O_p = min(O, ⌊W/2⌋)`
29
+ * (at least 1) and `R_p = min(R, ⌊W/8⌋)` in place of the output cap and the reserve, so the input
30
+ * target `W - O_p - R_p` is at least `3W/8` on any model. Without them a model whose output cap is
31
+ * about its window, or whose window is smaller than the reserve, had a target of about one token.
32
+ * Common models are unchanged (W 200k, O 32k, R 8k: `O_p = O`, `R_p = R`).
30
33
  */
31
- export declare function clampOutput(contextWindow: number, maxOutputTokens: number, estimate: number): number;
34
+ export declare function planningBounds(contextWindow: number, maxOutputTokens: number, reserveTokens: number): {
35
+ output: number;
36
+ reserve: number;
37
+ target: number;
38
+ };
32
39
  /**
33
- * The reserve actually kept (`R_eff`, spec §4.3 point 2): the configured reserve, reduced to what
34
- * the clamped output leaves below the window. A reserve larger than the window is sacrificed
35
- * (the hard bound is what must hold), so the target keeps at least one token of room.
40
+ * The output cap actually sent (`O'`, spec §4.1 / §4.3 point 4): `clamp(O, 1, W - input - R_p)`,
41
+ * from the input actually sent (after the fit plan). The configured cap whenever it fits beside the
42
+ * input and the reserve; otherwise what is left, the reserve kept. Every path (ordinary, squeezed,
43
+ * reactive) clamps with it.
36
44
  */
37
- export declare function effectiveReserve(contextWindow: number, clampedOutput: number, reserveTokens: number): number;
38
- /** The input room left below the window: `W - O' - R_eff` with the clamped output and reserve. */
39
- export declare function fitTarget(contextWindow: number, clampedOutput: number, reserveTokens: number): number;
45
+ export declare function sentOutputCap(contextWindow: number, maxOutputTokens: number, inputSent: number, reserveTokens: number): number;
40
46
  export interface PlanFitInput {
41
47
  /** The log the request was built from (documentation: the plan replays from it). */
42
48
  events: ConversationEvent[];
@@ -44,27 +50,53 @@ export interface PlanFitInput {
44
50
  request: ModelRequest;
45
51
  /** The model the request is for: its context window is the hard bound. */
46
52
  model: ModelInfo;
47
- /** `O`: the requested output cap (`ModelRequest.maxOutputTokens`, before the clamp). */
53
+ /** `O`: the requested output cap (`ModelRequest.maxOutputTokens`, unclamped; bounded here). */
48
54
  maxOutputTokens: number;
49
- /** `R`: the safety reserve in effect for the run's organization, before the clamp. */
55
+ /** `R`: the safety reserve in effect for the run's organization (unreduced; bounded here). */
50
56
  reserveTokens: number;
51
57
  /** The request's input-token estimate (uncalibrated, as recorded). */
52
58
  estimate: number;
53
59
  }
54
60
  /**
55
- * The deterministic fit plan for a request over `W - O' - R_eff` (the output cap and reserve first
56
- * clamped to the window, {@link clampOutput} / {@link effectiveReserve}), or null when it already
57
- * fits. A plan that cannot reach the target even after dropping every droppable message and
58
- * truncating every kept text / `tool_result` block is still returned: the caller raises
59
- * `run.context_too_large` before any provider call.
61
+ * The deterministic fit plan for a request over the planning target `W - O_p - R_p`
62
+ * ({@link planningBounds}), or null when it already fits. A plan that cannot reach the target even after dropping every droppable
63
+ * message and truncating every kept text / `tool_result` block is still returned: the caller decides
64
+ * (the ordinary guard fails before any provider call).
60
65
  *
61
- * Drops, in this order, every droppable message before the latest user turn until the estimate is
62
- * at or below the target: complete tool pairs first (a tool call with the results message that
63
- * follows it), then assistant text, then complete older user turns. Never a pair's half, never the
64
- * summary. If that is not enough, it truncates the kept tail's largest text / `tool_result` blocks
65
- * (replacing the content with {@link FIT_TRUNCATION_NOTE}).
66
+ * Drops, in this order, until the estimate is at or below the target: before the latest user turn,
67
+ * complete tool pairs first (a tool call with the results message that follows it), then assistant
68
+ * text, then complete older user turns; then the complete tool pairs inside the latest user turn,
69
+ * oldest first, stopping before the latest complete pair (spec §4.3, revision 2026-11-15). The
70
+ * latest typed message stays (when the summary covers it, the turn starts after the summary). Never
71
+ * a pair's half, never the summary or a system message. If that is not enough, it truncates the kept
72
+ * messages' largest text / `tool_result` blocks (replacing the content with
73
+ * {@link FIT_TRUNCATION_NOTE}); in the summary message only the blocks after the summary text (the
74
+ * re-rendered opening user message) are candidates.
66
75
  */
67
76
  export declare function planFit(input: PlanFitInput): FitPlan | null;
77
+ /**
78
+ * The fallback when {@link planFit} cannot reach its target, even after one forced compaction
79
+ * (spec §4.3 point 5): plan against `W - 1 - R_p`, giving the output whatever the input leaves
80
+ * while the reserve stays. The caller sends the cap {@link sentOutputCap} gives from the post-fit
81
+ * estimate. A plan that cannot reach this target either means the system prompt, tools, summary and
82
+ * latest pair are too large (`run.context_too_large`).
83
+ */
84
+ export declare function planSqueezedFit(input: PlanFitInput): {
85
+ plan: FitPlan | null;
86
+ target: number;
87
+ };
88
+ /** The reactive trim's fractions of the fit target, most aggressive first (spec §4.3 point 6). */
89
+ export declare const REACTIVE_TRIM_FACTORS: readonly [0.7, 0.8, 0.9];
90
+ /**
91
+ * The deterministic plan for a reactive trim (spec §4.3 point 6 / §4.4): the provider rejected a
92
+ * request the estimate thought fit, so the retry is trimmed against 70%, 80% or 90% of the fit
93
+ * target `W - O_p - R_p`, the most aggressive one the plan actually reaches (its estimate after the
94
+ * plan at or below it). Null when none is reached (a plan that cannot reach even 90% would replace
95
+ * every kept block with notes) or when the request already fits 70% (nothing to trim, the same
96
+ * request would be rejected again): no trim retry, the step surfaces `model.context_overflow`. The
97
+ * plan is ordinary and replays byte-for-byte like any other.
98
+ */
99
+ export declare function planReactiveTrim(input: PlanFitInput): FitPlan | null;
68
100
  /**
69
101
  * Applies a plan to an assembled request (pure): drops the named messages and replaces the named
70
102
  * blocks' content with their note. Message and block indexes refer to the request as given, so the