diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index 0bfdcf78ee3..005723e1ee0 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -443,7 +443,8 @@ and settings inspection reports it. The stdio frame limit, `REA_MCP_MAX_RESPONSE_BYTES`, stays a separate transport safety net. When complete Evidence fits, it is delivered inline as before. When it does -not, the work is never refused or truncated: +not, the work is never truncated, and it is refused only when even its summary +does not fit: - MCP retains the complete Evidence in the session and returns `{"summary": …, "delivery": …}`, the shape the CLI prints. `summary` is the @@ -456,6 +457,11 @@ not, the work is never refused or truncated: is its serialization, so the facts reach the model whether its client forwards only `structuredContent` (Codex, VS Code) or only text (Gemini CLI, LangChain). Each budgeted tool's output schema admits this result. +- When the summary itself is over the budget, MCP returns a + `resource_constraint` error instead. The complete Evidence is still retained, + and `details.reported_limits.agent_budget` carries the same delivery facts, + including `next`, so the next call pages the record within the budget. + The CLI still prints its summary. - `inspect_analysis_view` with view `{kind: "evidence-json", offset, limit}` pages the exact JSON text of the retained record in UTF-16 code units. It is the recovery every client can diff --git a/scripts/verify/baselines/resource-constraint-constructor.json b/scripts/verify/baselines/resource-constraint-constructor.json index bcece840c99..261c297785d 100644 --- a/scripts/verify/baselines/resource-constraint-constructor.json +++ b/scripts/verify/baselines/resource-constraint-constructor.json @@ -126,7 +126,7 @@ "src/rust/RustBinaryProvider.ts": 2, "src/server/ErrorEvidenceTransport.ts": 2, "src/server/ProgressiveToolCatalog.ts": 1, - "src/server/ToolResultDelivery.ts": 2, + "src/server/ToolResultDelivery.ts": 1, "src/sqlite/SqliteDatabaseProvider.ts": 1, "src/sqlite/SqliteDatabaseSnapshot.ts": 1, "src/sqlite/SqliteDatabaseWorkerExecution.ts": 3, diff --git a/scripts/verify/untyped-budget-refusal-baseline.json b/scripts/verify/untyped-budget-refusal-baseline.json index afc349773f8..b18f74a0218 100644 --- a/scripts/verify/untyped-budget-refusal-baseline.json +++ b/scripts/verify/untyped-budget-refusal-baseline.json @@ -25,5 +25,5 @@ "src/model/ModelFormat.ts": 1, "src/server/ErrorEvidenceTransport.ts": 2, "src/server/ProgressiveToolCatalog.ts": 1, - "src/server/ToolResultDelivery.ts": 2 + "src/server/ToolResultDelivery.ts": 1 } diff --git a/src/domain/agentResultBudget.ts b/src/domain/agentResultBudget.ts index 74f33f8b03b..0f3a8ad1d7b 100644 --- a/src/domain/agentResultBudget.ts +++ b/src/domain/agentResultBudget.ts @@ -301,6 +301,8 @@ export const agentBudgetDelivery = (input: { readonly budget: AgentResultBudget; readonly recovery: AgentBudgetRecovery; readonly failure?: { readonly tool: string }; + /** The summary was also over the budget, so the result was refused. */ + readonly withheld?: true; }): AgentBudgetDelivery => { const { budget, completeBytes, evidenceId, recovery } = input; const source = pageSource(evidenceId, recovery); @@ -332,9 +334,11 @@ export const agentBudgetDelivery = (input: { ? { retention_failure: recovery.reason } : {}), note: - input.failure === undefined - ? `Complete ${input.operation} Evidence ${evidenceId} is ${sizeAndBudget(completeBytes, budget)}, so its summary was delivered. Nothing was truncated. ${recoveryNote(recovery)}` - : `The complete ${input.failure.tool} failure is ${sizeAndBudget(completeBytes, budget)}, so a bounded summary of it was delivered: details.${OMITTED_FAILURE_DETAILS} names the detail fields left out and details.${TRUNCATED_FAILURE_FIELDS} any shortened text. ${input.operation} Evidence ${evidenceId} holds every fact. ${failureRecoveryNote(recovery)}`, + input.withheld === true + ? `Complete ${input.operation} Evidence ${evidenceId} is ${sizeAndBudget(completeBytes, budget)}, and its summary is over the budget too, so neither was delivered. Nothing was truncated. ${recoveryNote(recovery)}` + : input.failure === undefined + ? `Complete ${input.operation} Evidence ${evidenceId} is ${sizeAndBudget(completeBytes, budget)}, so its summary was delivered. Nothing was truncated. ${recoveryNote(recovery)}` + : `The complete ${input.failure.tool} failure is ${sizeAndBudget(completeBytes, budget)}, so a bounded summary of it was delivered: details.${OMITTED_FAILURE_DETAILS} names the detail fields left out and details.${TRUNCATED_FAILURE_FIELDS} any shortened text. ${input.operation} Evidence ${evidenceId} holds every fact. ${failureRecoveryNote(recovery)}`, }; }; diff --git a/src/server/ToolResultDelivery.ts b/src/server/ToolResultDelivery.ts index 0ad4ca52f28..ad00f560d78 100644 --- a/src/server/ToolResultDelivery.ts +++ b/src/server/ToolResultDelivery.ts @@ -310,9 +310,8 @@ export class ToolResultDelivery { "The tool's own result, without the forwarded content, is details.result; use its ids, and ask for a smaller image: a screenshot region, or format jpeg with a lower quality.", }); return this.toErrorToolResult( - new AnalysisResourceConstraintError( + responseRefusal( contract.name, - "transport", projected.reason, { boundary: "mcp-response", @@ -320,7 +319,7 @@ export class ToolResultDelivery { response_bytes_at_least: measured.bytesAtLeast, constraint: measured.constraint, }, - { remediationAction: projected.remediationAction }, + projected.remediationAction, ), contract.returnsTargetContent, { result: result.ok ? result.value : null }, @@ -349,6 +348,11 @@ export class ToolResultDelivery { agentBudgetSeed: this.agentBudgetSeed, resultBudgetBytes: this.resultBudgetBytes, }); + if (budgeted?.kind === "summary-over-budget") + return this.toErrorToolResult( + summaryOverBudget(contract, budgeted.delivery), + contract.returnsTargetContent, + ); if (budgeted !== undefined) { // The delivery facts travel inside the structured result, so clients // that forward only `structuredContent` and clients that forward only @@ -698,9 +702,8 @@ export class ToolResultDelivery { nextStep: overflowNextStep(overflow, contract), }); return this.toErrorToolResult( - new AnalysisResourceConstraintError( + responseRefusal( contract.name, - "transport", projected.reason, { boundary: "mcp-response", @@ -715,7 +718,7 @@ export class ToolResultDelivery { ? {} : { next_operation: overflow.next.operation }), }, - { remediationAction: projected.remediationAction }, + projected.remediationAction, ), contract.returnsTargetContent, ); @@ -740,10 +743,15 @@ const overBudgetSummary = ( }, ): | { + readonly kind: "summary"; readonly summary: Evidence; readonly delivery: AgentBudgetDelivery; readonly link: ResourceLink | undefined; } + | { + readonly kind: "summary-over-budget"; + readonly delivery: AgentBudgetDelivery; + } | undefined => { if (evidence.operation === INSPECT_ANALYSIS_VIEW_OPERATION) return undefined; // Only a tool with a detail selector is budgeted: its caller can always @@ -763,27 +771,73 @@ const overBudgetSummary = ( const summary = summarizeOverBudgetEvidence(evidence); if (!summary.ok || !contract.outputSchema.safeParse(summary.value).success) return undefined; + const facts = { + operation: evidence.operation, + evidenceId: evidence.evidence_id, + completeBytes, + budget, + recovery: { kind: "session" }, + } as const; + const delivery = agentBudgetDelivery(facts); + // MCP sends the summary beside its delivery facts. When that answer is + // itself over the budget, refuse with the same facts instead: the complete + // Evidence is retained, and delivery.next pages it. + const answerBytes = jsonValueByteLength( + { summary: summary.value, delivery } as unknown as JsonValue, + budget.bytes + 1, + ); + if (answerBytes > budget.bytes) + return { + kind: "summary-over-budget", + delivery: agentBudgetDelivery({ ...facts, withheld: true }), + }; // The summary is retained like an explicit one, so its own ID resolves; // a summary that cannot be retained leaves complete delivery in place. if (recordSummary === undefined || !recordSummary(summary.value).ok) return undefined; return { + kind: "summary", summary: summary.value, link: retainedEvidenceLink( evidence, completeBytes, limits.resultBudgetBytes, ), - delivery: agentBudgetDelivery({ - operation: evidence.operation, - evidenceId: evidence.evidence_id, - completeBytes, - budget, - recovery: { kind: "session" }, - }), + delivery, }; }; +/** + * The refusal for complete Evidence whose summary is also over the agent + * result budget. The complete Evidence is retained; its delivery facts name + * the inspect_analysis_view call that pages it within the budget. + */ +/** A delivery refusal: a response over a boundary this delivery enforces. */ +const responseRefusal = ( + operation: string, + reason: string, + facts: Readonly>, + remediationAction: string, +): AnalysisResourceConstraintError => + new AnalysisResourceConstraintError(operation, "transport", reason, facts, { + remediationAction, + }); + +const summaryOverBudget = ( + contract: ToolContract, + delivery: AgentBudgetDelivery, +): AnalysisResourceConstraintError => + responseRefusal( + contract.name, + `The complete result and its summary are both over the agent result budget of ${String(delivery.budget_bytes)} bytes; complete Evidence ${delivery.evidence_id} is retained.`, + { agent_budget: delivery as unknown as JsonValue }, + // Only an idempotent call is safe to repeat; one with effects already + // ran, so the retained record is its result. + contract.effects.idempotent + ? "Page the retained complete Evidence with inspect_analysis_view, using details.reported_limits.agent_budget.next.arguments, or repeat the call with detail complete." + : "Page the retained complete Evidence with inspect_analysis_view, using details.reported_limits.agent_budget.next.arguments. Do not repeat the completed call; its actions already ran.", + ); + /** Wire bytes one more content block adds, with its array separator. */ const contentBlockBytes = (block: ResourceLink): number => Buffer.byteLength(JSON.stringify(block)) + 1; diff --git a/tests/boundary/mcp/agentResultBudgetMcp.test.ts b/tests/boundary/mcp/agentResultBudgetMcp.test.ts index ae426e2fca5..bf205966d41 100644 --- a/tests/boundary/mcp/agentResultBudgetMcp.test.ts +++ b/tests/boundary/mcp/agentResultBudgetMcp.test.ts @@ -23,6 +23,7 @@ import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; import { clientProjections } from "../../fixtures/mcpClientProjection.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { connectBudgetedLayout } from "./budgetedLayout.js"; const connect = async (overrides: Record = {}) => { @@ -286,8 +287,21 @@ it.each([ name: "inspect_byte_entropy", arguments: input, }); - expect(delivered.isError).not.toBe(true); - const delivery = deliveryOf(delivered); + // A summary that fits is delivered; one whose answer is over the budget + // too is refused with the same delivery facts. Either names next. + const delivery = ( + delivered.isError === true + ? ( + parseMcpToolError(delivered).error.details as { + readonly reported_limits: { readonly agent_budget: Delivery }; + } + ).reported_limits.agent_budget + : deliveryOf(delivered) + ) as Delivery & { readonly budget_source?: string }; + if (delivered.isError === true) + expect(parseMcpToolError(delivered).error.code).toBe( + "resource_constraint", + ); expect(delivery).toMatchObject({ budget_bytes: budget, budget_source: source, diff --git a/tests/boundary/mcp/debPackageMcp.test.ts b/tests/boundary/mcp/debPackageMcp.test.ts index c733d8ee525..c0ff86bf7bf 100644 --- a/tests/boundary/mcp/debPackageMcp.test.ts +++ b/tests/boundary/mcp/debPackageMcp.test.ts @@ -287,3 +287,79 @@ mcpTest( } }, ); + +mcpTest( + "refuses with paging facts when the summary itself is over the agent result budget", + async ({ mcp }) => { + const session = createTestBinarySession(() => { + throw new Error( + "Debian package inspection must not start a deep provider", + ); + }); + // The smallest budget, so the summary's own ar member rows exceed it. + const environment = { + ...testDeliveryEnvironment(process.env, "budgeted"), + REA_AGENT_RESULT_BUDGET_BYTES: "4096", + }; + const client = await mcp.connect( + createServer({ kind: "session", session }, { environment }), + undefined, + undefined, + "budgeted", + ); + try { + const root = await createTestTempDirectory("rea-deb-summary-budget-"); + const path = join(root, "many-members_1.0_all.deb"); + await writeFile( + path, + debPackageFixture({ + // 29 more members stay under the 32-member ar admission. + extraMembers: Array.from({ length: 29 }, (_, index) => ({ + name: `_extra-member${String(index).padStart(2, "0")}`, + data: Buffer.from("x"), + })), + }), + ); + const refused = await client.callTool({ + name: "inspect_deb_package", + arguments: { path }, + }); + const { error } = parseMcpToolError(refused); + expect(error).toMatchObject({ + code: "resource_constraint", + details: { + reported_limits: { + agent_budget: { + kind: "agent-budget-summary", + budget_bytes: 4096, + retained: "session", + next: { operation: "inspect_analysis_view" }, + // The note describes the refusal, not a delivered summary. + note: expect.stringContaining("so neither was delivered"), + }, + }, + }, + // inspect_deb_package is idempotent, so repeating it is offered. + remediation: { action: expect.stringContaining("detail complete") }, + }); + // The named next call pages the retained complete Evidence. + const next = ( + error.details as { + reported_limits: { + agent_budget: { next: { arguments: Record } }; + }; + } + ).reported_limits.agent_budget.next.arguments; + const page = await client.callTool({ + name: "inspect_analysis_view", + arguments: next, + }); + expect(page.isError, JSON.stringify(page.content)).not.toBe(true); + // The page that next names fits the same 4,096-byte budget. + const [text] = page.content as { type: string; text?: string }[]; + expect(Buffer.byteLength(String(text?.text))).toBeLessThanOrEqual(4096); + } finally { + await session.close(); + } + }, +); diff --git a/tests/boundary/mcp/firmwareVectorTableMcpCli.test.ts b/tests/boundary/mcp/firmwareVectorTableMcpCli.test.ts index 41f6e77f02b..c507754ae56 100644 --- a/tests/boundary/mcp/firmwareVectorTableMcpCli.test.ts +++ b/tests/boundary/mcp/firmwareVectorTableMcpCli.test.ts @@ -7,10 +7,7 @@ import { silentLogger } from "../../../src/logger.js"; import { AGENT_RESULT_BUDGET_ENVIRONMENT } from "../../../src/domain/agentResultBudget.js"; import { analysisRefusalRemediation } from "../../../src/domain/analysisRefusal.js"; import type { AdjustableBudget } from "../../../src/domain/analysisRefusal.js"; -import { - DEFAULT_AGENT_RESULT_BUDGET_BYTES, - MINIMUM_AGENT_RESULT_BUDGET_BYTES, -} from "../../../src/domain/analysisResourceLimits.js"; +import { DEFAULT_AGENT_RESULT_BUDGET_BYTES } from "../../../src/domain/analysisResourceLimits.js"; import { clientProjections } from "../../fixtures/mcpClientProjection.js"; import { createServer } from "../../../src/server/createServer.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; @@ -464,10 +461,12 @@ describe("inspect_firmware_vector_table CLI and MCP parity", () => { }); it("delivers a retained summary only when the complete result exceeds the selected agent result budget", async () => { + const SELECTED_BUDGET_BYTES = 12_000; const dir = await createTestTempDirectory("rea-fw-vt-budget-"); const fwPath = join(dir, "vt.bin"); - // 48 slots: a complete report between the 4096-byte minimum budget and - // the 32768-byte default, so only the selected budget summarizes it. + // 48 slots: a complete report (about 18 KB) above a 12,000-byte budget, + // whose summary answer still fits it, and under the 32768-byte default, + // so only the selected budget summarizes it. const img = Buffer.alloc(48 * 4, 0); img.writeUInt32LE(0x20020000, 0); for (let i = 1; i < 48; i += 1) @@ -511,9 +510,7 @@ describe("inspect_firmware_vector_table CLI and MCP parity", () => { const summarized = await inspectWith({ ...defaults, - [AGENT_RESULT_BUDGET_ENVIRONMENT]: String( - MINIMUM_AGENT_RESULT_BUDGET_BYTES, - ), + [AGENT_RESULT_BUDGET_ENVIRONMENT]: String(SELECTED_BUDGET_BYTES), }); expect(summarized.isError).not.toBe(true); const { summary, delivery } = clientProjections(summarized) as { @@ -523,10 +520,8 @@ describe("inspect_firmware_vector_table CLI and MCP parity", () => { readonly complete_bytes: number; }; }; - expect(delivery.budget_bytes).toBe(MINIMUM_AGENT_RESULT_BUDGET_BYTES); - expect(delivery.complete_bytes).toBeGreaterThan( - MINIMUM_AGENT_RESULT_BUDGET_BYTES, - ); + expect(delivery.budget_bytes).toBe(SELECTED_BUDGET_BYTES); + expect(delivery.complete_bytes).toBeGreaterThan(SELECTED_BUDGET_BYTES); expect(delivery.complete_bytes).toBeLessThanOrEqual( DEFAULT_AGENT_RESULT_BUDGET_BYTES, );