Skip to content

Commit a93a015

Browse files
VACIncroboclaw-bot
andauthored
fix: Responses sessions compact before reaching context limit (#130993)
* fix(agents): prevent false Responses compaction * fix(ai): reject incomplete Responses usage snapshots * fix(agents): keep staged compaction progress alive * fix(agents): align recovery compaction timeout ownership * fix(agents): preserve custom compaction watchdogs * fix(compaction): preserve timeout and task state ownership * fix(compaction): restore omitted latest requests * fix(compaction): retain source ask in split turns * fix(compaction): preserve caller cancellation * fix(compaction): preserve recovery invariants Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc * fix(compaction): preserve exact request context safely Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc * fix(compaction): bound delegated watchdog lifecycle Bound native delegated compaction from setup through post-processing while preserving progress-aware request windows. Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc * fix(compaction): rearm watchdog before fallback retry Give fallback session preparation a fresh delegated timeout window after a late provider rejection. Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc * refactor(context-engine): isolate abort helpers Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc * fix(compaction): preserve raw split requests Co-authored-by: VACInc <[email protected]> Worked on by: - @VACInc * fix(compaction): stop inferring task completion * fix(compaction): keep split-turn asks neutral * fix(compaction): ignore absent retained asks * fix(compaction): reconcile current main recovery paths * fix(compaction): bind retained ask to split prefix * test(compaction): expect neutral recovery context * fix(compaction): preserve summary source affinity * fix(compaction): preserve pending request qualifiers * fix(compaction): scope split-turn guidance * fix(compaction): feed retry feedback to split prefix * fix(compaction): audit real split-prefix format --------- Co-authored-by: VACInc <[email protected]> Co-authored-by: roboclaw-bot <[email protected]>
1 parent 49c7e91 commit a93a015

30 files changed

Lines changed: 1357 additions & 509 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2742,7 +2742,7 @@ src/config/zod-schema.channels-config.ts 3
27422742
src/config/zod-schema.core.ts 1
27432743
src/config/zod-schema.ts 2
27442744
src/context-engine/delegate.ts 1
2745-
src/context-engine/registry.ts 9
2745+
src/context-engine/registry.ts 7
27462746
src/context-engine/runtime-settings.ts 2
27472747
src/cron/delivery-channel-validation.ts 2
27482748
src/cron/delivery-context.ts 1

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -667,7 +667,7 @@ An explicit request `agentId` always wins, followed by `systemAgent.agentId`, a
667667
- `mode`: `default` or `safeguard` (chunked summarization for long histories). See [Compaction](/concepts/compaction).
668668
- `provider`: id of a registered compaction provider plugin. When set, the provider's `summarize()` is called instead of built-in LLM summarization. Falls back to built-in on failure. Setting a provider forces `mode: "safeguard"`. See [Compaction](/concepts/compaction).
669669
- `thinkingLevel`: thinking level used only for embedded OpenClaw compaction summaries (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `adaptive`, `max`, `ultra`, or `inherit`). It defaults to `low`; set `inherit` to reuse the session's current thinking level. The selected level is clamped to the compaction model/runtime. Native Codex app-server compaction ignores this setting because the native compact request has no per-operation thinking override; OpenClaw logs a warning when configured.
670-
- `timeoutSeconds`: maximum seconds allowed for a single compaction operation before OpenClaw aborts it. Default: `180`.
670+
- `timeoutSeconds`: safety window for each model request in built-in compaction. Multi-stage compaction refreshes the window when its next serial model request starts, so a complete compaction can exceed this value while an unresponsive request is still aborted. Plugin-owned compaction receives one window for the complete operation. Default: `180`.
671671
- `keepRecentTokens`: agent cut-point budget for keeping the most recent transcript tail verbatim. Default: `20000`.
672672
- `recentTurnsPreserve`: number of most recent user/assistant turns kept verbatim outside safeguard summarization. Default: `3`.
673673
- `identifierPolicy`: `strict` (default) or `off`. `strict` prepends built-in opaque identifier retention guidance during compaction summarization.

‎packages/agent-core/src/harness/compaction/compaction.test.ts‎

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -365,38 +365,14 @@ describe("session-entry compaction budgeting", () => {
365365
expect(preparation.value).toMatchObject({
366366
firstKeptEntryId: "entry-3",
367367
isSplitTurn: true,
368-
splitTurnCompleted: true,
369368
tokensBefore: 10,
370369
turnPrefixMessages: [{ role: "user" }, { role: "assistant" }],
371370
});
371+
expect(preparation.value).not.toHaveProperty("splitTurnCompleted");
372372
expect(JSON.stringify(preparation.value)).not.toContain("private output");
373373
expect(JSON.stringify(entries)).toContain("private output");
374374
});
375375

376-
it("binds split-turn completion to the cut turn instead of a newer retained turn", () => {
377-
const entries: SessionTreeEntry[] = [
378-
createMessageEntry({ role: "user", content: "boundary request", timestamp: 1 }, 0),
379-
createMessageEntry(createAssistant("boundary complete", createUsage(10), 2), 1),
380-
createMessageEntry({ role: "user", content: "newer unresolved request", timestamp: 3 }, 2),
381-
];
382-
383-
const preparation = prepareCompaction(entries, {
384-
enabled: true,
385-
reserveTokens: 0,
386-
keepRecentTokens: 8,
387-
});
388-
389-
expect(preparation.ok).toBe(true);
390-
if (!preparation.ok || !preparation.value) {
391-
throw new Error("expected the boundary turn to be split");
392-
}
393-
expect(preparation.value).toMatchObject({
394-
firstKeptEntryId: "entry-1",
395-
isSplitTurn: true,
396-
splitTurnCompleted: true,
397-
});
398-
});
399-
400376
it("applies the shared common-CJK budget heuristic", () => {
401377
expect(estimateTokens({ role: "user", content: "hello world", timestamp: 1 })).toBe(3);
402378
expect(estimateTokens({ role: "user", content: "你好世界", timestamp: 1 })).toBe(4);

‎packages/agent-core/src/harness/compaction/compaction.ts‎

Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -703,8 +703,6 @@ export interface CompactionPreparation {
703703
turnPrefixMessages: AgentMessage[];
704704
/** Whether compaction splits a turn. */
705705
isSplitTurn: boolean;
706-
/** Explicit terminal state of the turn whose prefix was split from its retained suffix. */
707-
splitTurnCompleted?: boolean;
708706
/** Estimated context tokens before compaction. */
709707
tokensBefore: number;
710708
/** Previous compaction summary used for iterative updates. */
@@ -717,24 +715,6 @@ export interface CompactionPreparation {
717715
settings: CompactionSettings;
718716
}
719717

720-
function latestUserTurnCompleted(messages: AgentMessage[]): boolean {
721-
let sawTurnTail = false;
722-
let completed = false;
723-
for (const message of messages.toReversed()) {
724-
if (message.role === "user") {
725-
return completed;
726-
}
727-
if (!sawTurnTail && (message.role === "assistant" || message.role === "toolResult")) {
728-
sawTurnTail = true;
729-
completed =
730-
message.role === "assistant" &&
731-
message.stopReason === "stop" &&
732-
message.content.some((block) => block.type === "text" && block.text.trim().length > 0);
733-
}
734-
}
735-
return false;
736-
}
737-
738718
/** Prepare session entries for compaction, or return undefined when compaction is not applicable. */
739719
export function prepareCompaction(
740720
pathEntries: SessionTreeEntry[],
@@ -844,7 +824,6 @@ export function prepareCompaction(
844824
}
845825
}
846826
const turnPrefixMessages: AgentMessage[] = [];
847-
const retainedTurnSuffixMessages: AgentMessage[] = [];
848827
if (cutPoint.isSplitTurn) {
849828
for (let i = cutPoint.turnStartIndex; i < cutPoint.firstKeptEntryIndex; i++) {
850829
const entry = effectiveEntries.at(i);
@@ -853,16 +832,6 @@ export function prepareCompaction(
853832
turnPrefixMessages.push(msg);
854833
}
855834
}
856-
for (let i = cutPoint.firstKeptEntryIndex; i < boundaryEnd; i++) {
857-
const entry = effectiveEntries.at(i);
858-
if (!entry || (i > cutPoint.firstKeptEntryIndex && isTurnStartEntry(entry))) {
859-
break;
860-
}
861-
const msg = getMessageFromEntryForCompaction(entry);
862-
if (msg) {
863-
retainedTurnSuffixMessages.push(msg);
864-
}
865-
}
866835
}
867836
if (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0) {
868837
return ok(undefined);
@@ -879,14 +848,6 @@ export function prepareCompaction(
879848
messagesToSummarize,
880849
turnPrefixMessages,
881850
isSplitTurn: cutPoint.isSplitTurn,
882-
...(cutPoint.isSplitTurn
883-
? {
884-
splitTurnCompleted: latestUserTurnCompleted([
885-
...turnPrefixMessages,
886-
...retainedTurnSuffixMessages,
887-
]),
888-
}
889-
: {}),
890851
tokensBefore,
891852
previousSummary,
892853
previousSummaryDetails,

‎packages/ai/src/providers/openai-responses-terminal-usage.test.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,14 @@ describe("mapResponsesTerminalUsage", () => {
1919
total_tokens: 110,
2020
input_tokens_details: { cached_tokens: 20, cache_write_tokens: 30 },
2121
}),
22-
).toEqual({ input: 50, output: 10, cacheRead: 20, cacheWrite: 30, totalTokens: 110 });
22+
).toEqual({
23+
input: 50,
24+
output: 10,
25+
cacheRead: 20,
26+
cacheWrite: 30,
27+
contextUsage: { state: "available", promptTokens: 100, totalTokens: 110 },
28+
totalTokens: 110,
29+
});
2330
});
2431

2532
it("derives totalTokens from the buckets when the payload omits it", () => {
@@ -28,6 +35,7 @@ describe("mapResponsesTerminalUsage", () => {
2835
output: 12,
2936
cacheRead: 0,
3037
cacheWrite: 0,
38+
contextUsage: { state: "available", promptTokens: 30, totalTokens: 42 },
3139
totalTokens: 42,
3240
});
3341
});
@@ -41,7 +49,26 @@ describe("mapResponsesTerminalUsage", () => {
4149
total_tokens: 7,
4250
input_tokens_details: { cached_tokens: 4 },
4351
}),
44-
).toEqual({ input: 0, output: 5, cacheRead: 4, cacheWrite: 0, totalTokens: 9 });
52+
).toEqual({
53+
input: 0,
54+
output: 5,
55+
cacheRead: 4,
56+
cacheWrite: 0,
57+
contextUsage: { state: "unavailable" },
58+
totalTokens: 9,
59+
});
60+
});
61+
62+
it.each([0, 29])("rejects an output-absent context snapshot whose total is %i", (totalTokens) => {
63+
expect(
64+
mapResponsesTerminalUsage({ input_tokens: 30, total_tokens: totalTokens })?.contextUsage,
65+
).toEqual({ state: "unavailable" });
66+
});
67+
68+
it("accepts an output-absent context snapshot whose total covers its input", () => {
69+
expect(mapResponsesTerminalUsage({ input_tokens: 30, total_tokens: 30 })?.contextUsage).toEqual(
70+
{ state: "available", promptTokens: 30, totalTokens: 30 },
71+
);
4572
});
4673
});
4774

‎packages/ai/src/providers/openai-responses-terminal-usage.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,12 @@ export type ResponsesTerminalUsagePayload = {
2222
output_tokens_details?: { reasoning_tokens?: number | null } | null;
2323
};
2424

25+
function readReportedCount(value: number | null | undefined): number | undefined {
26+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
27+
}
28+
2529
function readCount(value: number | null | undefined): number {
26-
return typeof value === "number" && Number.isFinite(value) ? value : 0;
30+
return readReportedCount(value) ?? 0;
2731
}
2832

2933
/**
@@ -37,7 +41,9 @@ function readCount(value: number | null | undefined): number {
3741
*/
3842
export function mapResponsesTerminalUsage(
3943
usage: ResponsesTerminalUsagePayload | undefined | null,
40-
): Pick<Usage, "input" | "output" | "cacheRead" | "cacheWrite" | "totalTokens"> | undefined {
44+
):
45+
| Pick<Usage, "input" | "output" | "cacheRead" | "cacheWrite" | "contextUsage" | "totalTokens">
46+
| undefined {
4147
if (!usage) {
4248
return undefined;
4349
}
@@ -47,7 +53,28 @@ export function mapResponsesTerminalUsage(
4753
const output = readCount(usage.output_tokens);
4854
const bucketTotal = input + output + cacheRead + cacheWrite;
4955
const totalTokens = Math.max(bucketTotal, readCount(usage.total_tokens));
50-
return { input, output, cacheRead, cacheWrite, totalTokens };
56+
const reportedInput = readReportedCount(usage.input_tokens);
57+
const reportedOutput = readReportedCount(usage.output_tokens);
58+
const reportedTotal = readReportedCount(usage.total_tokens);
59+
const hasCoherentContext =
60+
reportedInput !== undefined &&
61+
(reportedOutput !== undefined ||
62+
(reportedTotal !== undefined && reportedTotal >= reportedInput)) &&
63+
cacheRead + cacheWrite <= reportedInput;
64+
return {
65+
input,
66+
output,
67+
cacheRead,
68+
cacheWrite,
69+
contextUsage: hasCoherentContext
70+
? {
71+
state: "available",
72+
promptTokens: reportedInput,
73+
totalTokens: Math.max(totalTokens, reportedInput + (reportedOutput ?? 0)),
74+
}
75+
: { state: "unavailable" },
76+
totalTokens,
77+
};
5178
}
5279

5380
/** Reasoning tokens are reported by the agent path only; the package path does not track them. */

0 commit comments

Comments
 (0)