@capybara-hq/kernel 0.1.0-rc.30 → 0.1.0-rc.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.json +3 -3
- package/dist/catalog/marketplace-fetch.d.ts +5 -2
- package/dist/catalog/marketplace-fetch.js +4 -1
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/catalog/requests.service.d.ts +6 -5
- package/dist/catalog/requests.service.js +7 -6
- package/dist/config/load.d.ts +6 -0
- package/dist/config/load.js +26 -0
- package/dist/config/schema.js +5 -5
- package/dist/conversations/events.d.ts +10 -0
- package/dist/conversations/events.js +23 -1
- package/dist/ctx/create-ctx.d.ts +26 -4
- package/dist/ctx/create-ctx.js +54 -34
- package/dist/devices/devices.controller.js +3 -2
- package/dist/devices/devices.service.d.ts +17 -5
- package/dist/devices/devices.service.js +24 -13
- package/dist/devices/dto.d.ts +7 -6
- package/dist/devices/dto.js +6 -5
- package/dist/errors.d.ts +6 -1
- package/dist/errors.js +6 -1
- package/dist/evals/reconstruct.js +18 -8
- package/dist/extensions/bootstrap.d.ts +1 -1
- package/dist/extensions/bootstrap.js +7 -1
- package/dist/extensions/installs.js +4 -1
- package/dist/extensions/permission-set.d.ts +7 -6
- package/dist/extensions/permission-set.js +9 -6
- package/dist/extensions/permission-view.d.ts +4 -4
- package/dist/extensions/permission-view.js +10 -5
- package/dist/http/app.d.ts +8 -2
- package/dist/http/app.js +12 -2
- package/dist/http/plugin-dispatch.d.ts +55 -18
- package/dist/http/plugin-dispatch.js +124 -29
- package/dist/http/plugin-route-access.d.ts +56 -0
- package/dist/http/plugin-route-access.js +192 -0
- package/dist/identity/auth.guard.d.ts +26 -12
- package/dist/identity/auth.guard.js +62 -33
- package/dist/infra/throttler/named-throttlers.d.ts +3 -0
- package/dist/infra/throttler/named-throttlers.js +16 -0
- package/dist/infra/throttler/throttler.guard.d.ts +2 -1
- package/dist/infra/throttler/throttler.guard.js +2 -1
- package/dist/kernel.module.js +3 -0
- package/dist/lifecycle/kernel-lifecycle.js +1 -3
- package/dist/net/public-address.d.ts +14 -4
- package/dist/net/public-address.js +22 -12
- package/dist/net/safe-fetch.d.ts +2 -1
- package/dist/net/safe-fetch.js +16 -4
- package/dist/overrides.d.ts +3 -0
- package/dist/overrides.js +2 -0
- package/dist/packages/npm.d.ts +28 -9
- package/dist/packages/npm.js +30 -19
- package/dist/packages/provenance.d.ts +3 -1
- package/dist/packages/provenance.js +7 -3
- package/dist/platform/ops/devices.ops.js +1 -1
- package/dist/platform/ops/platform.ops.d.ts +3 -1
- package/dist/platform/ops/platform.ops.js +11 -13
- package/dist/runtime/context/build.d.ts +10 -1
- package/dist/runtime/context/build.js +44 -10
- package/dist/runtime/context/compaction.d.ts +27 -8
- package/dist/runtime/context/compaction.js +133 -58
- package/dist/runtime/context/fit.d.ts +54 -22
- package/dist/runtime/context/fit.js +116 -40
- package/dist/runtime/model-call.d.ts +0 -8
- package/dist/runtime/model-call.js +185 -83
- package/dist/sandbox/review/classifier.d.ts +2 -0
- package/dist/sandbox/review/classifier.js +12 -1
- package/dist/sandbox/review/index.d.ts +3 -3
- package/dist/sandbox/review/index.js +3 -3
- package/dist/sandbox/review/review.service.d.ts +12 -4
- package/dist/sandbox/review/review.service.js +88 -19
- package/dist/sandbox/review/rules.d.ts +6 -0
- package/dist/sandbox/review/rules.js +1013 -95
- package/dist/sandbox/review/types.d.ts +21 -4
- package/dist/sandbox/review/types.js +41 -5
- package/dist/sandbox/sandbox.service.d.ts +8 -7
- package/dist/sandbox/sandbox.service.js +16 -16
- package/dist/setup/kernel-checks.js +3 -2
- package/dist/setup/oauth-token-probe.d.ts +1 -8
- package/dist/setup/oauth-token-probe.js +0 -16
- package/dist/tools/builtins/sandbox/common.d.ts +1 -1
- package/dist/tools/builtins/sandbox/common.js +1 -1
- package/dist/tools/builtins/tool-search.js +4 -3
- package/dist/tools/oauth/discovery.d.ts +38 -16
- package/dist/tools/oauth/discovery.js +59 -33
- package/dist/tools/pipeline.js +17 -13
- package/package.json +3 -3
|
@@ -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
|
|
49
|
-
*
|
|
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
|
|
87
|
-
*
|
|
88
|
-
*
|
|
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
|
|
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.
|
|
107
|
-
*
|
|
108
|
-
*
|
|
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(
|
|
129
|
-
|
|
130
|
-
|
|
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
|
-
|
|
139
|
-
if (
|
|
142
|
+
boundary = keepToolPairs(atPair, userIdx, start);
|
|
143
|
+
if (tail[boundary] <= budget)
|
|
140
144
|
break;
|
|
141
145
|
}
|
|
142
|
-
|
|
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
|
-
*
|
|
162
|
-
*
|
|
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
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
|
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
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
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
|
|
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
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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
|
|
28
|
-
*
|
|
29
|
-
*
|
|
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
|
|
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
|
|
34
|
-
* the
|
|
35
|
-
*
|
|
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
|
|
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`,
|
|
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
|
|
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 -
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
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,
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* (
|
|
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
|
|
@@ -2,63 +2,79 @@ import { estimateTokens } from "./tokens.js";
|
|
|
2
2
|
/** The note an oversized block carries once truncated (model-visible, English; spec §4.3). */
|
|
3
3
|
export const FIT_TRUNCATION_NOTE = "[content truncated to fit the model's context window]";
|
|
4
4
|
/**
|
|
5
|
-
* The
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* The planning bounds of a window (context compaction spec §4.1, revision 2026-11-15): every plan
|
|
6
|
+
* (the trigger, the compaction tail, the fit guard, the reactive trim) uses `O_p = min(O, ⌊W/2⌋)`
|
|
7
|
+
* (at least 1) and `R_p = min(R, ⌊W/8⌋)` in place of the output cap and the reserve, so the input
|
|
8
|
+
* target `W - O_p - R_p` is at least `3W/8` on any model. Without them a model whose output cap is
|
|
9
|
+
* about its window, or whose window is smaller than the reserve, had a target of about one token.
|
|
10
|
+
* Common models are unchanged (W 200k, O 32k, R 8k: `O_p = O`, `R_p = R`).
|
|
8
11
|
*/
|
|
9
|
-
export function
|
|
10
|
-
|
|
12
|
+
export function planningBounds(contextWindow, maxOutputTokens, reserveTokens) {
|
|
13
|
+
const output = Math.max(1, Math.min(maxOutputTokens, Math.floor(contextWindow / 2)));
|
|
14
|
+
const reserve = Math.max(0, Math.min(reserveTokens, Math.floor(contextWindow / 8)));
|
|
15
|
+
return { output, reserve, target: contextWindow - output - reserve };
|
|
11
16
|
}
|
|
12
17
|
/**
|
|
13
|
-
* The
|
|
14
|
-
* the
|
|
15
|
-
*
|
|
18
|
+
* The output cap actually sent (`O'`, spec §4.1 / §4.3 point 4): `clamp(O, 1, W - input - R_p)`,
|
|
19
|
+
* from the input actually sent (after the fit plan). The configured cap whenever it fits beside the
|
|
20
|
+
* input and the reserve; otherwise what is left, the reserve kept. Every path (ordinary, squeezed,
|
|
21
|
+
* reactive) clamps with it.
|
|
16
22
|
*/
|
|
17
|
-
export function
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
/** The input room left below the window: `W - O' - R_eff` with the clamped output and reserve. */
|
|
21
|
-
export function fitTarget(contextWindow, clampedOutput, reserveTokens) {
|
|
22
|
-
return contextWindow - clampedOutput - reserveTokens;
|
|
23
|
+
export function sentOutputCap(contextWindow, maxOutputTokens, inputSent, reserveTokens) {
|
|
24
|
+
const { reserve } = planningBounds(contextWindow, maxOutputTokens, reserveTokens);
|
|
25
|
+
return Math.max(1, Math.min(maxOutputTokens, contextWindow - inputSent - reserve));
|
|
23
26
|
}
|
|
24
27
|
const SUMMARY_OPEN = "<conversation_summary>";
|
|
25
28
|
const NOTE_TOKENS = estimateTokens([{ role: "user", content: [{ type: "text", text: FIT_TRUNCATION_NOTE }] }], []);
|
|
26
|
-
/**
|
|
27
|
-
const
|
|
29
|
+
/** The summary text block (never truncated: it is the retained history). */
|
|
30
|
+
const isSummaryText = (b) => b.type === "text" && b.text.startsWith(SUMMARY_OPEN);
|
|
31
|
+
/**
|
|
32
|
+
* The conversation summary message (never dropped; its summary text is never truncated, the
|
|
33
|
+
* re-rendered opening user message after it may be: spec §4.3 point 5).
|
|
34
|
+
*/
|
|
35
|
+
const isSummary = (m) => m.role === "user" && m.content.some(isSummaryText);
|
|
36
|
+
/**
|
|
37
|
+
* A typed user turn (a person's message): not a tool-result carrier and not the summary, which may
|
|
38
|
+
* cover the latest typed message (spec §4.2, revision 2026-11-15).
|
|
39
|
+
*/
|
|
40
|
+
const isTypedUser = (m) => m.role === "user" && m.content.some((b) => b.type !== "tool_result") && !isSummary(m);
|
|
28
41
|
/** A message that carries only tool results (the answer to a tool call). */
|
|
29
42
|
const isResults = (m) => m.role === "user" && m.content.length > 0 && m.content.every((b) => b.type === "tool_result");
|
|
30
43
|
const hasToolCall = (m) => m.role === "assistant" && m.content.some((b) => b.type === "tool_call");
|
|
31
|
-
/** The conversation summary message (never dropped or truncated: it is the retained history). */
|
|
32
|
-
const isSummary = (m) => m.role === "user" && m.content.some((b) => b.type === "text" && b.text.startsWith(SUMMARY_OPEN));
|
|
33
44
|
const messageTokens = (m) => estimateTokens([m], [], []);
|
|
34
45
|
const blockTokens = (b) => estimateTokens([{ role: "user", content: [b] }], [], []);
|
|
35
46
|
const truncatable = (b) => (b.type === "text" && b.text !== FIT_TRUNCATION_NOTE) ||
|
|
36
47
|
(b.type === "tool_result" && b.content !== FIT_TRUNCATION_NOTE);
|
|
37
48
|
/**
|
|
38
|
-
* The deterministic fit plan for a request over `W -
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* `run.context_too_large` before any provider call.
|
|
49
|
+
* The deterministic fit plan for a request over the planning target `W - O_p - R_p`
|
|
50
|
+
* ({@link planningBounds}), or null when it already fits. A plan that cannot reach the target even after dropping every droppable
|
|
51
|
+
* message and truncating every kept text / `tool_result` block is still returned: the caller decides
|
|
52
|
+
* (the ordinary guard fails before any provider call).
|
|
43
53
|
*
|
|
44
|
-
* Drops, in this order,
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* (
|
|
54
|
+
* Drops, in this order, until the estimate is at or below the target: before the latest user turn,
|
|
55
|
+
* complete tool pairs first (a tool call with the results message that follows it), then assistant
|
|
56
|
+
* text, then complete older user turns; then the complete tool pairs inside the latest user turn,
|
|
57
|
+
* oldest first, stopping before the latest complete pair (spec §4.3, revision 2026-11-15). The
|
|
58
|
+
* latest typed message stays (when the summary covers it, the turn starts after the summary). Never
|
|
59
|
+
* a pair's half, never the summary or a system message. If that is not enough, it truncates the kept
|
|
60
|
+
* messages' largest text / `tool_result` blocks (replacing the content with
|
|
61
|
+
* {@link FIT_TRUNCATION_NOTE}); in the summary message only the blocks after the summary text (the
|
|
62
|
+
* re-rendered opening user message) are candidates.
|
|
49
63
|
*/
|
|
50
64
|
export function planFit(input) {
|
|
51
|
-
const {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
65
|
+
const { model, maxOutputTokens, reserveTokens } = input;
|
|
66
|
+
return planFitTo(input, planningBounds(model.contextWindow, maxOutputTokens, reserveTokens).target);
|
|
67
|
+
}
|
|
68
|
+
/** {@link planFit} against an explicit input target (the squeezed fit, the reactive trim). */
|
|
69
|
+
function planFitTo(input, target) {
|
|
70
|
+
const { request, estimate } = input;
|
|
55
71
|
if (target <= 0 || estimate <= target)
|
|
56
72
|
return null;
|
|
57
73
|
const messages = request.messages;
|
|
58
|
-
// the latest user turn
|
|
59
|
-
// messages may go
|
|
74
|
+
// the latest user turn starts at the latest typed message, or (when the summary covers it) at the
|
|
75
|
+
// start: older messages may go whole, the turn itself only as complete tool pairs
|
|
60
76
|
const lastTyped = messages.findLastIndex(isTypedUser);
|
|
61
|
-
const keepFrom = lastTyped < 0 ?
|
|
77
|
+
const keepFrom = lastTyped < 0 ? 0 : lastTyped;
|
|
62
78
|
const droppable = (i) => {
|
|
63
79
|
const m = messages[i];
|
|
64
80
|
return i < keepFrom && m !== undefined && m.role !== "system" && !isSummary(m);
|
|
@@ -109,17 +125,40 @@ export function planFit(input) {
|
|
|
109
125
|
continue;
|
|
110
126
|
drop([i]);
|
|
111
127
|
}
|
|
128
|
+
// complete tool pairs inside the latest user turn, oldest first, keeping the latest complete pair
|
|
129
|
+
// (the one the next step answers)
|
|
130
|
+
const isPairAt = (i) => {
|
|
131
|
+
const m = messages[i];
|
|
132
|
+
const next = messages[i + 1];
|
|
133
|
+
return m !== undefined && hasToolCall(m) && next !== undefined && isResults(next);
|
|
134
|
+
};
|
|
135
|
+
let latestPair = -1;
|
|
136
|
+
for (let i = messages.length - 2; i >= keepFrom; i--) {
|
|
137
|
+
if (isPairAt(i)) {
|
|
138
|
+
latestPair = i;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (let i = keepFrom; i < latestPair && current > target; i++) {
|
|
143
|
+
if (!isPairAt(i))
|
|
144
|
+
continue;
|
|
145
|
+
drop([i, i + 1]);
|
|
146
|
+
i++;
|
|
147
|
+
}
|
|
112
148
|
if (current <= target)
|
|
113
149
|
return plan;
|
|
114
|
-
//
|
|
115
|
-
//
|
|
150
|
+
// still too large: replace the kept messages' largest text / tool_result blocks with the note,
|
|
151
|
+
// largest first, ties by position. In the summary message only the summary text is protected:
|
|
152
|
+
// the turn's opening message re-rendered after it (spec §4.2) is a kept block like any other
|
|
116
153
|
const candidates = [];
|
|
117
|
-
for (let i =
|
|
154
|
+
for (let i = 0; i < messages.length; i++) {
|
|
118
155
|
const m = messages[i];
|
|
119
|
-
if (m === undefined || m.role === "system"
|
|
156
|
+
if (m === undefined || dropped.has(i) || m.role === "system")
|
|
157
|
+
continue;
|
|
158
|
+
if (i < keepFrom && !isSummary(m))
|
|
120
159
|
continue;
|
|
121
160
|
m.content.forEach((b, block) => {
|
|
122
|
-
if (!truncatable(b))
|
|
161
|
+
if (!truncatable(b) || isSummaryText(b))
|
|
123
162
|
return;
|
|
124
163
|
const tokens = blockTokens(b);
|
|
125
164
|
if (tokens > NOTE_TOKENS)
|
|
@@ -139,6 +178,43 @@ export function planFit(input) {
|
|
|
139
178
|
}
|
|
140
179
|
return plan;
|
|
141
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* The fallback when {@link planFit} cannot reach its target, even after one forced compaction
|
|
183
|
+
* (spec §4.3 point 5): plan against `W - 1 - R_p`, giving the output whatever the input leaves
|
|
184
|
+
* while the reserve stays. The caller sends the cap {@link sentOutputCap} gives from the post-fit
|
|
185
|
+
* estimate. A plan that cannot reach this target either means the system prompt, tools, summary and
|
|
186
|
+
* latest pair are too large (`run.context_too_large`).
|
|
187
|
+
*/
|
|
188
|
+
export function planSqueezedFit(input) {
|
|
189
|
+
const { model, maxOutputTokens, reserveTokens } = input;
|
|
190
|
+
const { reserve } = planningBounds(model.contextWindow, maxOutputTokens, reserveTokens);
|
|
191
|
+
const target = model.contextWindow - 1 - reserve;
|
|
192
|
+
return { plan: planFitTo(input, target), target };
|
|
193
|
+
}
|
|
194
|
+
/** The reactive trim's fractions of the fit target, most aggressive first (spec §4.3 point 6). */
|
|
195
|
+
export const REACTIVE_TRIM_FACTORS = [0.7, 0.8, 0.9];
|
|
196
|
+
/**
|
|
197
|
+
* The deterministic plan for a reactive trim (spec §4.3 point 6 / §4.4): the provider rejected a
|
|
198
|
+
* request the estimate thought fit, so the retry is trimmed against 70%, 80% or 90% of the fit
|
|
199
|
+
* target `W - O_p - R_p`, the most aggressive one the plan actually reaches (its estimate after the
|
|
200
|
+
* plan at or below it). Null when none is reached (a plan that cannot reach even 90% would replace
|
|
201
|
+
* every kept block with notes) or when the request already fits 70% (nothing to trim, the same
|
|
202
|
+
* request would be rejected again): no trim retry, the step surfaces `model.context_overflow`. The
|
|
203
|
+
* plan is ordinary and replays byte-for-byte like any other.
|
|
204
|
+
*/
|
|
205
|
+
export function planReactiveTrim(input) {
|
|
206
|
+
const { request, model, maxOutputTokens, reserveTokens, estimate } = input;
|
|
207
|
+
const { target } = planningBounds(model.contextWindow, maxOutputTokens, reserveTokens);
|
|
208
|
+
for (const factor of REACTIVE_TRIM_FACTORS) {
|
|
209
|
+
const t = Math.floor(factor * target);
|
|
210
|
+
const plan = planFitTo(input, t);
|
|
211
|
+
if (plan === null)
|
|
212
|
+
return null;
|
|
213
|
+
if (estimateAfterFit(request, estimate, plan) <= t)
|
|
214
|
+
return plan;
|
|
215
|
+
}
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
142
218
|
/**
|
|
143
219
|
* Applies a plan to an assembled request (pure): drops the named messages and replaces the named
|
|
144
220
|
* blocks' content with their note. Message and block indexes refer to the request as given, so the
|
|
@@ -188,14 +188,6 @@ export declare const MAX_MODEL_ATTEMPTS = 3;
|
|
|
188
188
|
* so a persistent `model.context_overflow` cannot loop.
|
|
189
189
|
*/
|
|
190
190
|
export declare const MAX_STEP_MODEL_CALLS: number;
|
|
191
|
-
/**
|
|
192
|
-
* The progressively smaller fit targets of a reactive trim, as fractions of the model's window
|
|
193
|
-
* (context compaction spec §4.3 point 5 / §4.4 point 3). The trim fix-up tries them most
|
|
194
|
-
* aggressive first (70%, then 80%, then 90% of the window) and uses the first target a fit plan
|
|
195
|
-
* actually reaches, so the retry really shrinks a request the provider rejected. `null` when the
|
|
196
|
-
* request already fits every target (nothing to trim).
|
|
197
|
-
*/
|
|
198
|
-
export declare const REACTIVE_TRIM_FACTORS: readonly [0.9, 0.8, 0.7];
|
|
199
191
|
/** 本步解析出的工具与是否启用 ToolSearch(见 `ToolRegistry.forAgent`),以及本步已取的附件字节。 */
|
|
200
192
|
export interface StepTools {
|
|
201
193
|
list: RequestTool[];
|