Skip to content

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

fix(runtime): budget against the folded request transcript

vastsaa887bba8377a
diff --cc docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 610665e4c,67ad9cf89..d72e0dce6
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@@ -307,6 -307,6 +307,10 @@@ pi-agent-core 提供 Agent 循环及稳
仅作为 AGPL-3.0 行为参考,不是链接或复制的依赖关系。详细依赖边界见
[pi 运行时依赖边界](../02-architecture/06-pi-runtime-dependency-boundary.md)。
++输出预算按适配器实际发送的转录估算。若绑定模型不支持对话中途的系统消息,后续系统更新会
++折叠为一条携带当前指令和工具的前置消息;父运行时和子代理也把折叠后的转录交给 pi-ai,
++使两层输出上限估算一致,避免重复的旧指令快照耗尽输出预算。
++
压缩遵循 Codex 的机制 (ADR 0064):它总是内联发生在
回合边界,模型可以通过`new_context`请求,每次compaction
添加一个转录本行并提出一个警告 toast,并且没有
diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index d48f8dfa1,20fdd2d13..a2e85903c
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@@ -9369,6 -9290,6 +9369,15 @@@ Follow the [current S3 acceptance scena
会拿到两条输出」这一机制。
- **状态:** 单元测试覆盖;没有端到端驱动从「循环追加过的上下文」构建新回合的请求。
++### E2E-OUTPUT-CAP-716:保持模型请求在发布上下文窗口内
++
++- **先决条件:** 确定性 provider 夹具公布上下文窗口,支持父级和子代理请求并记录请求负载;不使用真实凭据。
++- **步骤:** 配置大于已发布窗口的用户上下文覆盖;发送包含 CJK 文本的父级提示、调用子代理并运行一次性补全,再以 `thinkingLevel: "omit"` 重复父级请求。随后恢复一个包含许多大型系统指令更新的长会话,并通过不支持对话中途系统消息的 Responses 网关继续;再运行一个最后一次用量报告之后才追加多次系统指令更新的子代理。
++- **预期:** 每个请求都有不超过估算剩余窗口的明确输出预算;运行时按已发布安全上限压缩,且 `input + output` 不超过上限。能容纳时,小型 ASCII 请求保留配置的预算;恢复会话和子代理仅发送一条折叠后的指令消息,并保留配置预算,而不是降至 provider 最小值。
++- **关联规格:** `03-runtime/02-agent-runtime.md`、`03-runtime/13-model-catalog-and-selection.md`。
++- **自动化:** `packages/agent-runtime/src/output-cap-request.test.ts` 通过 loopback Responses 网关驱动恢复会话和子代理请求。
++- **状态:** 折叠指令步骤由 loopback 网关覆盖;其余确定性 provider 夹具待补充。
++
### E2E-MCP-HTTP-ACK — HTTP acknowledgement and authorization status
- **Preconditions**: A local mock Streamable HTTP server returns JSON for
diff --cc packages/agent-runtime/src/output-cap-request.test.ts
index 000000000,f8b41a098..d1b522518
mode 000000,100644..100644
--- a/packages/agent-runtime/src/output-cap-request.test.ts
+++ b/packages/agent-runtime/src/output-cap-request.test.ts
@@@ -1,0 -1,171 +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",
++ sessionId: "long-session", mode: "agent", provider: gatewayProvider(baseUrl), history, thinkingLevel: "omit",
+ 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 --cc packages/agent-runtime/src/subagent-model-binding.ts
index 1c5702cf0,3a2955548..d4ba834bf
--- a/packages/agent-runtime/src/subagent-model-binding.ts
+++ b/packages/agent-runtime/src/subagent-model-binding.ts
@@@ -112,9 -110,9 +113,9 @@@ export function subagentModelBinding(op
baseUrl: m.baseUrl,
sessionId: opts.sessionId,
});
- return createProviderRetryStream(
+ return uniqueToolCalls(createProviderRetryStream(
m,
- context,
+ requestContext,
sessionOptions,
(retryOptions) => accountModelStream(m, () =>
omitThinking
diff --cc packages/agent-runtime/src/subagent.test.ts
index 40e1672e4,93da4371f..d7124b743
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@@ -147,10 -147,10 +147,10 @@@ 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", () => {
+ it("retains completed same-id rounds in a resumed subagent request", () => {
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
const { run } = createRun({