Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): keep the context budget reminder out of the prefix

vastsab419535b0e74
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 244e866e7..89fe44b1d 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -623,12 +623,17 @@ and testable.
**Model-facing surface.** `new_context` takes no parameters and starts a new
context window at the next turn boundary; it never clears or resets environment
-state. Two budget reminders are appended to the current turn's system prompt,
-each at most once per checkpoint window and reset when a checkpoint is
+state. Two budget reminders are appended to the tail of the current turn's
+request, each at most once per checkpoint window and reset when a checkpoint is
installed: one when the remaining budget falls to
`clamp(hardLimit * 0.15, 8k, 32k)`, asking the model to start closing out, and
one at 2,000 tokens remaining, telling it to write down whatever must survive.
-Neither reminder is persisted or shown in the transcript.
+A reminder never rewrites the request prefix (issue #2458): where the model
+keeps mid-conversation system messages in place it is a `context_budget` system
+section that expires at the next checkpoint; elsewhere, because pi-ai folds
+every system update into the leading system message, it is a request-only user
+message that is neither persisted nor carried into the next run. Neither
+reminder is shown in the transcript.
The hard boundary is the model context window minus request headroom. Automatic
compaction starts at 90% of `hardLimit`; this deterministic margin is not
diff --git a/docs/spec/06-delivery/e2e/providers-and-models.md b/docs/spec/06-delivery/e2e/providers-and-models.md
index 1a9b76dfb..b28a52255 100644
--- a/docs/spec/06-delivery/e2e/providers-and-models.md
+++ b/docs/spec/06-delivery/e2e/providers-and-models.md
@@ -1145,7 +1145,11 @@ with only Host API controlled. Running-turn configuration remains queued.
the full transcript and carries the existing summary forward instead of
reporting that there is no new context to compact.
- The budget reminders appear at most once each per checkpoint window, never
- in the transcript, and never in a persisted system prompt.
+ in the transcript, and never in a persisted system prompt. On a model
+ without mid-conversation system messages (for example a local OpenAI
+ compatible endpoint) the leading system message of the request that carries
+ a reminder is byte-identical to the previous request's, so the provider's
+ prefix cache stays warm.
- Idle `/compact` succeeds and shows its own informational toast on top of the
compaction warning, because the user asked for it. Compaction failures
surface once through `CONTEXT_COMPACTION_FAILED` without duplicate error
diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.ts
index 308ab3f56..429fd82f4 100644
--- a/packages/agent-runtime/src/output-cap.ts
+++ b/packages/agent-runtime/src/output-cap.ts
@@ -365,12 +365,23 @@ export function requestTranscript(
model: Pick<Model<Api>, "compat">,
context: TranscriptContext,
): TranscriptContext {
+ return resolveTranscript(context, supportsMidConversationSystemMessages(model));
+}
+
+/**
+ * Whether the adapter keeps later system messages in place. Without it pi-ai
+ * folds every system update into the leading system message, so a system
+ * section added mid-run rewrites the request prefix.
+ */
+export function supportsMidConversationSystemMessages(
+ model: Pick<Model<Api>, "compat">,
+): boolean {
const compat = model.compat;
- const midConversation =
+ return (
compat !== undefined &&
"supportsMidConvoSystemMessages" in compat &&
- compat.supportsMidConvoSystemMessages === true;
- return resolveTranscript(context, midConversation);
+ compat.supportsMidConvoSystemMessages === true
+ );
}
/**
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index c5223c2e5..5e4b24ab5 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -8,6 +8,7 @@ import {
createAssistantMessageEventStream,
getCurrentTools,
getCurrentSystemMessage,
+ normalizeContext,
toToolDeclaration,
type AssistantMessage,
} from "@earendil-works/pi-ai";
@@ -28,7 +29,7 @@ import {
type RuntimeMatchConfig,
type RuntimeProviderConfig,
} from "./runtime.js";
-import { estimateOutputCapInputTokens } from "./output-cap.js";
+import { estimateOutputCapInputTokens, requestTranscript } from "./output-cap.js";
import { COMPACTION_SUMMARY_MAX_RETRIES } from "./compaction-summary-input.js";
import { loadInstructionChain, type ProjectInstructions } from "./project-instructions.js";
@@ -7888,6 +7889,48 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
await runtime.dispose();
});
+ it("keeps the context budget reminder out of the collapsed request prefix", async () => {
+ const runtime = createRuntime();
+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue({
+ tokens: 195_000,
+ hardLimit: 224_000,
+ requestHeadroom: 32_000,
+ });
+ const model = (runtime as any).model;
+ const before = requestTranscript(model, normalizeContext({ messages: [...(runtime as any).agent.state.messages] }));
+
+ const reminded = await (runtime as any).prepareNextTurn(nextTurn);
+ const after = requestTranscript(model, normalizeContext({ messages: reminded.context.messages }));
+
+ // Issue #2458: the leading system message is the cached prefix; the
+ // reminder may only grow the tail.
+ expect(after.messages[0]).toEqual(before.messages[0]);
+ expect(JSON.stringify(after.messages[0])).not.toContain("<context_budget>");
+ expect(JSON.stringify(after.messages.at(-1))).toContain("<context_budget>");
+ await runtime.dispose();
+ });
+
+ it("keeps the context budget reminder as a system section where mid-run system messages stay in place", async () => {
+ const runtime = createRuntime();
+ (runtime as any).model = { ...(runtime as any).model, compat: { supportsMidConvoSystemMessages: true } };
+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue({
+ tokens: 195_000,
+ hardLimit: 224_000,
+ requestHeadroom: 32_000,
+ });
+
+ const reminded = await (runtime as any).prepareNextTurn(nextTurn);
+
+ expect(reminded.context.messages.at(-1)).toMatchObject({
+ role: "system",
+ content: "",
+ sections: { context_budget: expect.stringContaining("<context_budget>") },
+ });
+ expect(getCurrentSystemMessage(reminded.context.messages)?.sections?.context_budget).toContain("new_context");
+ expect(reminded.context.systemPrompt).not.toContain("<context_budget>");
+ await runtime.dispose();
+ });
+
it("compacts a long tool loop at the soft threshold after a reminder", async () => {
const onEvent = vi.fn();
const runtime = createRuntime({ onEvent });
@@ -7921,20 +7964,20 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
// 29k left is inside the first reminder tier but still below the 90%
// compaction trigger, so the model can close out before host compaction.
- expect(below.context.systemPrompt).toContain("<context_budget>");
- expect(below.context.systemPrompt).toContain("new_context");
+ // The default model folds system updates into the leading system message,
+ // so the reminder rides at the tail as a request-only user message.
+ expect(below.context.systemPrompt).not.toContain("<context_budget>");
expect(below.context.messages.at(-1)).toMatchObject({
- role: "system",
- content: "",
- sections: { context_budget: expect.stringContaining("<context_budget>") },
+ role: "user",
+ content: [{ type: "text", text: expect.stringContaining("<context_budget>") }],
});
- expect(getCurrentSystemMessage(below.context.messages)?.sections?.context_budget).toContain("new_context");
- expect(stillBelow.context.systemPrompt).not.toContain("<context_budget>");
- // The legacy prompt baseline stays unchanged; the returned transcript
- // carries the reminder section through the normal persistence path.
+ expect(JSON.stringify(below.context.messages.at(-1))).toContain("new_context");
+ expect(stillBelow.context.messages.at(-1)?.role).not.toBe("user");
+ // The prompt baseline stays unchanged and nothing lands in agent state.
expect((runtime as any).agent.state.systemPrompt).not.toContain(
"<context_budget>",
);
+ expect(JSON.stringify((runtime as any).agent.state.messages)).not.toContain("<context_budget>");
expect(runCompaction).not.toHaveBeenCalled();
vi.spyOn(runtime as any, "contextBudget")
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 86fb82f48..bf90b1b05 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -235,6 +235,7 @@ import {
effectiveModelContextWindow,
estimateOutputCapInputTokens,
requestTranscript,
+ supportsMidConversationSystemMessages,
truncateTextWithinOutputCap,
} from "./output-cap.js";
import {
@@ -7494,19 +7495,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const remaining = Math.max(0, budget.hardLimit - budget.tokens);
const reminder = this.claimContextBudgetReminder(remaining, budget);
if (!reminder) return context;
- const legacyContext = context as AgentContext & { systemPrompt?: string };
- const systemPrompt =
- typeof legacyContext.systemPrompt === "string"
- ? `${legacyContext.systemPrompt}\n\n${reminder}`
- : undefined;
- return {
- ...context,
- ...(systemPrompt ? { systemPrompt } : {}),
- messages: [
- ...context.messages,
- { role: "system", content: "", sections: { [CONTEXT_BUDGET_SECTION]: reminder }, timestamp: Date.now() },
- ],
- } as AgentContext;
+ // The reminder changes on every claim, so it must never reach the request
+ // prefix (issue #2458). A system section stays at the tail only where the
+ // adapter keeps mid-conversation system messages; elsewhere pi-ai folds it
+ // into the leading system message and invalidates the whole prefix cache.
+ // There it rides as a request-only user message appended at the tail,
+ // like steering, and is neither persisted nor carried into the next run.
+ const message: AgentMessage = supportsMidConversationSystemMessages(this.model)
+ ? { role: "system", content: "", sections: { [CONTEXT_BUDGET_SECTION]: reminder }, timestamp: Date.now() }
+ : { role: "user", content: [{ type: "text", text: reminder }], timestamp: Date.now() };
+ return { ...context, messages: [...context.messages, message] };
}
private claimContextBudgetReminder(