@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.
- package/bootstrap.json +27 -27
- package/dist/admin/admin.schemas.d.ts +7 -0
- package/dist/config/schema.d.ts +0 -2
- package/dist/config/schema.js +0 -16
- package/dist/conversations/conversations.controller.d.ts +11 -1
- package/dist/conversations/conversations.controller.js +25 -1
- package/dist/conversations/conversations.schemas.d.ts +8 -0
- package/dist/conversations/conversations.schemas.js +14 -0
- package/dist/conversations/conversations.service.d.ts +12 -0
- package/dist/conversations/conversations.service.js +10 -0
- package/dist/conversations/event-log.d.ts +14 -0
- package/dist/conversations/events.d.ts +12 -0
- package/dist/conversations/events.js +35 -3
- package/dist/db/kernel-schema.d.ts +5 -0
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +3 -0
- package/dist/evals/plan.d.ts +20 -15
- package/dist/evals/plan.js +29 -6
- package/dist/evals/reconstruct.d.ts +16 -1
- package/dist/evals/reconstruct.js +55 -1
- package/dist/evals/sets.service.d.ts +3 -2
- package/dist/evals/sets.service.js +16 -2
- package/dist/evals/step-replay.d.ts +6 -0
- package/dist/evals/step-replay.js +5 -0
- package/dist/evals/trajectory.d.ts +5 -1
- package/dist/evals/trajectory.js +3 -1
- package/dist/evals/worker.js +2 -1
- package/dist/identity/settings.d.ts +64 -0
- package/dist/identity/settings.js +86 -2
- package/dist/orgs/roles.d.ts +1 -1
- package/dist/orgs/roles.js +2 -0
- package/dist/orgs/settings.service.d.ts +17 -0
- package/dist/orgs/settings.service.js +31 -3
- package/dist/platform/ops/admin.ops.js +8 -2
- package/dist/platform/ops/conversations.ops.js +34 -0
- package/dist/platform/ops/evals.ops.js +12 -1
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/runtime/compaction-progress.d.ts +62 -0
- package/dist/runtime/compaction-progress.js +82 -0
- package/dist/runtime/compaction-settings.service.d.ts +16 -0
- package/dist/runtime/compaction-settings.service.js +42 -0
- package/dist/runtime/compaction.service.d.ts +50 -0
- package/dist/runtime/compaction.service.js +75 -0
- package/dist/runtime/context/compaction.d.ts +90 -12
- package/dist/runtime/context/compaction.js +256 -21
- package/dist/runtime/context/fit.d.ts +79 -0
- package/dist/runtime/context/fit.js +202 -0
- package/dist/runtime/model-call.d.ts +134 -5
- package/dist/runtime/model-call.js +766 -335
- package/dist/runtime/run-control.d.ts +6 -1
- package/dist/runtime/run-control.js +7 -0
- package/dist/runtime/run-queue.d.ts +14 -0
- package/dist/runtime/run-queue.js +75 -0
- package/dist/runtime/run-steps.d.ts +3 -1
- package/dist/runtime/run-steps.js +9 -2
- package/dist/runtime/run-worker.d.ts +14 -2
- package/dist/runtime/run-worker.js +160 -33
- package/dist/runtime/runtime.module.js +11 -0
- package/dist/runtime/stream.js +15 -0
- package/dist/tools/pipeline.js +6 -3
- package/package.json +1 -1
- package/src/migrations/0132_compact_runs.sql +6 -0
|
@@ -2,32 +2,112 @@ import { renderBackgroundFinished } from "../../background/render.js";
|
|
|
2
2
|
import { renderSubagentDelivery } from "../subagents/render.js";
|
|
3
3
|
import { latestSummary } from "./build.js";
|
|
4
4
|
import { scheduleHeader, senderTranscriptLabel } from "./run-context.js";
|
|
5
|
+
import { estimateTokens } from "./tokens.js";
|
|
5
6
|
import { toolsChangedText } from "./tool-changes.js";
|
|
6
7
|
/** 压缩请求的标记:放在 system 中,便于识别(model-fake 据此返回摘要)。 */
|
|
7
8
|
export const COMPACTION_MARKER = "CAPYBARA_COMPACTION";
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* The summary request's output cap when the caller gives none: the built-in default of the
|
|
11
|
+
* `compaction.maxOutputTokens` setting (context compaction spec §4.8). The effective setting is
|
|
12
|
+
* what the request uses, capped by the model's own max output.
|
|
13
|
+
*/
|
|
14
|
+
export const COMPACTION_MAX_OUTPUT_TOKENS = 20_000;
|
|
15
|
+
/** The shortest accepted summary: 200 characters or 5% of the transcript, whichever is smaller. */
|
|
11
16
|
const MIN_SUMMARY_CHARS = 200;
|
|
12
17
|
const MIN_SUMMARY_RATIO = 0.05;
|
|
13
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* The summary instruction (model-facing English): Claude Code's structured template (context
|
|
20
|
+
* compaction spec §4.2.1). The model first writes an `<analysis>` scratchpad, then a `<summary>`
|
|
21
|
+
* with nine sections; only the `<summary>` is stored and sent again in later requests.
|
|
22
|
+
*/
|
|
14
23
|
const COMPACTION_INSTRUCTION = [
|
|
15
24
|
COMPACTION_MARKER,
|
|
16
25
|
"You are summarizing the earlier part of a conversation between people and an AI agent, so the agent can continue without the full history.",
|
|
17
|
-
"Write a concise but complete summary that preserves: the users' goals and requests, decisions made, facts and data established (names, numbers, identifiers, file names, links), work completed and its results, and open questions or pending tasks.",
|
|
18
26
|
"If the transcript starts with an earlier summary, merge it into your summary.",
|
|
19
|
-
"Write in the same language as the conversation.
|
|
27
|
+
"Write in the same language as the conversation.",
|
|
28
|
+
"",
|
|
29
|
+
"Your task is to create a detailed summary of the conversation so far, paying close attention to the users' explicit requests and the agent's previous actions. This summary must be thorough: it is the only record the agent keeps of everything before it.",
|
|
30
|
+
"Before providing your final summary, wrap your analysis in <analysis>...</analysis> tags to organize your thoughts and make sure every point below is covered. In your <analysis> block, go through the conversation chronologically and identify, for each part: the users' explicit requests and intents; the agent's approach to addressing them; key decisions, technical concepts and code patterns; specific details such as file names, full code snippets, function signatures and file edits; errors that came up and how they were fixed; and specific feedback that told the agent to do something differently.",
|
|
31
|
+
"",
|
|
32
|
+
"Then write the summary inside <summary>...</summary> tags, with these sections:",
|
|
33
|
+
"1. Primary Request and Intent: capture every explicit request and intent of the users in detail.",
|
|
34
|
+
"2. Key Technical Concepts: list the important technical concepts, technologies and frameworks discussed.",
|
|
35
|
+
"3. Files and Code Sections: enumerate the files and code sections examined, modified or created. Include full snippets where they matter and say why each file or edit is important.",
|
|
36
|
+
"4. Errors and fixes: list the errors that came up and how they were fixed, including specific feedback that told the agent to do something differently.",
|
|
37
|
+
"5. Problem Solving: document the problems solved and any troubleshooting still open.",
|
|
38
|
+
"6. All user messages: list all user messages (not tool results), since they carry the users' feedback and changing intent.",
|
|
39
|
+
"7. Pending Tasks: outline the tasks the users explicitly asked for that are still open.",
|
|
40
|
+
"8. Current Work: describe in detail exactly what was being worked on immediately before this summary request, with file names and code snippets where applicable, and quote the most recent messages.",
|
|
41
|
+
"9. Optional Next Step: the next step directly in line with the most recent work, quoting the most recent conversation verbatim so the task does not drift. If the last task was concluded, only list a next step the users' requests explicitly call for; do not start tangential work.",
|
|
42
|
+
"",
|
|
43
|
+
'If a section does not apply to the conversation, write "Not applicable" or leave it out.',
|
|
44
|
+
"There may be additional summarization instructions in the transcript; follow them too.",
|
|
45
|
+
"Output the <analysis> block followed by the <summary> block and nothing else.",
|
|
20
46
|
].join("\n");
|
|
21
|
-
/**
|
|
22
|
-
|
|
23
|
-
|
|
47
|
+
/**
|
|
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).
|
|
50
|
+
*/
|
|
51
|
+
export function compactionInputBudget(window, maxOutput, reserve) {
|
|
52
|
+
return window - maxOutput - reserve;
|
|
53
|
+
}
|
|
54
|
+
/** The transcript wrapper of a summary request; the overhead counts it with an empty transcript. */
|
|
55
|
+
const transcriptWrapper = (text) => `<transcript>\n${text}\n</transcript>`;
|
|
56
|
+
/** A margin for estimator drift in the fixed part of a summary request (tokens). */
|
|
57
|
+
const COMPACTION_REQUEST_MARGIN = 64;
|
|
58
|
+
/**
|
|
59
|
+
* The input tokens every summary request carries regardless of its chunk: the instruction, the
|
|
60
|
+
* transcript wrapper and a small margin. A chunked compaction subtracts it from the chunk size
|
|
61
|
+
* (context compaction spec §4.5), so chunk + overhead stays inside the request budget.
|
|
62
|
+
*/
|
|
63
|
+
export function compactionRequestOverhead() {
|
|
64
|
+
return (textTokens(COMPACTION_INSTRUCTION) +
|
|
65
|
+
textTokens(transcriptWrapper("")) +
|
|
66
|
+
COMPACTION_REQUEST_MARGIN);
|
|
24
67
|
}
|
|
25
68
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
69
|
+
* The chunk size of a chunked compaction (context compaction spec §4.5): one summary call's input
|
|
70
|
+
* budget `B` minus the room the running summary may take in the next call (half the output cap) and
|
|
71
|
+
* the request's fixed overhead.
|
|
72
|
+
*/
|
|
73
|
+
export function compactionChunkSize(budget, maxOutputTokens) {
|
|
74
|
+
return budget - Math.ceil(maxOutputTokens / 2) - compactionRequestOverhead();
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The floor of one summary chunk (context compaction spec §4.5): the running summary can shrink a
|
|
78
|
+
* later chunk below it, and such a chunk fails with a clear reason instead of letting
|
|
79
|
+
* {@link nextTranscriptChunk} clamp to one token and make a call per token. A base chunk below it
|
|
80
|
+
* (a window that leaves no room for a chunked compaction) falls back to one call over the whole
|
|
81
|
+
* transcript.
|
|
82
|
+
*/
|
|
83
|
+
export const MIN_COMPACTION_CHUNK_TOKENS = 256;
|
|
84
|
+
/**
|
|
85
|
+
* 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).
|
|
29
89
|
*/
|
|
30
|
-
export function
|
|
90
|
+
export function shouldCompact(estimate, window, settings) {
|
|
91
|
+
const output = settings.maxOutputTokens;
|
|
92
|
+
if (estimate + output > window)
|
|
93
|
+
return true;
|
|
94
|
+
if (!settings.enabled)
|
|
95
|
+
return false;
|
|
96
|
+
return (estimate >=
|
|
97
|
+
Math.min(settings.threshold * window, compactionInputBudget(window, output, settings.reserveTokens)));
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The compaction plan: keep the most recent `settings.keepRecentTurns` turns verbatim (a maximum,
|
|
101
|
+
* not a rule) and transcribe everything older that the previous summary does not cover yet (that
|
|
102
|
+
* summary goes first, for the new summary to merge).
|
|
103
|
+
*
|
|
104
|
+
* The kept tail shrinks turn by turn, down to the latest user turn, until its estimated tokens fit
|
|
105
|
+
* `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.
|
|
109
|
+
*/
|
|
110
|
+
export function compactionPlan(events, settings, budget) {
|
|
31
111
|
const sorted = [...events].sort((a, b) => a.seq - b.seq);
|
|
32
112
|
const prev = latestSummary(sorted);
|
|
33
113
|
const floor = prev ? prev.payload.coversUpToSeq : Number.NEGATIVE_INFINITY;
|
|
@@ -37,14 +117,30 @@ export function compactionPlan(events, keepRecentTurns) {
|
|
|
37
117
|
if (e.type === "user_message")
|
|
38
118
|
userIdx.push(i);
|
|
39
119
|
});
|
|
120
|
+
const keep = settings.keepRecentTurns;
|
|
40
121
|
let boundary;
|
|
41
|
-
if (
|
|
122
|
+
if (keep <= 0)
|
|
42
123
|
boundary = candidate.length;
|
|
43
|
-
else if (userIdx.length <
|
|
124
|
+
else if (userIdx.length < keep)
|
|
44
125
|
boundary = 0;
|
|
45
126
|
else
|
|
46
|
-
boundary = userIdx[userIdx.length -
|
|
127
|
+
boundary = userIdx[userIdx.length - keep];
|
|
47
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;
|
|
135
|
+
for (const start of userIdx) {
|
|
136
|
+
if (start <= boundary)
|
|
137
|
+
continue;
|
|
138
|
+
chosen = keepToolPairs(candidate, userIdx, start);
|
|
139
|
+
if (tailTokens(candidate, chosen) <= budget)
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
boundary = chosen;
|
|
143
|
+
}
|
|
48
144
|
const lines = [];
|
|
49
145
|
for (const e of candidate.slice(0, boundary)) {
|
|
50
146
|
const line = transcriptLine(e);
|
|
@@ -61,6 +157,20 @@ export function compactionPlan(events, keepRecentTurns) {
|
|
|
61
157
|
const parts = prev ? [`[Earlier summary]\n${prev.payload.text}`, ...lines] : lines;
|
|
62
158
|
return { coversUpToSeq, transcript: parts.join("\n\n") };
|
|
63
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Estimated input tokens of the kept tail (the events rendered as the transcript renders them, then
|
|
162
|
+
* estimated with the request estimator).
|
|
163
|
+
*/
|
|
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 }] }], []);
|
|
171
|
+
}
|
|
172
|
+
return tokens;
|
|
173
|
+
}
|
|
64
174
|
/**
|
|
65
175
|
* 边界不得切开工具调用与其结果:工具运行期间到达的插话(user_message)记在 assistant 的 tool_call 与
|
|
66
176
|
* tool_result 之间,若它成了边界,assistant 进摘要而结果留在原文,构建请求时结果因找不到调用被丢弃。
|
|
@@ -174,23 +284,148 @@ function renderBlocks(blocks) {
|
|
|
174
284
|
}
|
|
175
285
|
return out.join("\n");
|
|
176
286
|
}
|
|
177
|
-
/**
|
|
178
|
-
|
|
287
|
+
/**
|
|
288
|
+
* The text to store as the compaction summary (context compaction spec §4.2.1): the `<summary>`
|
|
289
|
+
* block when the model returned one, since the `<analysis>` scratchpad must never be sent in a
|
|
290
|
+
* later request; otherwise the answer with any `<analysis>` block and any dangling `<summary>` tag
|
|
291
|
+
* removed (a truncated response may have been cut off after the opening tag). Trimmed; an empty
|
|
292
|
+
* result fails the attempt.
|
|
293
|
+
*/
|
|
294
|
+
export function extractSummary(text) {
|
|
295
|
+
const block = /<summary>([\s\S]*?)<\/summary>/i.exec(text);
|
|
296
|
+
if (block)
|
|
297
|
+
return (block[1] ?? "").trim();
|
|
298
|
+
return text
|
|
299
|
+
.replace(/<analysis>[\s\S]*?<\/analysis>/gi, "")
|
|
300
|
+
.replace(/<\/?summary>/gi, "")
|
|
301
|
+
.trim();
|
|
302
|
+
}
|
|
303
|
+
/** The marker a hard-split line carries where it was cut (context compaction spec §4.5). */
|
|
304
|
+
const CHUNK_SPLIT_MARKER = "\n[chunk split]\n";
|
|
305
|
+
/** Estimated tokens the split marker adds to a chunk. */
|
|
306
|
+
const CHUNK_SPLIT_TOKENS = textTokens(CHUNK_SPLIT_MARKER);
|
|
307
|
+
/** Estimated tokens a line separator adds to a chunk. */
|
|
308
|
+
const NEWLINE_TOKENS = textTokens("\n");
|
|
309
|
+
/**
|
|
310
|
+
* The next chunk of a transcript and what is left to summarise (context compaction spec §4.5):
|
|
311
|
+
* whole lines up to `chunkSize` estimated tokens, counting the line separators; a single line over
|
|
312
|
+
* the chunk size (usually a tool result) is hard-split at a character boundary with the split
|
|
313
|
+
* marker, never inside a UTF-16 surrogate pair, and the rest of the line stays for the next call.
|
|
314
|
+
* Null for empty input.
|
|
315
|
+
*/
|
|
316
|
+
export function nextTranscriptChunk(transcript, chunkSize) {
|
|
317
|
+
if (transcript.length === 0)
|
|
318
|
+
return null;
|
|
319
|
+
const max = Math.max(1, chunkSize);
|
|
320
|
+
const lines = transcript.split("\n");
|
|
321
|
+
const taken = [];
|
|
322
|
+
let tokens = 0;
|
|
323
|
+
let ended = 0;
|
|
324
|
+
for (let i = 0; i < lines.length; i++) {
|
|
325
|
+
const line = lines[i];
|
|
326
|
+
const lineTokens = textTokens(line);
|
|
327
|
+
if (lineTokens > max && taken.length === 0) {
|
|
328
|
+
// the loop only breaks on the transcript's first line (every other line is taken or ends a
|
|
329
|
+
// chunk), so the rest is the transcript after the piece: no marker is left in it, or the
|
|
330
|
+
// next split would count the marker as content
|
|
331
|
+
const pieces = splitLine(line, Math.max(1, max - CHUNK_SPLIT_TOKENS));
|
|
332
|
+
const head = pieces[0];
|
|
333
|
+
return { chunk: `${head}${CHUNK_SPLIT_MARKER}`, rest: transcript.slice(head.length) };
|
|
334
|
+
}
|
|
335
|
+
const cost = lineTokens + (taken.length > 0 ? NEWLINE_TOKENS : 0);
|
|
336
|
+
if (taken.length > 0 && tokens + cost > max)
|
|
337
|
+
break;
|
|
338
|
+
taken.push(line);
|
|
339
|
+
tokens += cost;
|
|
340
|
+
ended = i + 1;
|
|
341
|
+
}
|
|
342
|
+
return { chunk: taken.join("\n"), rest: lines.slice(ended).join("\n") };
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Splits a transcript into chunks of at most `chunkSize` estimated tokens at line boundaries
|
|
346
|
+
* (context compaction spec §4.5). A single line over the chunk size is hard-split at a character
|
|
347
|
+
* boundary rather than failing, its pieces marked with {@link CHUNK_SPLIT_MARKER}. Empty input
|
|
348
|
+
* returns no chunks; input that fits returns itself as the only chunk.
|
|
349
|
+
*/
|
|
350
|
+
export function chunkTranscript(transcript, chunkSize) {
|
|
351
|
+
const chunks = [];
|
|
352
|
+
let rest = transcript;
|
|
353
|
+
while (rest !== null) {
|
|
354
|
+
const next = nextTranscriptChunk(rest, chunkSize);
|
|
355
|
+
if (next === null)
|
|
356
|
+
break;
|
|
357
|
+
// an empty piece carries nothing (a transcript of blank lines only)
|
|
358
|
+
if (next.chunk !== "")
|
|
359
|
+
chunks.push(next.chunk);
|
|
360
|
+
rest = next.rest.length === 0 ? null : next.rest;
|
|
361
|
+
}
|
|
362
|
+
return chunks;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Cuts a line into pieces of at most `max` estimated tokens, at character boundaries. Iterates
|
|
366
|
+
* code points (not UTF-16 units), so a surrogate pair is never split.
|
|
367
|
+
*/
|
|
368
|
+
function splitLine(line, max) {
|
|
369
|
+
const pieces = [];
|
|
370
|
+
let start = 0;
|
|
371
|
+
let ascii = 0;
|
|
372
|
+
let other = 0;
|
|
373
|
+
let i = 0;
|
|
374
|
+
while (i < line.length) {
|
|
375
|
+
const code = line.codePointAt(i);
|
|
376
|
+
const isAscii = code < 128;
|
|
377
|
+
const nextAscii = ascii + (isAscii ? 1 : 0);
|
|
378
|
+
const nextOther = other + (isAscii ? 0 : 1);
|
|
379
|
+
if (i > start && Math.ceil(nextAscii / 4 + nextOther) > max) {
|
|
380
|
+
pieces.push(line.slice(start, i));
|
|
381
|
+
start = i;
|
|
382
|
+
ascii = isAscii ? 1 : 0;
|
|
383
|
+
other = isAscii ? 0 : 1;
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
ascii = nextAscii;
|
|
387
|
+
other = nextOther;
|
|
388
|
+
}
|
|
389
|
+
// a surrogate pair is two UTF-16 units, one code point
|
|
390
|
+
i += code > 0xffff ? 2 : 1;
|
|
391
|
+
}
|
|
392
|
+
pieces.push(line.slice(start));
|
|
393
|
+
return pieces;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* The summary request: the marked English instruction as the system prompt and the transcript as
|
|
397
|
+
* the only user message. `maxOutputTokens` is the effective `compaction.maxOutputTokens` setting,
|
|
398
|
+
* which the caller narrows to the model's own cap (context compaction spec §4.8); omitted, it is
|
|
399
|
+
* the built-in default.
|
|
400
|
+
*/
|
|
401
|
+
export function buildCompactionRequest(transcript, model, maxOutputTokens = COMPACTION_MAX_OUTPUT_TOKENS) {
|
|
179
402
|
return {
|
|
180
403
|
model,
|
|
181
404
|
system: [{ text: COMPACTION_INSTRUCTION, cache: false }],
|
|
182
405
|
messages: [
|
|
183
406
|
{
|
|
184
407
|
role: "user",
|
|
185
|
-
content: [{ type: "text", text:
|
|
408
|
+
content: [{ type: "text", text: transcriptWrapper(transcript) }],
|
|
186
409
|
},
|
|
187
410
|
],
|
|
188
411
|
tools: [],
|
|
189
|
-
maxOutputTokens
|
|
412
|
+
maxOutputTokens,
|
|
190
413
|
params: {},
|
|
191
414
|
};
|
|
192
415
|
}
|
|
193
|
-
/**
|
|
416
|
+
/** Estimated input tokens of a plain text (a user message carries nothing else). */
|
|
417
|
+
function textTokens(text) {
|
|
418
|
+
return estimateTokens([{ role: "user", content: [{ type: "text", text }] }], []);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* What a compaction saved (context compaction spec §4.9): the estimated transcript input minus the
|
|
422
|
+
* stored summary output. Floored at zero — a summary at least as long as the transcript saved no
|
|
423
|
+
* tokens, and `savedTokens` is a non-negative count — so the UI can render it as "saved N".
|
|
424
|
+
*/
|
|
425
|
+
export function summarySavedTokens(transcript, summary) {
|
|
426
|
+
return Math.max(0, textTokens(transcript) - textTokens(summary));
|
|
427
|
+
}
|
|
428
|
+
/** A summary of at least min(200, 5% of the transcript) characters is accepted; shorter fails. */
|
|
194
429
|
export function acceptSummary(text, transcript) {
|
|
195
430
|
const min = Math.min(MIN_SUMMARY_CHARS, transcript.length * MIN_SUMMARY_RATIO);
|
|
196
431
|
return text.trim().length >= min;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { ModelInfo, ModelRequest } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { ConversationEvent } from "../../conversations/events.js";
|
|
3
|
+
/**
|
|
4
|
+
* The hard fit guard (context compaction spec §4.3): a request whose input is over the fit target is
|
|
5
|
+
* trimmed with a deterministic plan, recorded in `model_call.request.fit`, and replayed by applying
|
|
6
|
+
* the same plan to the rebuilt request (byte-for-byte).
|
|
7
|
+
*
|
|
8
|
+
* A plan names **indexes into the assembled request's message list**: `droppedMessageIndexes` are
|
|
9
|
+
* message positions, and a `truncated` entry is the block index inside that message. Indexes keep
|
|
10
|
+
* `applyFit` a pure function of the request alone; the builder and the replay path assemble the same
|
|
11
|
+
* messages from the same log, so the same plan applies to both. A message is never split from its
|
|
12
|
+
* tool call/result partner.
|
|
13
|
+
*/
|
|
14
|
+
export interface FitPlan {
|
|
15
|
+
/** Indexes into the assembled request's messages, in the order they were chosen. */
|
|
16
|
+
droppedMessageIndexes: number[];
|
|
17
|
+
/** Text / tool_result blocks of the kept tail replaced by the note. */
|
|
18
|
+
truncated: {
|
|
19
|
+
messageIndex: number;
|
|
20
|
+
block: number;
|
|
21
|
+
note: string;
|
|
22
|
+
}[];
|
|
23
|
+
}
|
|
24
|
+
/** The note an oversized block carries once truncated (model-visible, English; spec §4.3). */
|
|
25
|
+
export declare const FIT_TRUNCATION_NOTE = "[content truncated to fit the model's context window]";
|
|
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.
|
|
30
|
+
*/
|
|
31
|
+
export declare function clampOutput(contextWindow: number, maxOutputTokens: number, estimate: number): number;
|
|
32
|
+
/**
|
|
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.
|
|
36
|
+
*/
|
|
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;
|
|
40
|
+
export interface PlanFitInput {
|
|
41
|
+
/** The log the request was built from (documentation: the plan replays from it). */
|
|
42
|
+
events: ConversationEvent[];
|
|
43
|
+
/** The assembled request (after the pairing guard and the output-cap computation). */
|
|
44
|
+
request: ModelRequest;
|
|
45
|
+
/** The model the request is for: its context window is the hard bound. */
|
|
46
|
+
model: ModelInfo;
|
|
47
|
+
/** `O`: the requested output cap (`ModelRequest.maxOutputTokens`, before the clamp). */
|
|
48
|
+
maxOutputTokens: number;
|
|
49
|
+
/** `R`: the safety reserve in effect for the run's organization, before the clamp. */
|
|
50
|
+
reserveTokens: number;
|
|
51
|
+
/** The request's input-token estimate (uncalibrated, as recorded). */
|
|
52
|
+
estimate: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
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.
|
|
60
|
+
*
|
|
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
|
+
*/
|
|
67
|
+
export declare function planFit(input: PlanFitInput): FitPlan | null;
|
|
68
|
+
/**
|
|
69
|
+
* Applies a plan to an assembled request (pure): drops the named messages and replaces the named
|
|
70
|
+
* blocks' content with their note. Message and block indexes refer to the request as given, so the
|
|
71
|
+
* runtime and the replay path (rebuilding the same messages from the log) produce the same request.
|
|
72
|
+
*/
|
|
73
|
+
export declare function applyFit(request: ModelRequest, plan: FitPlan): ModelRequest;
|
|
74
|
+
/**
|
|
75
|
+
* The request's estimate after `plan` is applied: the given estimate minus the dropped messages and
|
|
76
|
+
* the truncated blocks' savings. Same arithmetic as {@link planFit} used to stop, so a plan that
|
|
77
|
+
* reached the target is known to have done so without re-estimating the whole request.
|
|
78
|
+
*/
|
|
79
|
+
export declare function estimateAfterFit(request: ModelRequest, estimate: number, plan: FitPlan): number;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { estimateTokens } from "./tokens.js";
|
|
2
|
+
/** The note an oversized block carries once truncated (model-visible, English; spec §4.3). */
|
|
3
|
+
export const FIT_TRUNCATION_NOTE = "[content truncated to fit the model's context window]";
|
|
4
|
+
/**
|
|
5
|
+
* The output cap actually sent (`O'`, spec §4.3 point 2): the configured cap, lowered so the
|
|
6
|
+
* provider-visible total (`input + O'`) fits the window. At least one output token is always left.
|
|
7
|
+
* When the window is smaller than the requested cap this is what keeps the plan's target reachable.
|
|
8
|
+
*/
|
|
9
|
+
export function clampOutput(contextWindow, maxOutputTokens, estimate) {
|
|
10
|
+
return Math.max(1, Math.min(maxOutputTokens, Math.max(1, contextWindow - estimate)));
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The reserve actually kept (`R_eff`, spec §4.3 point 2): the configured reserve, reduced to what
|
|
14
|
+
* the clamped output leaves below the window. A reserve larger than the window is sacrificed
|
|
15
|
+
* (the hard bound is what must hold), so the target keeps at least one token of room.
|
|
16
|
+
*/
|
|
17
|
+
export function effectiveReserve(contextWindow, clampedOutput, reserveTokens) {
|
|
18
|
+
return Math.min(reserveTokens, Math.max(0, contextWindow - clampedOutput - 1));
|
|
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
|
+
}
|
|
24
|
+
const SUMMARY_OPEN = "<conversation_summary>";
|
|
25
|
+
const NOTE_TOKENS = estimateTokens([{ role: "user", content: [{ type: "text", text: FIT_TRUNCATION_NOTE }] }], []);
|
|
26
|
+
/** A typed user turn (a person's message), not a tool-result carrier and not the summary. */
|
|
27
|
+
const isTypedUser = (m) => m.role === "user" && m.content.some((b) => b.type !== "tool_result");
|
|
28
|
+
/** A message that carries only tool results (the answer to a tool call). */
|
|
29
|
+
const isResults = (m) => m.role === "user" && m.content.length > 0 && m.content.every((b) => b.type === "tool_result");
|
|
30
|
+
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
|
+
const messageTokens = (m) => estimateTokens([m], [], []);
|
|
34
|
+
const blockTokens = (b) => estimateTokens([{ role: "user", content: [b] }], [], []);
|
|
35
|
+
const truncatable = (b) => (b.type === "text" && b.text !== FIT_TRUNCATION_NOTE) ||
|
|
36
|
+
(b.type === "tool_result" && b.content !== FIT_TRUNCATION_NOTE);
|
|
37
|
+
/**
|
|
38
|
+
* The deterministic fit plan for a request over `W - O' - R_eff` (the output cap and reserve first
|
|
39
|
+
* clamped to the window, {@link clampOutput} / {@link effectiveReserve}), or null when it already
|
|
40
|
+
* fits. A plan that cannot reach the target even after dropping every droppable message and
|
|
41
|
+
* truncating every kept text / `tool_result` block is still returned: the caller raises
|
|
42
|
+
* `run.context_too_large` before any provider call.
|
|
43
|
+
*
|
|
44
|
+
* Drops, in this order, every droppable message before the latest user turn until the estimate is
|
|
45
|
+
* at or below the target: complete tool pairs first (a tool call with the results message that
|
|
46
|
+
* follows it), then assistant text, then complete older user turns. Never a pair's half, never the
|
|
47
|
+
* summary. If that is not enough, it truncates the kept tail's largest text / `tool_result` blocks
|
|
48
|
+
* (replacing the content with {@link FIT_TRUNCATION_NOTE}).
|
|
49
|
+
*/
|
|
50
|
+
export function planFit(input) {
|
|
51
|
+
const { request, model, maxOutputTokens, reserveTokens, estimate } = input;
|
|
52
|
+
const output = clampOutput(model.contextWindow, maxOutputTokens, estimate);
|
|
53
|
+
const reserve = effectiveReserve(model.contextWindow, output, reserveTokens);
|
|
54
|
+
const target = fitTarget(model.contextWindow, output, reserve);
|
|
55
|
+
if (target <= 0 || estimate <= target)
|
|
56
|
+
return null;
|
|
57
|
+
const messages = request.messages;
|
|
58
|
+
// the latest user turn and everything after it are kept (the turn being answered); older
|
|
59
|
+
// messages may go
|
|
60
|
+
const lastTyped = messages.findLastIndex(isTypedUser);
|
|
61
|
+
const keepFrom = lastTyped < 0 ? messages.length : lastTyped;
|
|
62
|
+
const droppable = (i) => {
|
|
63
|
+
const m = messages[i];
|
|
64
|
+
return i < keepFrom && m !== undefined && m.role !== "system" && !isSummary(m);
|
|
65
|
+
};
|
|
66
|
+
const plan = { droppedMessageIndexes: [], truncated: [] };
|
|
67
|
+
const dropped = new Set();
|
|
68
|
+
let current = estimate;
|
|
69
|
+
const drop = (indexes) => {
|
|
70
|
+
for (const i of indexes) {
|
|
71
|
+
if (dropped.has(i))
|
|
72
|
+
continue;
|
|
73
|
+
const m = messages[i];
|
|
74
|
+
if (m === undefined)
|
|
75
|
+
continue;
|
|
76
|
+
dropped.add(i);
|
|
77
|
+
plan.droppedMessageIndexes.push(i);
|
|
78
|
+
current -= messageTokens(m);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
// complete tool pairs, oldest first: an assistant message with at least one tool call and the
|
|
82
|
+
// results message that follows it stay together (its half would orphan the other)
|
|
83
|
+
for (let i = 0; i < keepFrom && current > target; i++) {
|
|
84
|
+
if (!droppable(i))
|
|
85
|
+
continue;
|
|
86
|
+
const m = messages[i];
|
|
87
|
+
if (!hasToolCall(m))
|
|
88
|
+
continue;
|
|
89
|
+
const next = messages[i + 1];
|
|
90
|
+
if (next === undefined || i + 1 >= keepFrom || !isResults(next))
|
|
91
|
+
continue;
|
|
92
|
+
drop([i, i + 1]);
|
|
93
|
+
i++;
|
|
94
|
+
}
|
|
95
|
+
// assistant text, oldest first
|
|
96
|
+
for (let i = 0; i < keepFrom && current > target; i++) {
|
|
97
|
+
if (!droppable(i) || dropped.has(i))
|
|
98
|
+
continue;
|
|
99
|
+
const m = messages[i];
|
|
100
|
+
if (m.role !== "assistant" || hasToolCall(m))
|
|
101
|
+
continue;
|
|
102
|
+
drop([i]);
|
|
103
|
+
}
|
|
104
|
+
// complete older user turns, oldest first (their replies are already gone)
|
|
105
|
+
for (let i = 0; i < keepFrom && current > target; i++) {
|
|
106
|
+
if (!droppable(i) || dropped.has(i))
|
|
107
|
+
continue;
|
|
108
|
+
if (!isTypedUser(messages[i]))
|
|
109
|
+
continue;
|
|
110
|
+
drop([i]);
|
|
111
|
+
}
|
|
112
|
+
if (current <= target)
|
|
113
|
+
return plan;
|
|
114
|
+
// the latest turn alone is too large: replace its largest text / tool_result blocks (and those of
|
|
115
|
+
// the kept tail) with the note, largest first, ties by position
|
|
116
|
+
const candidates = [];
|
|
117
|
+
for (let i = keepFrom; i < messages.length; i++) {
|
|
118
|
+
const m = messages[i];
|
|
119
|
+
if (m === undefined || m.role === "system" || isSummary(m))
|
|
120
|
+
continue;
|
|
121
|
+
m.content.forEach((b, block) => {
|
|
122
|
+
if (!truncatable(b))
|
|
123
|
+
return;
|
|
124
|
+
const tokens = blockTokens(b);
|
|
125
|
+
if (tokens > NOTE_TOKENS)
|
|
126
|
+
candidates.push({ messageIndex: i, block, tokens });
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
candidates.sort((a, b) => b.tokens - a.tokens || a.messageIndex - b.messageIndex || a.block - b.block);
|
|
130
|
+
for (const c of candidates) {
|
|
131
|
+
if (current <= target)
|
|
132
|
+
break;
|
|
133
|
+
current -= c.tokens - NOTE_TOKENS;
|
|
134
|
+
plan.truncated.push({
|
|
135
|
+
messageIndex: c.messageIndex,
|
|
136
|
+
block: c.block,
|
|
137
|
+
note: FIT_TRUNCATION_NOTE,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return plan;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Applies a plan to an assembled request (pure): drops the named messages and replaces the named
|
|
144
|
+
* blocks' content with their note. Message and block indexes refer to the request as given, so the
|
|
145
|
+
* runtime and the replay path (rebuilding the same messages from the log) produce the same request.
|
|
146
|
+
*/
|
|
147
|
+
export function applyFit(request, plan) {
|
|
148
|
+
const dropped = new Set(plan.droppedMessageIndexes);
|
|
149
|
+
const truncated = new Map();
|
|
150
|
+
for (const t of plan.truncated) {
|
|
151
|
+
const byBlock = truncated.get(t.messageIndex) ?? new Map();
|
|
152
|
+
byBlock.set(t.block, t.note);
|
|
153
|
+
truncated.set(t.messageIndex, byBlock);
|
|
154
|
+
}
|
|
155
|
+
const messages = [];
|
|
156
|
+
request.messages.forEach((m, i) => {
|
|
157
|
+
if (dropped.has(i))
|
|
158
|
+
return;
|
|
159
|
+
const notes = truncated.get(i);
|
|
160
|
+
if (notes === undefined || m.role === "system") {
|
|
161
|
+
messages.push(m);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
messages.push({
|
|
165
|
+
...m,
|
|
166
|
+
content: m.content.map((b, block) => {
|
|
167
|
+
const note = notes.get(block);
|
|
168
|
+
if (note === undefined)
|
|
169
|
+
return b;
|
|
170
|
+
if (b.type === "text")
|
|
171
|
+
return { type: "text", text: note };
|
|
172
|
+
if (b.type === "tool_result")
|
|
173
|
+
return { ...b, content: note };
|
|
174
|
+
return b;
|
|
175
|
+
}),
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
return { ...request, messages };
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* The request's estimate after `plan` is applied: the given estimate minus the dropped messages and
|
|
182
|
+
* the truncated blocks' savings. Same arithmetic as {@link planFit} used to stop, so a plan that
|
|
183
|
+
* reached the target is known to have done so without re-estimating the whole request.
|
|
184
|
+
*/
|
|
185
|
+
export function estimateAfterFit(request, estimate, plan) {
|
|
186
|
+
let out = estimate;
|
|
187
|
+
for (const i of plan.droppedMessageIndexes) {
|
|
188
|
+
const m = request.messages[i];
|
|
189
|
+
if (m !== undefined)
|
|
190
|
+
out -= messageTokens(m);
|
|
191
|
+
}
|
|
192
|
+
for (const t of plan.truncated) {
|
|
193
|
+
const m = request.messages[t.messageIndex];
|
|
194
|
+
if (m === undefined || m.role === "system")
|
|
195
|
+
continue;
|
|
196
|
+
const b = m.content[t.block];
|
|
197
|
+
if (b === undefined)
|
|
198
|
+
continue;
|
|
199
|
+
out -= blockTokens(b) - NOTE_TOKENS;
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|