Skip to content

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

fix(runtime): size the output cap from the folded request transcript

spacker-343c82490ce7e6f
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 34f3a0a7e..a5d4dff28 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -577,7 +577,13 @@ the pi-ai chars/4 baseline plus a CJK correction, then reserves the larger of
4,096 tokens or 1% of the effective window. The effective window is the smaller
of the configured value and the published catalog window when both are known;
this prevents an oversized user override from bypassing compaction and output
-protection. Unknown windows preserve the configured output budget.
+protection. Unknown windows preserve the configured output budget. The estimate
+measures the transcript the adapter sends: unless the bound model declares
+mid-conversation system support, later system-transcript updates are folded
+into one leading message carrying the current instructions and tools, and the
+parent and subagent paths hand that folded transcript to pi-ai as well, so its
+own `streamSimple` clamp agrees. Superseded instruction snapshots are never
+charged against the output budget.
The incoming user prompt participates in budgeting before the first provider
request. The automatic summary request retries transient provider failures
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index c6989e987..56c8fcc82 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -17416,16 +17416,24 @@ the latest destination. These assertions measure work counts, not device FPS.
window, supports parent and subagent requests, and records request payloads.
- **Steps:** Configure a user context override larger than the published window;
send a CJK-heavy parent prompt, invoke a subagent, and run a one-shot
- completion. Repeat the parent request with `thinkingLevel: "omit"`.
+ completion. Repeat the parent request with `thinkingLevel: "omit"`. Restore a
+ session whose transcript holds many large instruction updates on a Responses
+ gateway without mid-conversation system support, then continue it and run a
+ subagent whose updates follow its last usage report.
- **Expected:** Each request carries a concrete output budget no larger than the
remaining published window after input estimation and safety reserve. The
runtime compacts against the published safety ceiling, and no request is sent
with `input + output` beyond that ceiling. Small ASCII requests retain the
- configured budget when it fits.
+ configured budget when it fits. The restored session and the subagent send one
+ folded instruction message and keep the configured output budget instead of
+ the provider's minimum.
- **Specs linked:** `03-runtime/02-agent-runtime.md`,
`03-runtime/13-model-catalog-and-selection.md`
- **Acceptance:** F (runtime provider requests), C (chat and stream)
-- **Status:** Unit-covered; deterministic provider fixture pending
+- **Automation:** `packages/agent-runtime/src/output-cap-request.test.ts` drives
+ the restored-session and subagent steps through a loopback Responses gateway.
+- **Status:** Unit-covered; folded-instruction steps covered by a loopback
+ gateway; remaining deterministic provider fixture pending
### E2E-PROVIDER-certificate-trust-and-terminal-errors
diff --git a/packages/agent-runtime/src/output-cap-request.test.ts b/packages/agent-runtime/src/output-cap-request.test.ts
new file mode 100644
index 000000000..f8b41a098
--- /dev/null
+++ b/packages/agent-runtime/src/output-cap-request.test.ts
@@ -0,0 +1,171 @@
+import { createServer, type ServerResponse } from "node:http";
+import { afterEach, describe, expect, it } from "vitest";
+import { normalizeContext, type Message } from "@earendil-works/pi-ai";
+import type { UiMessage } from "@pi-desktop/shared";
+import { DesktopAgentRuntime } from "./runtime.js";
+import type { RuntimeProviderConfig } from "./provider-binding.js";
+import { subagentModelBinding } from "./subagent-model-binding.js";
+
+/**
+ * A long session rewrites a large instruction section many times. A gateway
+ * without mid-conversation system support receives only the current
+ * instructions, so the output budget must be measured against that request,
+ * not against every superseded snapshot kept in the transcript.
+ */
+
+const WINDOW = 128_000;
+const OUTPUT = 8_192;
+const UPDATES = 20;
+/** Each snapshot alone is ~6k tokens; all of them together exceed the window. */
+const SECTION_CHARS = 25_000;
+
+type WireItem = { role?: string; type?: string; content?: unknown };
+type WireRequest = { max_output_tokens?: number; input: WireItem[] };
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+
+function section(index: number): string {
+ return `update-${index}:`.padEnd(SECTION_CHARS, "x");
+}
+
+function respond(res: ServerResponse): void {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const send = (data: { type: string; [key: string]: unknown }) =>
+ res.write(`event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`);
+ const item = {
+ id: "msg_fixture", type: "message", role: "assistant", status: "completed",
+ content: [{ type: "output_text", text: "Continuing.", annotations: [] }],
+ };
+ send({ type: "response.created", response: { id: "resp_fixture" } });
+ send({ type: "response.output_item.added", output_index: 0, item: { ...item, content: [], status: "in_progress" } });
+ send({ type: "response.output_text.delta", output_index: 0, content_index: 0, delta: "Continuing." });
+ send({ type: "response.output_item.done", output_index: 0, item });
+ send({
+ type: "response.completed",
+ response: {
+ id: "resp_fixture", status: "completed", output: [item],
+ usage: {
+ input_tokens: 10, output_tokens: 2, total_tokens: 12,
+ input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 },
+ },
+ },
+ });
+ res.end();
+}
+
+async function gateway(): Promise<{ baseUrl: string; requests: WireRequest[] }> {
+ const requests: WireRequest[] = [];
+ const server = createServer(async (req, res) => {
+ let raw = "";
+ for await (const part of req) raw += part;
+ requests.push(JSON.parse(raw) as WireRequest);
+ respond(res);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ cleanups.push(async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("fixture address missing");
+ return { baseUrl: `http://127.0.0.1:${address.port}/v1`, requests };
+}
+
+/** A user-configured Responses gateway: mid-conversation system support is unverified. */
+function gatewayProvider(baseUrl: string): RuntimeProviderConfig {
+ return {
+ id: "gateway", name: "Gateway", baseUrl, modelId: "gateway-model", apiKey: "fixture-not-real",
+ apiStyle: "responses", supportsReasoning: false, supportedThinkingLevels: ["off"],
+ modelConfig: {
+ source: "generic", name: "Gateway model", baseUrl, reasoning: false, input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: WINDOW, maxTokens: OUTPUT,
+ },
+ };
+}
+
+function instructionItems(request: WireRequest): WireItem[] {
+ return request.input.filter((item) => item.role === "system" || item.role === "developer");
+}
+
+describe("output budget with superseded instruction snapshots", () => {
+ it("keeps the configured output budget when a restored long session continues", async () => {
+ const { baseUrl, requests } = await gateway();
+ const createdAt = "2026-10-20T10:00:00.000Z";
+ const history: UiMessage[] = [];
+ let previous: string | undefined;
+ for (let index = 0; index < UPDATES; index++) {
+ const update = { role: "system", content: "", sections: { context: section(index) }, timestamp: 1_000 + index };
+ history.push({
+ id: `update-${index}`, role: "system", content: "", createdAt,
+ modelSystem: {
+ version: 1, messageJson: JSON.stringify(update),
+ ...(previous ? { afterMessageId: previous } : {}),
+ },
+ });
+ history.push({ id: `user-${index}`, role: "user", content: `Step ${index}`, createdAt, status: "complete" });
+ history.push({
+ id: `assistant-${index}`, role: "assistant", content: `Done ${index}.`, createdAt, status: "complete",
+ // The provider measured the folded request, not the unfolded history.
+ usage: { inputTokens: 12_000, outputTokens: 100, totalTokens: 12_100 },
+ });
+ previous = `assistant-${index}`;
+ }
+ const runtime = new DesktopAgentRuntime({
+ sessionId: "long-session", mode: "agent", provider: gatewayProvider(baseUrl), history, thinkingLevel: "off",
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ host: {
+ call: async <T>(method: string): Promise<T> => {
+ if (method === "session.appendMessage") return undefined as T;
+ throw new Error(`Unexpected host method: ${method}`);
+ },
+ onNotification: () => () => {},
+ },
+ onEvent: () => {},
+ });
+ cleanups.push(async () => { await runtime.dispose(); });
+
+ await runtime.prompt("Continue");
+
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ expect(request.max_output_tokens).toBe(OUTPUT);
+ expect(instructionItems(request)).toHaveLength(1);
+ expect(JSON.stringify(request.input)).not.toContain("update-0:");
+ });
+
+ it("keeps a delegate's output budget when instruction updates follow its usage anchor", async () => {
+ const { baseUrl, requests } = await gateway();
+ const binding = subagentModelBinding(
+ { provider: gatewayProvider(baseUrl), thinkingLevel: "off", sessionId: "long-session" },
+ { claim: () => undefined },
+ );
+ const messages: Message[] = [
+ { role: "system", content: "Delegate instructions.", timestamp: 1 },
+ { role: "user", content: "Review the change.", timestamp: 2 },
+ {
+ role: "assistant", content: [{ type: "text", text: "Reviewing." }],
+ api: "openai-responses", provider: binding.model.provider, model: binding.model.id,
+ usage: {
+ input: 12_000, output: 100, cacheRead: 0, cacheWrite: 0, totalTokens: 12_100,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop", timestamp: 3,
+ },
+ ...Array.from({ length: UPDATES }, (_, index): Message => ({
+ role: "system", content: "", sections: { context: section(index) }, timestamp: 4 + index,
+ })),
+ { role: "user", content: "Continue.", timestamp: 100 },
+ ];
+
+ const result = await binding.streamFn(binding.model, normalizeContext({ messages }), {}).result();
+
+ expect(result.stopReason).toBe("stop");
+ expect(requests).toHaveLength(1);
+ expect(requests[0].max_output_tokens).toBe(OUTPUT);
+ expect(instructionItems(requests[0])).toHaveLength(1);
+ });
+});
diff --git a/packages/agent-runtime/src/output-cap.test.ts b/packages/agent-runtime/src/output-cap.test.ts
index 234a118a5..c36e3726e 100644
--- a/packages/agent-runtime/src/output-cap.test.ts
+++ b/packages/agent-runtime/src/output-cap.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
+import { getCurrentSystemPrompt, normalizeContext, type Message } from "@earendil-works/pi-ai";
import {
clampOutputToContext,
estimateOutputCapInputTokens,
+ requestTranscript,
type OutputCapContext,
} from "./output-cap.js";
@@ -353,6 +355,33 @@ describe("clampOutputToContext", () => {
});
});
+describe("requestTranscript", () => {
+ const updates = (count: number): Message[] => [
+ { role: "system", content: "Base instructions.", timestamp: 1 },
+ ...Array.from({ length: count }, (_, index): Message => ({
+ role: "system", content: "", sections: { context: `${index}`.padEnd(40_000, "x") }, timestamp: 2 + index,
+ })),
+ { role: "user", content: "Continue.", timestamp: 100 },
+ ];
+ const model = { contextWindow: 128_000, maxTokens: 8_192, compat: { supportsMidConvoSystemMessages: false } };
+
+ it("charges only the current instructions when the adapter folds system updates", () => {
+ const context = normalizeContext({ messages: updates(16) });
+ const request = requestTranscript(model, context);
+ expect(request.messages.filter((message) => message.role === "system")).toHaveLength(1);
+ expect(getCurrentSystemPrompt(request.messages)).toBe(getCurrentSystemPrompt(context.messages));
+ expect(clampOutputToContext(model, context, 8_192)).toBe(1);
+ expect(clampOutputToContext(model, request, 8_192)).toBe(8_192);
+ });
+
+ it("keeps every update for a model that receives them mid-conversation", () => {
+ const midConversation = { ...model, compat: { supportsMidConvoSystemMessages: true } };
+ const context = normalizeContext({ messages: updates(16) });
+ expect(requestTranscript(midConversation, context)).toBe(context);
+ expect(clampOutputToContext(midConversation, requestTranscript(midConversation, context), 8_192)).toBe(1);
+ });
+});
+
// Transcript-only Pi requests have no legacy systemPrompt/tools fields.
it("counts instruction sections and tool declarations in transcript-only requests", () => {
const base = { messages: [{ role: "system", content: "" }] };
diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.ts
index 728d05858..c3fa25c6a 100644
--- a/packages/agent-runtime/src/output-cap.ts
+++ b/packages/agent-runtime/src/output-cap.ts
@@ -22,9 +22,17 @@
* `web_search_call` from another model) no longer inflates the estimate while
* same-model search history keeps counting. A caller that has no target model
* passes none and keeps the conservative block-protocol estimate.
+ *
+ * Instruction history is charged the way the adapter sends it as well: see
+ * `requestTranscript`.
*/
-import type { Api } from "@earendil-works/pi-ai";
+import {
+ resolveTranscript,
+ type Api,
+ type Model,
+ type TranscriptContext,
+} from "@earendil-works/pi-ai";
import {
hostedSearchReplayProjection,
type HostedSearchReplayOptions,
@@ -251,6 +259,27 @@ export function estimateOutputCapInputTokens(
return baseline + Math.ceil(cjkChars * 0.75);
}
+/**
+ * The transcript the adapter puts on the wire. Unless the model declares
+ * mid-conversation system support, every adapter folds the later system
+ * messages into one leading message holding the current instructions and
+ * tools. Estimating the unfolded history charges each superseded instruction
+ * snapshot again: a long session with a large instruction section then
+ * starves the output budget to the provider's floor while the request itself
+ * is far from the window.
+ */
+export function requestTranscript(
+ model: Pick<Model<Api>, "compat">,
+ context: TranscriptContext,
+): TranscriptContext {
+ const compat = model.compat;
+ const midConversation =
+ compat !== undefined &&
+ "supportsMidConvoSystemMessages" in compat &&
+ compat.supportsMidConvoSystemMessages === true;
+ return resolveTranscript(context, midConversation);
+}
+
/**
* Cap the effective output budget so `estimatedInput + output` stays inside
* the model's context window, regardless of which adapter branch the caller
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 7249de152..4affe7ed6 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -202,6 +202,7 @@ import {
clampOutputToContext,
effectiveModelContextWindow,
estimateOutputCapInputTokens,
+ requestTranscript,
} from "./output-cap.js";
import {
composeSubagentSystemPrompt,
@@ -2200,6 +2201,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// with pi's own run signal (Stop must keep working): the adapter refuses
// to start an attempt on an aborted signal, and its backoff sleep rejects.
const stallAbort = new AbortController();
+ // Both output clamps, ours and pi-ai's inside `streamSimple`, must see
+ // the instructions the adapter sends, not every superseded snapshot.
+ const requestContext = requestTranscript(m, context);
const attemptOptions: SimpleStreamOptions = {
...hookedOptions,
// Cap the output budget at the pi-desktop layer so the estimate
@@ -2207,7 +2211,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// max_tokens, but the low-level `stream` path used by
// `thinkingLevel: "omit"` would otherwise send it untouched, and
// both consume an estimate that under-counts CJK text (issue B).
- maxTokens: clampOutputToContext(m, context, hookedOptions.maxTokens),
+ maxTokens: clampOutputToContext(m, requestContext, hookedOptions.maxTokens),
signal: AbortSignal.any([
...(hookedOptions.signal ? [hookedOptions.signal] : []),
stallAbort.signal,
@@ -2216,12 +2220,12 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const usageTurnId = this.turnId;
const retryStream = createProviderRetryStream(
m,
- context,
+ requestContext,
attemptOptions,
(retryOptions) => accountModelStream(m, () =>
this.thinkingLevel === "omit"
- ? this.models.stream(omitThinkingModel(m), context, retryOptions)
- : this.models.streamSimple(m, context, retryOptions), {
+ ? this.models.stream(omitThinkingModel(m), requestContext, retryOptions)
+ : this.models.streamSimple(m, requestContext, retryOptions), {
providerId: this.provider.id,
nativeCost: this.provider.modelConfig?.nativeCost,
onUsage: (usage) => this.emit({ type: "usage", usage }, usageTurnId),
diff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.ts
index 183b30ada..3a2955548 100644
--- a/packages/agent-runtime/src/subagent-model-binding.ts
+++ b/packages/agent-runtime/src/subagent-model-binding.ts
@@ -13,7 +13,7 @@ import {
} from "./opencode-session-headers.js";
import { withSessionAffinityOptions } from "./session-affinity.js";
import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";
-import { clampOutputToContext } from "./output-cap.js";
+import { clampOutputToContext, requestTranscript } from "./output-cap.js";
import {
agentThinkingLevel as agentThinkingLevelFor,
omitThinkingModel as withOmittedThinking,
@@ -65,6 +65,7 @@ export function subagentModelBinding(opts: {
retry.headers = undefined;
retry.status = undefined;
retry.failure = undefined;
+ const requestContext = requestTranscript(m, context);
const requestOptions = withProviderHeaders(
withOpenCodeSessionHeaders(
{
@@ -72,7 +73,7 @@ export function subagentModelBinding(opts: {
// Same request-side output cap as the parent runtime: the
// `omit` branch hits pi-ai's low-level `stream` which never
// re-derives max_tokens (issue B).
- maxTokens: clampOutputToContext(m, context, options?.maxTokens),
+ maxTokens: clampOutputToContext(m, requestContext, options?.maxTokens),
maxRetries: 0,
sessionId: opts.sessionId,
fetch: providerRequestFetch(
@@ -111,12 +112,12 @@ export function subagentModelBinding(opts: {
});
return createProviderRetryStream(
m,
- context,
+ requestContext,
sessionOptions,
(retryOptions) => accountModelStream(m, () =>
omitThinking
- ? models.stream(omitThinkingModel, context, retryOptions)
- : models.streamSimple(m, context, retryOptions), {
+ ? models.stream(omitThinkingModel, requestContext, retryOptions)
+ : models.streamSimple(m, requestContext, retryOptions), {
providerId: opts.provider.id,
nativeCost: opts.provider.modelConfig?.nativeCost,
onUsage: opts.onUsage,
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index fa4b4f884..93da4371f 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -147,7 +147,7 @@ describe("SubagentRun event forwarding", () => {
expect(run.agent.state.thinkingLevel).toBe("off");
expect(run.agent.streamFunction.toString()).toContain(
- "models.stream(omitThinkingModel, context, retryOptions)",
+ "models.stream(omitThinkingModel, requestContext, retryOptions)",
);
});
it("deduplicates repeated tool calls before a subagent request", () => {