Skip to content

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

fix(agent-runtime): enforce published context safety ceiling

vastsaf15898806abe
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index c39871745..ff8a42f42 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -462,6 +462,14 @@ boundary falls, not what survives it. The active-user retention limit is 20,000
tokens, capped at half the hard budget so retention alone cannot fill a small
window and leave the summary no room. None of these values are configurable.
+The provider request layer also caps the concrete output budget before every
+parent, subagent, and one-shot request. It estimates the serialized input with
+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.
+
The incoming user prompt participates in budgeting before the first provider
request. The automatic summary request retries transient provider failures
under a bounded pi-ai retry policy (3 retries, 2s/4s/8s backoff, cancelled by
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index b1cac92e6..ab9c3c114 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -334,6 +334,12 @@ models still use the conservative 128k generic window and are never promoted fro
an ID pattern alone. The marker is optional in the persisted record, so a config
written by an older version stays readable and a downgrade ignores it.
+The configured user value remains persisted and visible in Advanced settings, but
+provider safety does not trust an enlarged override beyond a known published
+window. Outbound output caps, automatic compaction, and overflow classification
+use the smaller of the configured and published windows; a smaller user value
+continues to narrow the runtime budget.
+
### 9.2 Conversation Composer scope
The conversation Composer is a configured-model picker, not a raw discovery
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 29d07c29e..d57b4d7cd 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13854,3 +13854,20 @@ the latest destination. These assertions measure work counts, not device FPS.
- **Automation:** `pnpm test:e2e:dialog-overflow`; source/contract dialog suites
supplement, but do not replace, real Chromium geometry and pointer checks.
- **Status:** Implemented. Native Windows evidence; macOS/Linux not qualified.
+
+### E2E-OUTPUT-CAP-716: Keep model requests inside the published context window
+
+- **Preconditions:** A deterministic provider fixture exposes a published context
+ 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"`.
+- **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.
+- **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
diff --git a/packages/agent-runtime/src/model-capabilities.test.ts b/packages/agent-runtime/src/model-capabilities.test.ts
index 12b3a92cd..54cb30bf3 100644
--- a/packages/agent-runtime/src/model-capabilities.test.ts
+++ b/packages/agent-runtime/src/model-capabilities.test.ts
@@ -116,6 +116,14 @@ describe("main-supplied model capabilities", () => {
]);
expect(configured.thinkingLevelMap).toMatchObject({ max: "max" });
+ const enlarged = modelConfigWithBinding(knownModel(), {
+ contextWindow: 256_000,
+ maxTokens: 8_192,
+ thinkingLevels: [],
+ });
+ expect(enlarged.contextWindow).toBe(256_000);
+ expect(enlarged.catalogContextWindow).toBe(128_000);
+
const unknown = modelConfigWithBinding(genericModelConfig("unknown"), {
contextWindow: 16_000,
maxTokens: 2_000,
diff --git a/packages/agent-runtime/src/model-capabilities.ts b/packages/agent-runtime/src/model-capabilities.ts
index 89b835f4d..e7a04c7a5 100644
--- a/packages/agent-runtime/src/model-capabilities.ts
+++ b/packages/agent-runtime/src/model-capabilities.ts
@@ -101,8 +101,14 @@ export function modelConfigWithBinding(
const contextWindow =
effectiveContextWindow(model.contextWindow, binding.contextWindow) ??
model.contextWindow;
+ const catalogContextWindow =
+ model.catalogContextWindow ??
+ (model.source === "models.dev" && model.contextWindow > 0
+ ? model.contextWindow
+ : undefined);
return {
...model,
+ ...(catalogContextWindow !== undefined ? { catalogContextWindow } : {}),
contextWindow,
limit: {
...(model.limit ?? {}),
diff --git a/packages/agent-runtime/src/one-shot-complete.ts b/packages/agent-runtime/src/one-shot-complete.ts
index 1a173d06b..40b564cd6 100644
--- a/packages/agent-runtime/src/one-shot-complete.ts
+++ b/packages/agent-runtime/src/one-shot-complete.ts
@@ -13,6 +13,7 @@ import type {
} from "@earendil-works/pi-ai";
import type { MessageUsage, ThinkingLevel } from "@pi-desktop/shared";
import { classifyAgentError } from "./agent-errors.js";
+import { clampOutputToContext } from "./output-cap.js";
import { assistantContent, usageFromPi } from "./agent-messages.js";
import {
buildProviderModel,
@@ -89,6 +90,7 @@ export async function completeOneShot(
const requestOptions: SimpleStreamOptions = withProviderHeaders(
withOpenCodeSessionHeaders(
{
+ maxTokens: clampOutputToContext(model, context, undefined),
...(options.signal ? { signal: options.signal } : {}),
maxRetries: 0,
...(thinkingLevel !== "off" ? { reasoning: thinkingLevel } : {}),
diff --git a/packages/agent-runtime/src/output-cap.test.ts b/packages/agent-runtime/src/output-cap.test.ts
index 66c6d80a3..c3215e96d 100644
--- a/packages/agent-runtime/src/output-cap.test.ts
+++ b/packages/agent-runtime/src/output-cap.test.ts
@@ -123,6 +123,15 @@ describe("clampOutputToContext", () => {
expect(clampOutputToContext(model, BASE_CONTEXT, 8888)).toBe(8888);
});
+ it("uses the published window as a safety ceiling", () => {
+ const model = {
+ contextWindow: 262_144,
+ catalogContextWindow: 128_000,
+ maxTokens: 200_000,
+ };
+ expect(clampOutputToContext(model, BASE_CONTEXT, 200_000)).toBe(123_904);
+ });
+
it("never exceeds the requested budget", () => {
const context: OutputCapContext = {
messages: [{ role: "user", content: "a".repeat(100) }],
diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.ts
index 1aa201a41..6b10f673f 100644
--- a/packages/agent-runtime/src/output-cap.ts
+++ b/packages/agent-runtime/src/output-cap.ts
@@ -28,9 +28,24 @@ export type OutputCapContext = {
/** Structural view of the active model. */
export type OutputCapModel = {
contextWindow: number;
+ /** Published limit, when a user override may have enlarged contextWindow. */
+ catalogContextWindow?: number;
maxTokens: number;
};
+function positiveWindow(value: number | undefined): number | undefined {
+ if (!Number.isFinite(value) || (value ?? 0) <= 0) return undefined;
+ return Math.max(1, Math.round(value!));
+}
+
+/** Use the published window as a hard safety ceiling for configured values. */
+export function effectiveModelContextWindow(model: OutputCapModel): number {
+ const configured = positiveWindow(model.contextWindow);
+ const catalog = positiveWindow(model.catalogContextWindow);
+ if (configured === undefined) return catalog ?? 0;
+ return catalog === undefined ? configured : Math.min(configured, catalog);
+}
+
/** Fallback reserve when the window is too small to afford the ratio. */
const OUTPUT_SAFETY_FLOOR_TOKENS = 4096;
/** Window-proportional reserve; at 262k this is ~4k, at 1M ~10k. */
@@ -146,14 +161,14 @@ export function clampOutputToContext(
context: OutputCapContext,
requestedMaxTokens: number | undefined,
): number {
- const contextWindow = Math.max(1, Math.round(model.contextWindow || 0));
+ const contextWindow = effectiveModelContextWindow(model);
const desired = Math.max(
1,
Math.round(requestedMaxTokens ?? model.maxTokens),
);
// Unknown window: there is nothing context-based to clamp against; keep the
// configured budget (mirrors pi-ai's `contextWindow <= 0` behavior).
- if (model.contextWindow <= 0) return desired;
+ if (contextWindow <= 0) return desired;
const inputTokens = estimateOutputCapInputTokens(context);
const reserve = Math.max(
OUTPUT_SAFETY_FLOOR_TOKENS,
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 63c286968..11550e123 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -144,7 +144,10 @@ import {
seedDelegateMessages,
type DelegationChain,
} from "./delegation-history.js";
-import { clampOutputToContext } from "./output-cap.js";
+import {
+ clampOutputToContext,
+ effectiveModelContextWindow,
+} from "./output-cap.js";
import {
composeSubagentSystemPrompt,
SubagentRun,
@@ -5659,7 +5662,7 @@ Delegation rules:
private contextBudget(messages: AgentMessage[]): ContextBudget {
const contextWindow = Math.max(
1,
- Math.round(this.model.contextWindow || DEFAULT_CONTEXT_WINDOW),
+ effectiveModelContextWindow(this.model) || DEFAULT_CONTEXT_WINDOW,
);
const modelOutputBudget = Math.min(
Math.max(1, Math.round(this.model.maxTokens || DEFAULT_MAX_TOKENS)),
@@ -6813,7 +6816,7 @@ Delegation rules:
| undefined;
const overflow = isContextOverflow(
event.message as AssistantMessage,
- this.model.contextWindow || DEFAULT_CONTEXT_WINDOW,
+ effectiveModelContextWindow(this.model) || DEFAULT_CONTEXT_WINDOW,
);
const failed = stopReason === "error" || overflow;
const aborted = stopReason === "aborted";
diff --git a/packages/agent-runtime/src/thinking-level.ts b/packages/agent-runtime/src/thinking-level.ts
index d9d77a12d..32cb0625e 100644
--- a/packages/agent-runtime/src/thinking-level.ts
+++ b/packages/agent-runtime/src/thinking-level.ts
@@ -54,6 +54,8 @@ export type ModelConfig = {
catalogProvider?: ModelProviderMetadata;
/** Adapter-facing subset; models.dev modalities remain complete above. */
input: Array<"text" | "image">;
+ /** Published context window retained as a safety ceiling for user overrides. */
+ catalogContextWindow?: number;
contextWindow: number;
maxTokens: number;
/**