Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
refactor(agent-runtime): extract the context budget formula
Zihao Peng8327024ffa4f
diff --git a/packages/agent-runtime/src/context-budget.test.ts b/packages/agent-runtime/src/context-budget.test.tsnew file mode 100644index 000000000..582cc47d8--- /dev/null+++ b/packages/agent-runtime/src/context-budget.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it } from "vitest";+import type { AgentMessage } from "@earendil-works/pi-agent-core";+import {+ COMPACTION_MAX_KEEP_RECENT_TOKENS,+ COMPACTION_MIN_KEEP_RECENT_TOKENS,+ COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS,+ contextBudgetFor,+ contextBudgetLimitsFor,+ retainedUserMessageBudget,+} from "./context-budget.js";+import {+ DEFAULT_CONTEXT_WINDOW,+ DEFAULT_MAX_TOKENS,+} from "./provider-binding.js";++describe("contextBudgetFor", () => {+ it("derives the hard limit from provider-request headroom", () => {+ // The numbers the session runtime's own compaction tests assert against.+ expect(contextBudgetFor({ contextWindow: 256_000, maxTokens: 32_000 }, []))+ .toEqual({+ tokens: 0,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 44_800,+ });+ });++ it("clamps the retained tail for a small model context window", () => {+ // A 32K window cannot spare 20% for the tail: the half-budget clamp wins,+ // which lands exactly on the minimum rather than below it.+ expect(contextBudgetLimitsFor({ contextWindow: 32_000, maxTokens: 8_000 }))+ .toEqual({+ hardLimit: 16_000,+ requestHeadroom: 16_000,+ keepRecentTokens: 8_000,+ });+ });++ it("holds the reserve floor on a 64K window", () => {+ // The 25% cap keeps a 64K window's output budget at 16_000, just under the+ // reserve floor, so the floor is what the headroom settles on.+ expect(contextBudgetLimitsFor({ contextWindow: 64_000, maxTokens: 16_000 }))+ .toEqual({+ hardLimit: 47_616,+ requestHeadroom: 16_384,+ keepRecentTokens: 9_523,+ });+ });++ it("falls back to the package defaults when the model reports no window", () => {+ const budget = contextBudgetLimitsFor({});+ const fallback = contextBudgetLimitsFor({+ contextWindow: DEFAULT_CONTEXT_WINDOW,+ maxTokens: DEFAULT_MAX_TOKENS,+ });++ expect(budget).toEqual(fallback);+ expect(budget.hardLimit).toBe(111_616);+ expect(budget.requestHeadroom).toBe(16_384);+ expect(budget.keepRecentTokens).toBe(22_323);+ });++ it("caps the retained tail on a very large window", () => {+ const budget = contextBudgetLimitsFor({+ contextWindow: 1_048_576,+ maxTokens: 64_000,+ });++ expect(budget.hardLimit).toBe(984_576);+ // Without the cap a 1M window would carry ~197K tokens forward.+ expect(budget.keepRecentTokens).toBe(COMPACTION_MAX_KEEP_RECENT_TOKENS);+ });++ it("never lets the retained tail exceed half of the hard limit", () => {+ for (const contextWindow of [+ 1, 100, 4_000, 8_000, 16_000, 32_000, 64_000, 128_000, 200_000, 256_000,+ 1_048_576, 2_000_000,+ ]) {+ const budget = contextBudgetLimitsFor({ contextWindow });++ expect(budget.hardLimit).toBeGreaterThan(0);+ // A one-token window is degenerate: it can reserve nothing and still has+ // to leave a positive limit behind, so headroom may legitimately be zero.+ expect(budget.requestHeadroom).toBeGreaterThanOrEqual(0);+ expect(budget.requestHeadroom).toBeLessThan(contextWindow);+ expect(budget.keepRecentTokens).toBeGreaterThan(0);+ expect(budget.keepRecentTokens).toBeLessThanOrEqual(+ Math.max(1, Math.floor(budget.hardLimit * 0.5)),+ );+ expect(budget.keepRecentTokens).toBeLessThanOrEqual(+ COMPACTION_MAX_KEEP_RECENT_TOKENS,+ );+ // The minimum only applies while half the budget can still cover it.+ if (budget.hardLimit * 0.5 >= COMPACTION_MIN_KEEP_RECENT_TOKENS) {+ expect(budget.keepRecentTokens).toBeGreaterThanOrEqual(+ COMPACTION_MIN_KEEP_RECENT_TOKENS,+ );+ }+ }+ });++ it("counts the estimated tokens of the supplied context", () => {+ const messages: AgentMessage[] = [+ { role: "user", content: "count these tokens", timestamp: 1 },+ ];++ const empty = contextBudgetFor({ contextWindow: 256_000 }, []);+ const filled = contextBudgetFor({ contextWindow: 256_000 }, messages);++ expect(empty.tokens).toBe(0);+ expect(filled.tokens).toBeGreaterThan(0);+ // Only `tokens` depends on the messages; the thresholds are window-derived.+ expect({ ...filled, tokens: 0 }).toEqual(empty);+ });+});++describe("retainedUserMessageBudget", () => {+ it("uses the flat cap when the budget can afford it", () => {+ expect(retainedUserMessageBudget({ hardLimit: 224_000 })).toBe(+ COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS,+ );+ });++ it("clamps against half of the hard limit on a small window", () => {+ expect(retainedUserMessageBudget({ hardLimit: 16_000 })).toBe(8_000);+ expect(retainedUserMessageBudget({ hardLimit: 2_000 })).toBe(1_000);+ });++ it("stays positive when half the budget rounds to zero", () => {+ expect(retainedUserMessageBudget({ hardLimit: 1 })).toBe(1);+ });+});diff --git a/packages/agent-runtime/src/context-budget.ts b/packages/agent-runtime/src/context-budget.tsnew file mode 100644index 000000000..a6703a08f--- /dev/null+++ b/packages/agent-runtime/src/context-budget.ts@@ -0,0 +1,146 @@+/**+ * Context thresholds derived from the active model's window.+ *+ * The session runtime and its subagents must arrive at the same numbers: a+ * child that computed a looser budget than its parent would keep issuing+ * requests the parent already considers unsafe. Both therefore read the+ * formula from here instead of each owning a copy that can drift.+ *+ * Deliberately dependency-light — token estimation is delegated to+ * pi-agent-core and nothing else is imported, so this module stays usable from+ * any runtime context and can never form a cycle with `runtime.ts`.+ */++import {+ estimateContextTokens,+ type AgentMessage,+} from "@earendil-works/pi-agent-core";+import {+ DEFAULT_CONTEXT_WINDOW,+ DEFAULT_MAX_TOKENS,+} from "./provider-binding.js";++/**+ * Tokens held back from the context window for the summary prompt and the+ * model's own output. Compaction thresholds are derived from the active model's+ * window rather than configured, and this floor reproduces the reserve that+ * used to be the default setting, so the hard safety boundary is unchanged.+ */+export const COMPACTION_RESERVE_FLOOR_TOKENS = 16_384;+/**+ * Retained-tail target as a share of the safe budget, bounded so a 32K window+ * still keeps a usable tail and a 1M window does not carry the whole session+ * forward. A single fixed token count cannot serve both.+ */+export const COMPACTION_KEEP_RECENT_RATIO = 0.2;+export const COMPACTION_MIN_KEEP_RECENT_TOKENS = 8_000;+export const COMPACTION_MAX_KEEP_RECENT_TOKENS = 64_000;+/**+ * Cap on the user messages carried across a compaction boundary, matching+ * Codex's `COMPACT_USER_MESSAGE_MAX_TOKENS`. Clamped against the safe budget so+ * a small model window is not filled by retention alone.+ */+export const COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS = 20_000;++/**+ * Context thresholds derived from the active model's window.+ *+ * `hardLimit` is the safety boundary: the next provider request must not be+ * issued while the context is at or above it. Compaction happens inline at that+ * boundary, the way Codex does it — there is no off-critical-path variant.+ */+export type ContextBudget = {+ /** Estimated tokens in the reconstructed model context. */+ tokens: number;+ /** Point where an uncompacted provider request is no longer allowed. */+ hardLimit: number;+ /** Tokens reserved for the request's own prompt and output. */+ requestHeadroom: number;+ /** Approximate recent-context tokens a checkpoint should retain. */+ keepRecentTokens: number;+};++/**+ * The only model facts the budget depends on. Kept structural and optional so a+ * pi-ai `Model` passes directly, while a catalog entry that never reported a+ * window still falls back to the package defaults instead of producing NaN.+ */+export type ContextBudgetModel = {+ contextWindow?: number;+ maxTokens?: number;+};++/** Thresholds only, for callers that already know their own token count. */+export type ContextBudgetLimits = Omit<ContextBudget, "tokens">;++/**+ * Derive the safety thresholds for a model window, without estimating tokens.+ *+ * Headroom is the larger of the reserve floor, the model's own output budget,+ * and 5% of the window: a model that can emit 32K tokens needs at least that+ * much room, and a very large window needs proportionally more than the floor.+ * Every bound is clamped so a pathologically small window still yields a+ * positive limit rather than zero or a negative one.+ */+export function contextBudgetLimitsFor(+ model: ContextBudgetModel,+): ContextBudgetLimits {+ const contextWindow = Math.max(+ 1,+ Math.round(model.contextWindow || DEFAULT_CONTEXT_WINDOW),+ );+ const modelOutputBudget = Math.min(+ Math.max(1, Math.round(model.maxTokens || DEFAULT_MAX_TOKENS)),+ Math.max(1, Math.floor(contextWindow * 0.25)),+ );+ const reserveFloor = Math.min(+ COMPACTION_RESERVE_FLOOR_TOKENS,+ Math.max(1, Math.floor(contextWindow * 0.5)),+ );+ const requestHeadroom = Math.min(+ contextWindow - 1,+ Math.max(reserveFloor, modelOutputBudget, Math.ceil(contextWindow * 0.05)),+ );+ const hardLimit = Math.max(1, contextWindow - requestHeadroom);+ const keepRecentTokens = Math.min(+ Math.max(+ COMPACTION_MIN_KEEP_RECENT_TOKENS,+ Math.min(+ COMPACTION_MAX_KEEP_RECENT_TOKENS,+ Math.floor(hardLimit * COMPACTION_KEEP_RECENT_RATIO),+ ),+ ),+ // A retained tail wider than half the safe budget would leave the summary+ // no room, so the min/max clamp above never wins on a small window.+ Math.max(1, Math.floor(hardLimit * 0.5)),+ );+ return { hardLimit, requestHeadroom, keepRecentTokens };+}++/** Thresholds for a model window, plus the estimated size of `messages`. */+export function contextBudgetFor(+ model: ContextBudgetModel,+ messages: AgentMessage[],+): ContextBudget {+ return {+ tokens: estimateContextTokens(messages).tokens,+ ...contextBudgetLimitsFor(model),+ };+}++/**+ * Cap on the active user message a checkpoint carries forward. Codex uses a+ * flat 20k; the clamp keeps a small model window from being filled by+ * retention alone, which would leave the summary no room.+ */+export function retainedUserMessageBudget(+ budget: Pick<ContextBudget, "hardLimit">,+): number {+ return Math.max(+ 1,+ Math.min(+ COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS,+ Math.floor(budget.hardLimit * 0.5),+ ),+ );+}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 44b7abf05..5190d8143 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -9,7 +9,6 @@ import {BACKGROUND_CONTEXT,compact,convertToLlm,- estimateContextTokens,estimateTokens,prepareCompaction,withAbortSignal,@@ -133,6 +132,11 @@ import {providerRequestKey,type RuntimeProviderConfig,} from "./provider-binding.js";+import {+ contextBudgetFor,+ retainedUserMessageBudget,+ type ContextBudget,+} from "./context-budget.js";import { PathMutex } from "./path-lock.js";import { DelegationChainRegistry } from "./delegation-chain.js";import {@@ -527,27 +531,6 @@ function formatDelegationResults(includedDelegationIds,};}-/**- * Tokens held back from the context window for the summary prompt and the- * model's own output. Compaction thresholds are derived from the active model's- * window rather than configured, and this floor reproduces the reserve that- * used to be the default setting, so the hard safety boundary is unchanged.- */-const COMPACTION_RESERVE_FLOOR_TOKENS = 16_384;-/**- * Retained-tail target as a share of the safe budget, bounded so a 32K window- * still keeps a usable tail and a 1M window does not carry the whole session- * forward. A single fixed token count cannot serve both.- */-const COMPACTION_KEEP_RECENT_RATIO = 0.2;-const COMPACTION_MIN_KEEP_RECENT_TOKENS = 8_000;-const COMPACTION_MAX_KEEP_RECENT_TOKENS = 64_000;-/**- * Cap on the user messages carried across a compaction boundary, matching- * Codex's `COMPACT_USER_MESSAGE_MAX_TOKENS`. Clamped against the safe budget so- * a small model window is not filled by retention alone.- */-const COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS = 20_000;const COMPACTION_FALLBACK_KEEP_RECENT_RATIO = 0.25;const COMPACTION_FALLBACK_MAX_SUMMARY_CHARS = 12_000;const COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS = 2_048;@@ -802,24 +785,6 @@ function contextFallbackReminder(): string {}-/**- * Context thresholds derived from the active model's window.- *- * `hardLimit` is the safety boundary: the next provider request must not be- * issued while the context is at or above it. Compaction happens inline at that- * boundary, the way Codex does it — there is no off-critical-path variant.- */-type ContextBudget = {- /** Estimated tokens in the reconstructed model context. */- tokens: number;- /** Point where an uncompacted provider request is no longer allowed. */- hardLimit: number;- /** Tokens reserved for the request's own prompt and output. */- requestHeadroom: number;- /** Approximate recent-context tokens a checkpoint should retain. */- keepRecentTokens: number;-};-export type PluginToolDef = {/** Full exposed name (`plugin_<pluginIdSafe>_<toolName>`, D015). */name: string;@@ -5656,43 +5621,7 @@ Delegation rules:}private contextBudget(messages: AgentMessage[]): ContextBudget {- const contextWindow = Math.max(- 1,- Math.round(this.model.contextWindow || DEFAULT_CONTEXT_WINDOW),- );- const modelOutputBudget = Math.min(- Math.max(1, Math.round(this.model.maxTokens || DEFAULT_MAX_TOKENS)),- Math.max(1, Math.floor(contextWindow * 0.25)),- );- const reserveFloor = Math.min(- COMPACTION_RESERVE_FLOOR_TOKENS,- Math.max(1, Math.floor(contextWindow * 0.5)),- );- const requestHeadroom = Math.min(- contextWindow - 1,- Math.max(- reserveFloor,- modelOutputBudget,- Math.ceil(contextWindow * 0.05),- ),- );- const hardLimit = Math.max(1, contextWindow - requestHeadroom);- const keepRecentTokens = Math.min(- Math.max(- COMPACTION_MIN_KEEP_RECENT_TOKENS,- Math.min(- COMPACTION_MAX_KEEP_RECENT_TOKENS,- Math.floor(hardLimit * COMPACTION_KEEP_RECENT_RATIO),- ),- ),- Math.max(1, Math.floor(hardLimit * 0.5)),- );- return {- tokens: estimateContextTokens(messages).tokens,- hardLimit,- requestHeadroom,- keepRecentTokens,- };+ return contextBudgetFor(this.model, messages);}private automaticCompactionNeeded(@@ -5704,19 +5633,8 @@ Delegation rules:return this.compactionEnabled && budget.tokens >= budget.hardLimit;}- /**- * Cap on the active user message a checkpoint carries forward. Codex uses a- * flat 20k; the clamp keeps a small model window from being filled by- * retention alone, which would leave the summary no room.- */private retainedUserMessageBudget(budget: ContextBudget): number {- return Math.max(- 1,- Math.min(- COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS,- Math.floor(budget.hardLimit * 0.5),- ),- );+ return retainedUserMessageBudget(budget);}/**