Skip to content

Commit 23264c6

Browse files
committed
feat(agents): add mid-turn compaction precheck
1 parent a4e92c0 commit 23264c6

19 files changed

Lines changed: 572 additions & 8 deletions

‎docs/gateway/config-agents.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,7 @@ Periodic heartbeat runs.
555555
identifierPolicy: "strict", // strict | off | custom
556556
identifierInstructions: "Preserve deployment IDs, ticket IDs, and host:port pairs exactly.", // used when identifierPolicy=custom
557557
qualityGuard: { enabled: true, maxRetries: 1 },
558+
midTurnPrecheck: { enabled: false }, // optional Pi tool-loop pressure check
558559
postCompactionSections: ["Session Startup", "Red Lines"], // [] disables reinjection
559560
model: "openrouter/anthropic/claude-sonnet-4-6", // optional compaction-only model override
560561
truncateAfterCompaction: true, // rotate to a smaller successor JSONL after compaction
@@ -580,6 +581,7 @@ Periodic heartbeat runs.
580581
- `identifierPolicy`: `strict` (default), `off`, or `custom`. `strict` prepends built-in opaque identifier retention guidance during compaction summarization.
581582
- `identifierInstructions`: optional custom identifier-preservation text used when `identifierPolicy=custom`.
582583
- `qualityGuard`: retry-on-malformed-output checks for safeguard summaries. Enabled by default in safeguard mode; set `enabled: false` to skip the audit.
584+
- `midTurnPrecheck`: optional Pi tool-loop pressure check. When `enabled: true`, OpenClaw checks context pressure after tool results are appended and before the next model call. If the context no longer fits, it aborts the current attempt before submitting the prompt and reuses the existing precheck recovery path to truncate tool results or compact and retry. Works with both `default` and `safeguard` compaction modes. Default: disabled.
583585
- `postCompactionSections`: optional AGENTS.md H2/H3 section names to re-inject after compaction. Defaults to `["Session Startup", "Red Lines"]`; set `[]` to disable reinjection. When unset or explicitly set to that default pair, older `Every Session`/`Safety` headings are also accepted as a legacy fallback.
584586
- `model`: optional `provider/model-id` override for compaction summarization only. Use this when the main session should keep one model but compaction summaries should run on another; when unset, compaction uses the session's primary model.
585587
- `maxActiveTranscriptBytes`: optional byte threshold (`number` or strings like `"20mb"`) that triggers normal local compaction before a run when the active JSONL grows past the threshold. Requires `truncateAfterCompaction` so successful compaction can rotate to a smaller successor transcript. Disabled when unset or `0`.

‎docs/reference/session-management-compaction.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,20 @@ reopen cost, not raw archival: OpenClaw still runs normal semantic compaction,
272272
and it requires `truncateAfterCompaction` so the compacted summary can become a
273273
new successor transcript.
274274

275+
For embedded Pi runs, `agents.defaults.compaction.midTurnPrecheck.enabled: true`
276+
adds an opt-in tool-loop guard. After a tool result is appended and before the
277+
next model call, OpenClaw estimates the prompt pressure using the same preflight
278+
budget logic used at turn start. If the context no longer fits, the guard does
279+
not compact inside Pi's `transformContext` hook. It raises a structured
280+
mid-turn precheck signal, stops the current prompt submission, and lets the
281+
outer run loop use the existing recovery path: truncate oversized tool results
282+
when that is enough, or trigger the configured compaction mode and retry. The
283+
option is disabled by default and works with both `default` and `safeguard`
284+
compaction modes, including provider-backed safeguard compaction.
285+
This is independent of `maxActiveTranscriptBytes`: the byte-size guard runs
286+
before a turn opens, while mid-turn precheck runs later in the embedded Pi tool
287+
loop after new tool results have been appended.
288+
275289
---
276290

277291
## Compaction settings (`reserveTokens`, `keepRecentTokens`)
@@ -298,6 +312,11 @@ OpenClaw also enforces a safety floor for embedded runs:
298312
and keeps Pi's recent-tail cut point. Without an explicit keep budget,
299313
manual compaction remains a hard checkpoint and rebuilt context starts from
300314
the new summary.
315+
- Set `agents.defaults.compaction.midTurnPrecheck.enabled: true` to run the
316+
optional tool-loop precheck after new tool results and before the next model
317+
call. This is a trigger only; summary generation still uses the configured
318+
compaction path. It is independent of `maxActiveTranscriptBytes`, which is a
319+
turn-start active-transcript byte-size guard.
301320
- Set `agents.defaults.compaction.maxActiveTranscriptBytes` to a byte value or
302321
string such as `"20mb"` to run local compaction before a turn when the active
303322
transcript gets large. This guard is active only when
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const CONTEXT_LIMIT_TRUNCATION_NOTICE = "more characters truncated";
2+
3+
export function formatContextLimitTruncationNotice(truncatedChars: number): string {
4+
return `[... ${Math.max(1, Math.floor(truncatedChars))} ${CONTEXT_LIMIT_TRUNCATION_NOTICE}]`;
5+
}

‎src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
22
import path from "node:path";
33
import type { AgentMessage } from "@mariozechner/pi-agent-core";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import type { OpenClawConfig } from "../../../config/types.js";
56
import { buildMemorySystemPromptAddition } from "../../../context-engine/delegate.js";
67
import {
78
clearMemoryPluginState,
@@ -29,6 +30,7 @@ import {
2930
buildEmbeddedSubscriptionParams,
3031
cleanupEmbeddedAttemptResources,
3132
} from "./attempt.subscription-cleanup.js";
33+
import type { MidTurnPrecheckRequest } from "./midturn-precheck.js";
3234

3335
const hoisted = getHoisted();
3436
const embeddedSessionId = "embedded-session";
@@ -37,6 +39,11 @@ const seedMessage = { role: "user", content: "seed", timestamp: 1 } as AgentMess
3739
const doneMessage = { role: "assistant", content: "done", timestamp: 2 } as unknown as AgentMessage;
3840
type AfterTurnPromptCacheCall = { runtimeContext?: { promptCache?: Record<string, unknown> } };
3941
type TrajectoryEvent = { type?: string; data?: Record<string, unknown> };
42+
type ToolResultGuardInstallParams = {
43+
midTurnPrecheck?: {
44+
onMidTurnPrecheck?: (request: MidTurnPrecheckRequest) => void;
45+
};
46+
};
4047

4148
function createTestContextEngine(params: Partial<AttemptContextEngine>): AttemptContextEngine {
4249
return {
@@ -770,3 +777,95 @@ describe("runEmbeddedAttempt context engine sessionKey forwarding", () => {
770777
});
771778
});
772779
});
780+
781+
describe("runEmbeddedAttempt context engine mid-turn precheck integration", () => {
782+
const sessionKey = "agent:main:guildchat:channel:midturn-precheck";
783+
const tempPaths: string[] = [];
784+
785+
beforeEach(() => {
786+
resetEmbeddedAttemptHarness();
787+
clearMemoryPluginState();
788+
});
789+
790+
afterEach(async () => {
791+
await cleanupTempPaths(tempPaths);
792+
clearMemoryPluginState();
793+
vi.restoreAllMocks();
794+
});
795+
796+
it("keeps mid-turn precheck out of the context-engine-owned compaction hook", async () => {
797+
await createContextEngineAttemptRunner({
798+
contextEngine: {
799+
...createContextEngineBootstrapAndAssemble(),
800+
info: { ownsCompaction: true },
801+
},
802+
sessionKey,
803+
tempPaths,
804+
attemptOverrides: {
805+
config: {
806+
agents: {
807+
defaults: {
808+
compaction: {
809+
mode: "safeguard",
810+
midTurnPrecheck: { enabled: true },
811+
},
812+
},
813+
},
814+
} as OpenClawConfig,
815+
},
816+
});
817+
818+
expect(hoisted.installContextEngineLoopHookMock).toHaveBeenCalledWith(
819+
expect.not.objectContaining({ midTurnPrecheck: expect.anything() }),
820+
);
821+
});
822+
823+
it("recovers when Pi persists the mid-turn precheck as an assistant error", async () => {
824+
hoisted.installToolResultContextGuardMock.mockImplementation((...args: unknown[]) => {
825+
const params = args[0] as ToolResultGuardInstallParams;
826+
params.midTurnPrecheck?.onMidTurnPrecheck?.({
827+
route: "compact_only",
828+
estimatedPromptTokens: 9000,
829+
promptBudgetBeforeReserve: 7000,
830+
overflowTokens: 2000,
831+
toolResultReducibleChars: 0,
832+
effectiveReserveTokens: 1000,
833+
});
834+
return () => {};
835+
});
836+
837+
const syntheticPiError = {
838+
role: "assistant",
839+
content: [{ type: "text", text: "" }],
840+
stopReason: "error",
841+
errorMessage: "Context overflow: prompt too large for the model (mid-turn precheck).",
842+
timestamp: 3,
843+
} as unknown as AgentMessage;
844+
845+
const result = await createContextEngineAttemptRunner({
846+
contextEngine: createContextEngineBootstrapAndAssemble(),
847+
sessionKey,
848+
tempPaths,
849+
attemptOverrides: {
850+
config: {
851+
agents: {
852+
defaults: {
853+
compaction: {
854+
mode: "safeguard",
855+
midTurnPrecheck: { enabled: true },
856+
},
857+
},
858+
},
859+
} as OpenClawConfig,
860+
},
861+
sessionMessages: [seedMessage],
862+
sessionPrompt: async (session) => {
863+
session.messages = [...session.messages, syntheticPiError];
864+
},
865+
});
866+
867+
expect(result.promptErrorSource).toBe("precheck");
868+
expect(result.preflightRecovery).toEqual({ route: "compact_only" });
869+
expect(result.messagesSnapshot).toEqual([seedMessage]);
870+
});
871+
});

‎src/agents/pi-embedded-runner/run/attempt.spawn-workspace.test-support.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ type AttemptSpawnWorkspaceHoisted = {
6363
subscribeEmbeddedPiSessionMock: Mock<SubscribeEmbeddedPiSessionFn>;
6464
acquireSessionWriteLockMock: Mock<AcquireSessionWriteLockFn>;
6565
installToolResultContextGuardMock: UnknownMock;
66+
installContextEngineLoopHookMock: UnknownMock;
6667
flushPendingToolResultsAfterIdleMock: AsyncUnknownMock;
6768
releaseWsSessionMock: UnknownMock;
6869
resolveBootstrapContextForRunMock: Mock<() => Promise<BootstrapContext>>;
@@ -117,6 +118,7 @@ const hoisted = vi.hoisted((): AttemptSpawnWorkspaceHoisted => {
117118
const ensureGlobalUndiciStreamTimeoutsMock = vi.fn();
118119
const buildEmbeddedMessageActionDiscoveryInputMock = vi.fn((params: unknown) => params);
119120
const installToolResultContextGuardMock = vi.fn(() => () => {});
121+
const installContextEngineLoopHookMock = vi.fn(() => () => {});
120122
const flushPendingToolResultsAfterIdleMock = vi.fn(async () => {});
121123
const releaseWsSessionMock = vi.fn(() => {});
122124
const subscribeEmbeddedPiSessionMock = vi.fn<SubscribeEmbeddedPiSessionFn>(() =>
@@ -166,6 +168,7 @@ const hoisted = vi.hoisted((): AttemptSpawnWorkspaceHoisted => {
166168
subscribeEmbeddedPiSessionMock,
167169
acquireSessionWriteLockMock,
168170
installToolResultContextGuardMock,
171+
installContextEngineLoopHookMock,
169172
flushPendingToolResultsAfterIdleMock,
170173
releaseWsSessionMock,
171174
resolveBootstrapContextForRunMock,
@@ -218,7 +221,7 @@ vi.mock("../../sandbox.js", () => ({
218221
}));
219222

220223
vi.mock("../../session-tool-result-guard-wrapper.js", () => ({
221-
guardSessionManager: () => hoisted.sessionManager,
224+
guardSessionManager: (sessionManager: unknown) => sessionManager,
222225
}));
223226

224227
vi.mock("../../pi-embedded-subscribe.js", () => ({
@@ -355,6 +358,8 @@ vi.mock("../tool-result-context-guard.js", async () => {
355358
`[... ${Math.max(1, Math.floor(truncatedChars))} more characters truncated]`,
356359
installToolResultContextGuard: (...args: unknown[]) =>
357360
(hoisted.installToolResultContextGuardMock as (...args: unknown[]) => unknown)(...args),
361+
installContextEngineLoopHook: (...args: unknown[]) =>
362+
(hoisted.installContextEngineLoopHookMock as (...args: unknown[]) => unknown)(...args),
358363
};
359364
});
360365

@@ -750,6 +755,7 @@ export function resetEmbeddedAttemptHarness(
750755
release: async () => {},
751756
});
752757
hoisted.installToolResultContextGuardMock.mockReset().mockReturnValue(() => {});
758+
hoisted.installContextEngineLoopHookMock.mockReset().mockReturnValue(() => {});
753759
hoisted.flushPendingToolResultsAfterIdleMock.mockReset().mockResolvedValue(undefined);
754760
hoisted.releaseWsSessionMock.mockReset().mockReturnValue(undefined);
755761
hoisted.resolveBootstrapContextForRunMock.mockReset().mockResolvedValue({

0 commit comments

Comments
 (0)