From 06cf356a8bc94f709fcd15606fe05e17933fe3b2 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 28 Sep 2026 16:10:15 -0500 Subject: [PATCH] Preserve Pi validation failures and structured Bash output Bump the immutable Pi profile to version 3 and reject prior warm snapshots. Bound and redact authenticated MCP validation errors while retaining failure status; preserve standard ACP tool values alongside terminal metadata. Co-Authored-By: Paperclip --- doc/architecture/runner-pi-capabilities.md | 34 +++++++- .../runner-core/src/acpx_provider_backend.rs | 4 +- .../scripts/materialize-pi-distribution.mjs | 2 +- .../backends/native-backend-factory.test.ts | 4 +- .../src/drivers/acpx/pi-closure-pins.ts | 6 +- .../src/drivers/acpx/pi-installation.test.ts | 7 +- .../src/drivers/acpx/pi-installation.ts | 2 +- .../drivers/acpx/pi-runtime-extension.test.ts | 38 ++++++++ .../src/drivers/acpx/pi-runtime-extension.ts | 31 ++++++- .../src/drivers/acpx/qualified-profiles.ts | 4 +- .../test-fixtures/pi-acp/fake-pi.mjs | 10 +++ .../test/pi-acp-package-contract.test.mjs | 23 +++++ patches/pi-acp@0.0.33.patch | 87 +++++++++++++------ 13 files changed, 206 insertions(+), 46 deletions(-) diff --git a/doc/architecture/runner-pi-capabilities.md b/doc/architecture/runner-pi-capabilities.md index 0012ffc1b36..aeb25ab096e 100644 --- a/doc/architecture/runner-pi-capabilities.md +++ b/doc/architecture/runner-pi-capabilities.md @@ -204,7 +204,7 @@ that those targets have executed successfully. ### Installation authority and token semantics -`verifyPiInstallation(profile)` admits only profile version 2 and the source-owned +`verifyPiInstallation(profile)` admits only profile version 3 and the source-owned Pi identity. It resolves `provider-assets/pi/-` inside the verified Runner package, checks the complete runtime against source-pinned closure hashes, and opens a guarded immutable native snapshot. The snapshot bootstrap binds Node, @@ -227,9 +227,9 @@ The first authenticated local Runner snapshot verified the exact configured model ID. It did not settle or produce a terminal usage receipt; complete local and Linux/Daytona receipt qualification remains outstanding. -Profile version 2 declaration digest: `sha256:0f687e38cb3c607a01fab80f03e19bbbf5cb53a8afb1fc40d71f9ab54551cff1`. It hashes the versioned +Profile version 3 declaration digest: `sha256:72cb225288376f733b9ed3afa5e13565eb4152f0de509bc1181382fa44bee472`. It hashes the versioned profile domain, patched wrapper source and platform closure pins. Every native -closure remains independently checked at launch. Version 1 warm sessions cannot +closure remains independently checked at launch. Version 1 and 2 warm sessions cannot be reused with this integration. Pi 0.84.2 emits `compaction_start`/`compaction_end`; the wrapper maps those @@ -441,3 +441,31 @@ reports and fixtures; an execution-source change requires a fresh build. Production admission remains qualification-pending until the live matrix and spend receipt checks pass. + + +## Version 3: retain failed tool validation and Bash results + +The version 2 file-edit Product attempt exposed an owned bridge defect: five +`paperclip_finish` calls returned failed MCP results, but the extension replaced +all authenticated validation text with a generic rejection. Version 3 keeps +valid text and structured error details within an 8 KiB UTF-8 bound, redacts +bound credentials and labelled secrets, and still raises a failed tool result. +Malformed or oversized errors remain explicit failures. The original five call +arguments were not retained across the privacy boundary, and the fixture's +workspace was removed during cleanup, so this report does not reconstruct their +contents or assert that the file oracle passed. + +A separate Bash projection gap discarded native result fields because upstream +sent them only as private terminal metadata. The wrapper now also emits standard +ACP `rawInput` and `rawOutput`, preserving each structured value whole up to +64 KiB and marking larger values omitted. Installed-process fixtures cover +success, failure, partial output and the size boundary. Canonical `exitCode` +remains unknown: the shared projection does not yet map the native structured +field, and this patch does not infer it from text or success status. + +These changes alter the immutable wrapper and owned extension. All three target +closure pins and the versioned profile digest change; version 2 warm snapshots +are rejected. Earlier local hello, restrictive-denial and Linux initialization +proofs remain tied to their version 2 execution source. Version 3 must complete +fresh immutable-pack checks and paid qualification before those behaviors can be +claimed for its bytes. diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index b3306c89d60..6145730e2be 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -170,7 +170,7 @@ impl AcpxProviderDescriptor { "0.0.33", Some("@earendil-works/pi-coding-agent"), Some("0.84.2"), - "sha256:0f687e38cb3c607a01fab80f03e19bbbf5cb53a8afb1fc40d71f9ab54551cff1", + "sha256:72cb225288376f733b9ed3afa5e13565eb4152f0de509bc1181382fa44bee472", ), "cursor" => ( self.model.as_str(), @@ -2461,7 +2461,7 @@ mod tests { "pi", "pi-acp", "0.0.33", - "sha256:0f687e38cb3c607a01fab80f03e19bbbf5cb53a8afb1fc40d71f9ab54551cff1", + "sha256:72cb225288376f733b9ed3afa5e13565eb4152f0de509bc1181382fa44bee472", Some("@earendil-works/pi-coding-agent"), Some("0.84.2"), "openrouter/deepseek/deepseek-v4-flash-0731", diff --git a/packages/paperclip-runner/scripts/materialize-pi-distribution.mjs b/packages/paperclip-runner/scripts/materialize-pi-distribution.mjs index de0e341d56c..312d4b4ebae 100644 --- a/packages/paperclip-runner/scripts/materialize-pi-distribution.mjs +++ b/packages/paperclip-runner/scripts/materialize-pi-distribution.mjs @@ -18,7 +18,7 @@ const patchPath = join(workspaceRoot, "patches/pi-acp@0.0.33.patch"); const supportedTargets = new Set(["darwin-arm64", "darwin-x64", "linux-x64"]); export const PI_DISTRIBUTION_PINS = Object.freeze({ wrapper: "0.0.33", runtime: "0.84.2", sdk: "0.26.0", zod: "3.25.76", nodeVersion: PI_NODE_VERSION, - wrapperSha256: "2eb201c3a931177490a8e18f4a8392f00cbcf21847e9cc171de528da5e253935", + wrapperSha256: "df6b6270d95154aef058e3dacb766d0f0ca0d26fbfaccc4c804cdb088fd89e1e", helperSha256: "4333d284ff06ab1195e49630041f0b03a486a92fc678100525ad107e0982dba1", }); const hash = (bytes) => createHash("sha256").update(bytes).digest("hex"); diff --git a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts index 63a589e27c5..e054312aff9 100644 --- a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts +++ b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts @@ -534,10 +534,10 @@ describe("native backend factory", () => { })).toThrow("ACPX candidate direct execution requires completed qualification"); }); - it("rejects a Pi version 1 warm snapshot after the rich ACP upgrade", () => { + it.each([1, 2] as const)("rejects a Pi version %s warm snapshot after the rich ACP upgrade", version => { const input = acpxExecution("pi"); if (input.provider.kind !== "acpx") throw new Error("invalid fixture"); - input.provider.profile.agentProfileVersion = 1; + input.provider.profile.agentProfileVersion = version; expect(() => createNativeSessionBackend(input, { acpxRuntimeDirectory: "/runtime" })) .toThrow("does not match the qualified agentProfileVersion"); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/pi-closure-pins.ts b/packages/paperclip-runner/src/drivers/acpx/pi-closure-pins.ts index dca9ac67b3a..bd19336e41f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-closure-pins.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-closure-pins.ts @@ -6,7 +6,7 @@ * three pins. Never accept a digest supplied only by an installed manifest. */ export const PI_DISTRIBUTION_CLOSURE_SHA256 = Object.freeze({ - "darwin-arm64": "b30047dce9c4c25e1fbc88a1aa828690a6a11ebdc3f6fcc083875986eb2d9585", - "darwin-x64": "3bff53a334f7226bd14adb6a91e6e3603281bec7b93e7dd62aa5599483df8bba", - "linux-x64": "482e648e5b8890971fdf326a936fddc01ae89c335159d7133ddff70b49ed3d3d", + "darwin-arm64": "a523fa338cef7db88a42b81e2dc8a5cc41b78775aed1be0a9439f6622ea8a710", + "darwin-x64": "27988352e6bb214ac1c78faeb3157cf5995cceb12612aef09c44e7f0e76356f6", + "linux-x64": "002812b62463ffae84b8e8b58567a6f4ba5025dd830528c5ed3b4c50c2a0ee29", }); diff --git a/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts index b9cbfc005d0..2ba0af71da3 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts @@ -10,7 +10,7 @@ import { QUALIFIED_ACPX_PROFILES, type QualifiedAcpxProfile } from "./qualified- const roots: string[] = []; afterEach(async () => { vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); -const candidate = (): QualifiedAcpxProfile => ({ ...QUALIFIED_ACPX_PROFILES.pi, agentProfileVersion: 2 }); +const candidate = (): QualifiedAcpxProfile => ({ ...QUALIFIED_ACPX_PROFILES.pi, agentProfileVersion: 3 }); async function fixture() { const root = await mkdtemp(join(tmpdir(), "pi-installation-test-")); roots.push(root); @@ -24,7 +24,7 @@ async function fixture() { describe("Pi installation factory", () => { it("binds the profile declaration to the reviewed patch and platform closure pins", async () => { - const digest = createHash("sha256").update("paperclip.pi.rich-acp.profile.v2\0") + const digest = createHash("sha256").update("paperclip.pi.rich-acp.profile.v3\0") .update(await readFile(new URL("../../../../../patches/pi-acp@0.0.33.patch", import.meta.url))) .update("\0").update(await readFile(new URL("./pi-closure-pins.ts", import.meta.url))).digest("hex"); expect(QUALIFIED_ACPX_PROFILES.pi.commandDigest).toBe(`sha256:${digest}`); @@ -32,7 +32,8 @@ describe("Pi installation factory", () => { it("rejects legacy profiles and caller-selected identities", () => { expect(() => assertPiInstallationProfile(candidate())).not.toThrow(); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 1 })).toThrow("version 2"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 1 })).toThrow("version 3"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 2 })).toThrow("version 3"); for (const changed of [{ agentServerVersion: "latest" }, { commandDigest: `sha256:${"0".repeat(64)}` }, { reportedModelId: "different" }, { agentRuntimePackage: "ambient-pi" }]) { expect(() => assertPiInstallationProfile({ ...candidate(), ...changed })).toThrow("trusted declaration"); } diff --git a/packages/paperclip-runner/src/drivers/acpx/pi-installation.ts b/packages/paperclip-runner/src/drivers/acpx/pi-installation.ts index c2e6fb768b5..a55cbc46dc9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-installation.ts @@ -24,7 +24,7 @@ function record(value: unknown): Record { /** Candidate identity is build-owned; model selection cannot substitute a CLI. */ export function assertPiInstallationProfile(profile: QualifiedAcpxProfile): void { const trusted = QUALIFIED_ACPX_PROFILES.pi; - if (profile.agentProfileVersion !== 2) throw new Error("Pi rich ACP requires profile version 2; reopen the previous session"); + if (profile.agentProfileVersion !== 3) throw new Error("Pi rich ACP requires profile version 3; reopen the previous session"); if (profile.agent !== "pi" || profile.driverKind !== trusted.driverKind || profile.protocolVersion !== trusted.protocolVersion || profile.acpxVersion !== trusted.acpxVersion || profile.agentServerPackage !== "pi-acp" || profile.agentServerVersion !== "0.0.33" || profile.agentRuntimePackage !== "@earendil-works/pi-coding-agent" || profile.agentRuntimeVersion !== "0.84.2" || profile.commandDigest !== trusted.commandDigest || profile.permissionPolicy !== "interactive" || profile.qualificationModel !== PI_MODEL || profile.reportedModelId !== PI_MODEL) throw new Error("Pi distribution profile differs from its trusted declaration"); } diff --git a/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.test.ts b/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.test.ts index 63d81cea6b2..04838466f4f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.test.ts @@ -152,6 +152,44 @@ describe("owned Pi runtime extension", () => { expect(select).not.toHaveBeenCalled(); }); + it("preserves bounded MCP validation errors as failures and removes bound authentication", async () => { + const { config } = await workspace(); const h = harness(); + const authorization = "Bearer assigned-mcp-token-123456789"; + config.servers = [{ type: "http", name: "paperclip", url: "http://127.0.0.1:1234", headers: [{ name: "Authorization", value: authorization }] }]; + const request = vi.fn(async (_server, method) => method === "tools/list" + ? { tools: [{ name: "paperclip_finish", inputSchema: { type: "object" } }] } + : method === "tools/call" ? { isError: true, content: [{ type: "text", text: `completionClaim.contractRevision must equal 1; verification.items[0].status is invalid; Authorization: ${authorization}; token=other-private-value; \"password\":\"another-secret\"` }], structuredContent: { code: "INVALID_VERIFICATION", field: "verification.items[0].status" } } : {}); + await installPiRuntimeExtension(h.api, config, request); + const error = await h.tools[0]!.execute("original-call", {}).catch(value => value); + expect(error).toBeInstanceOf(Error); + expect(error.message).toContain("completionClaim.contractRevision must equal 1"); + expect(error.message).toContain("verification.items[0].status is invalid"); + expect(error.message).not.toContain("assigned-mcp-token-123456789"); + expect(error.message).not.toContain("other-private-value"); + expect(error.message).not.toContain("another-secret"); + expect(error.message).toContain("INVALID_VERIFICATION"); + expect(error.message).toContain("[REDACTED]"); + }); + + it.each([ + { isError: true, content: [{ type: "text", text: "x".repeat(9000) }] }, + { isError: true, content: [{ type: "text", text: { unsafe: "not text" } }] }, + { isError: true, content: [{ type: "image", data: "not an error description", mimeType: "image/png" }] }, + { isError: true, content: null }, + { isError: "true", content: [{ type: "text", text: "malformed error flag" }] }, + ])("fails closed for oversized or malformed MCP error content %#", async result => { + const { config } = await workspace(); const h = harness(); + config.servers = [{ type: "http", name: "paperclip", url: "http://127.0.0.1:1234", headers: [] }]; + const request = vi.fn(async (_server, method) => method === "tools/list" + ? { tools: [{ name: "paperclip_finish", inputSchema: { type: "object" } }] } + : method === "tools/call" ? result : {}); + await installPiRuntimeExtension(h.api, config, request); + const error = await h.tools[0]!.execute("call", {}).catch(value => value); + expect(error).toBeInstanceOf(Error); + expect(Buffer.byteLength(error.message)).toBeLessThanOrEqual(8192); + expect(error.message).not.toContain("not an error description"); + }); + it("rejects incomplete catalogs and tool-result errors without exposing auth", async () => { const { config } = await workspace(); const h = harness(); config.servers = [{ type: "http", name: "paperclip", url: "http://127.0.0.1:1234", headers: [] }]; diff --git a/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.ts b/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.ts index 6a7a6b667d8..530802cf936 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-runtime-extension.ts @@ -11,6 +11,8 @@ export const PI_PERMISSION_OPTIONS = ["Allow once", "Allow for this session", "D const MAX_CONFIGURATION_BYTES = 64 * 1024; const MAX_RESPONSE_BYTES = 4 * 1024 * 1024; const MAX_TOOLS = 512; +// Match the sidecar safeText error bound; the extension is an immutable standalone module. +const MAX_ERROR_BYTES = 8_192; interface PiUi { select(title: string, options: string[]): Promise; @@ -160,6 +162,32 @@ export async function checkPiNativeTool( return "Pi tool path is outside its assigned workspace"; } +/** Keep authenticated tool validation useful without exposing transport credentials. */ +function piMcpToolError(result: Record, config: PiRuntimeConfiguration): Error { + const fallback = "Paperclip tool request was rejected"; + if (!Array.isArray(result.content) || result.content.length > MAX_TOOLS) return new Error(`${fallback}: invalid error content`); + const parts: string[] = []; + for (const item of result.content) { + if (!item || typeof item !== "object" || Array.isArray(item)) return new Error(`${fallback}: invalid error content`); + const block = item as Record; + if (block.type !== "text" || typeof block.text !== "string") return new Error(`${fallback}: invalid error content`); + parts.push(block.text); + } + if (result.structuredContent !== undefined) { + if (!result.structuredContent || typeof result.structuredContent !== "object" || Array.isArray(result.structuredContent)) return new Error(`${fallback}: invalid error details`); + parts.push(JSON.stringify(result.structuredContent)); + } + let message = `${fallback}: ${parts.join("\n").trim() || "no validation details"}`; + if (Buffer.byteLength(message) > MAX_ERROR_BYTES) return new Error(`${fallback}: error content exceeds ${MAX_ERROR_BYTES} bytes`); + const boundSecrets = [process.env.OPENROUTER_API_KEY, ...config.servers.flatMap(server => server.headers.flatMap(header => [header.value, header.value.replace(/^Bearer /, "")]))]; + for (const secret of boundSecrets) if (secret) message = message.split(secret).join("[REDACTED]"); + // Use the same labelled-secret rule as sidecar safeText, also covering JSON + // quoted keys and bearer values that can occur in gateway error text. + message = message.replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [REDACTED]") + .replace(/(key|token|secret|password|authorization)["']?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\]]+)/gi, "$1=[REDACTED]"); + return new Error(Buffer.byteLength(message) <= MAX_ERROR_BYTES ? message : `${fallback}: redacted error content exceeds ${MAX_ERROR_BYTES} bytes`); +} + /** Bounded JSON MCP client for runner-owned HTTP bridges. No redirects or files. */ export async function piMcpRequest( server: PiMcpServer, @@ -258,7 +286,8 @@ export async function installPiRuntimeExtension( parameters: structuredClone(schema), async execute(callId, arguments_, signal) { const result = await request(server, "tools/call", { name: sourceName, arguments: arguments_ }, callId, signal); - if (result.isError === true) throw new Error("Paperclip tool request was rejected"); + if (result.isError !== undefined && typeof result.isError !== "boolean") throw new Error("Pi MCP tool error flag is invalid"); + if (result.isError === true) throw piMcpToolError(result, config); if (!Array.isArray(result.content)) throw new Error("Pi MCP tool result is invalid"); const content = result.content.map((item) => { const block = asRecord(item); diff --git a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts index 66439d892c1..ff1f1141f8f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts @@ -47,14 +47,14 @@ export const QUALIFIED_ACPX_PROFILES: Readonly< protocolVersion: ACPX_DRIVER_PROTOCOL_VERSION, acpxVersion: QUALIFIED_ACPX_VERSION, agent: "pi", - agentProfileVersion: 2, + agentProfileVersion: 3, qualificationStatus: "pending", agentServerPackage: "pi-acp", agentServerVersion: "0.0.33", agentRuntimePackage: "@earendil-works/pi-coding-agent", agentRuntimeVersion: "0.84.2", commandDigest: - "sha256:0f687e38cb3c607a01fab80f03e19bbbf5cb53a8afb1fc40d71f9ab54551cff1", + "sha256:72cb225288376f733b9ed3afa5e13565eb4152f0de509bc1181382fa44bee472", qualificationModel: "openrouter/deepseek/deepseek-v4-flash-0731", reportedModelId: "openrouter/deepseek/deepseek-v4-flash-0731", permissionPolicy: "interactive", diff --git a/packages/paperclip-runner/test-fixtures/pi-acp/fake-pi.mjs b/packages/paperclip-runner/test-fixtures/pi-acp/fake-pi.mjs index d0a1f347015..f472f99087e 100644 --- a/packages/paperclip-runner/test-fixtures/pi-acp/fake-pi.mjs +++ b/packages/paperclip-runner/test-fixtures/pi-acp/fake-pi.mjs @@ -32,6 +32,16 @@ createInterface({ input: process.stdin }).on("line", (line) => { if (request.type === "abort") { response(); if (active) { active = false; output({ type: "agent_settled" }); } return; } if (request.type === "prompt") { response({ disposition: "started" }); active = true; output({ type: "agent_start" }); + if (request.message.startsWith("bash-")) { + const failure = request.message === "bash-failure"; + const oversized = request.message === "bash-oversized"; + const args = { command: failure ? "printf failure >&2; exit 7" : "printf done", timeout: 3 }; + const result = { content: [{ type: "text", text: oversized ? "x".repeat(65536) : failure ? "failure\n" : "done\n" }], details: { exitCode: failure ? 7 : 0, truncated: false } }; + output({ type: "tool_execution_start", toolCallId: "bash-fixture", toolName: "bash", args }); + output({ type: "tool_execution_update", toolCallId: "bash-fixture", toolName: "bash", partialResult: { content: [{ type: "text", text: "partial" }] } }); + output({ type: "tool_execution_end", toolCallId: "bash-fixture", toolName: "bash", result, isError: failure }); + finish("bash completed"); return; + } if (request.message === "die") { process.exit(4); } if (request.message === "long") return; if (["retry-success", "retry-failure", "retry-unknown"].includes(request.message)) { diff --git a/packages/paperclip-runner/test/pi-acp-package-contract.test.mjs b/packages/paperclip-runner/test/pi-acp-package-contract.test.mjs index cf83ccbd3a0..0dfaed5eaea 100644 --- a/packages/paperclip-runner/test/pi-acp-package-contract.test.mjs +++ b/packages/paperclip-runner/test/pi-acp-package-contract.test.mjs @@ -159,3 +159,26 @@ test("manual and automatic compaction retain Pi 0.84.2 progress and usage", asyn f.notify("session/cancel", { sessionId: session.sessionId }); await active; assert.match(packageSource, /this\.request\(\{ type: "compact", customInstructions \}, 120000\)/); }); + +for (const outcome of ["success", "failure", "oversized"]) { + test(`actual patched ACP Bash ${outcome} retains standard structured tool data`, async (t) => { + const f = await fixture(t); + const session = await f.call("session/new", { cwd: join(f.root, "workspace"), mcpServers: [] }); + const result = await f.call("session/prompt", { sessionId: session.sessionId, prompt: [{ type: "text", text: `bash-${outcome}` }] }); + assert.equal(result.stopReason, "end_turn"); + const updates = f.notifications.map((event) => event.params?.update).filter((update) => update?.toolCallId === "bash-fixture"); + assert.deepEqual(updates[0].rawInput, { command: outcome === "failure" ? "printf failure >&2; exit 7" : "printf done", timeout: 3 }); + assert.deepEqual(updates[1].rawOutput, { content: [{ type: "text", text: "partial" }] }); + const terminal = updates.at(-1); + assert.equal(terminal.status, outcome === "failure" ? "failed" : "completed"); + if (outcome === "oversized") { + assert.equal(terminal.rawOutput._meta.paperclipPi.omitted, "tool value exceeds 65536 bytes"); + assert.ok(terminal.rawOutput._meta.paperclipPi.originalBytes > 65536); + assert.ok(Buffer.byteLength(JSON.stringify(terminal.rawOutput)) < 256); + } else { + assert.deepEqual(terminal.rawOutput, { content: [{ type: "text", text: outcome === "failure" ? "failure\n" : "done\n" }], details: { exitCode: outcome === "failure" ? 7 : 0, truncated: false } }); + } + // Preserve existing terminal consumers without inferring a canonical exit code. + assert.equal(terminal._meta.terminal_exit.exit_code, outcome === "failure" ? 7 : 0); + }); +} diff --git a/patches/pi-acp@0.0.33.patch b/patches/pi-acp@0.0.33.patch index d70fb86b4a9..daa07bff7ac 100644 --- a/patches/pi-acp@0.0.33.patch +++ b/patches/pi-acp@0.0.33.patch @@ -174,7 +174,22 @@ ); } -@@ -714,6 +719,7 @@ +@@ -534,6 +539,14 @@ + const record = value; + const command = record?.command ?? record?.cmd ?? record?.args?.command ?? record?.args?.cmd ?? record?.input?.command ?? record?.input?.cmd ?? record?.rawInput?.command ?? record?.rawInput?.cmd ?? record?.toolInput?.command ?? record?.toolInput?.cmd ?? record?.details?.command ?? record?.details?.cmd; + return typeof command === "string" && command.trim() ? command : void 0; ++} ++// Standard ACP data survives clients that do not consume terminal metadata. ++// Keep each structured native value whole or explicitly omit it at a byte bound. ++function boundedBashValue(value) { ++ const encoded = JSON.stringify(value); ++ if (encoded === void 0) return void 0; ++ const bytes = Buffer.byteLength(encoded); ++ return bytes <= 65536 ? value : { _meta: { paperclipPi: { omitted: "tool value exceeds 65536 bytes", originalBytes: bytes } } }; + } + function bashResultText(result) { + const record = result; +@@ -714,6 +727,7 @@ try { proc = await PiRpcProcess.spawn({ cwd: params.cwd, @@ -182,7 +197,7 @@ piCommand: params.piCommand }); } catch (e) { -@@ -808,6 +814,9 @@ +@@ -808,6 +822,9 @@ this.proc = opts.proc; this.conn = opts.conn; this.fileCommands = opts.fileCommands ?? []; @@ -192,7 +207,7 @@ this.proc.onEvent((ev) => this.handlePiEvent(ev)); } setStartupInfo(text) { -@@ -852,6 +861,7 @@ +@@ -852,6 +869,7 @@ } async cancel() { this.cancelRequested = true; @@ -200,7 +215,23 @@ if (this.turnQueue.length) { const queued = this.turnQueue.splice(0, this.turnQueue.length); for (const t of queued) t.resolve("cancelled"); -@@ -920,12 +930,16 @@ +@@ -890,6 +908,7 @@ + kind: "execute", + status: params.status, + locations: params.locations, ++ rawInput: boundedBashValue(params.args), + ...params.includeTerminal ? { content: bashTerminalContent(params.toolCallId) } : {}, + ...params.includeTerminal ? { _meta: bashTerminalInfoMeta(params.toolCallId, this.cwd) } : {} + }); +@@ -903,6 +922,7 @@ + sessionUpdate: "tool_call_update", + toolCallId: params.toolCallId, + status: params.status, ++ rawOutput: boundedBashValue(params.result), + _meta: { + ...delta ? bashTerminalOutputMeta(params.toolCallId, delta) : {}, + ...params.status === "completed" || params.status === "failed" ? bashTerminalExitMeta(params.toolCallId, bashExitCode(params.result, Boolean(params.isError))) : {} +@@ -920,12 +940,16 @@ this.cancelRequested = false; this.inAgentLoop = false; this.pendingTurn = { resolve: t.resolve, reject: t.reject }; @@ -217,7 +248,7 @@ const authErr = maybeAuthRequiredError(err); if (authErr) { this.pendingTurn?.reject(authErr); -@@ -946,6 +960,23 @@ +@@ -946,6 +970,23 @@ handlePiEvent(ev) { const type = String(ev.type ?? ""); switch (type) { @@ -241,7 +272,7 @@ case "message_update": { const ame = ev.assistantMessageEvent; if (ame?.type === "text_delta" && typeof ame.delta === "string") { -@@ -1047,7 +1078,7 @@ +@@ -1047,7 +1088,7 @@ if (p) { try { const abs = isAbsolute(p) ? p : resolvePath(this.cwd, p); @@ -250,7 +281,7 @@ this.fileSnapshots.set(toolCallId, { path: p, oldText: snapshotOldText }); if (toolName === "edit") { for (const needle of getEditOldTexts(args)) { -@@ -1125,7 +1156,7 @@ +@@ -1125,7 +1166,7 @@ if (!isError && snapshot) { try { const abs = isAbsolute(snapshot.path) ? snapshot.path : resolvePath(this.cwd, snapshot.path); @@ -259,7 +290,7 @@ if (snapshot.oldText === null || newText !== snapshot.oldText) { hasStructuredDiff = true; content = [ -@@ -1154,14 +1185,11 @@ +@@ -1154,14 +1195,11 @@ break; } case "extension_ui_request": { @@ -278,7 +309,7 @@ break; } case "auto_retry_start": { -@@ -1174,28 +1202,31 @@ +@@ -1174,28 +1212,31 @@ case "auto_retry_end": { this.emit({ sessionUpdate: "agent_message_chunk", @@ -326,7 +357,7 @@ break; } case "agent_start": { -@@ -1210,9 +1241,12 @@ +@@ -1210,9 +1251,12 @@ break; } case "agent_settled": { @@ -340,7 +371,7 @@ this.pendingTurn = null; this.inAgentLoop = false; const next = this.turnQueue.shift(); -@@ -1725,6 +1759,7 @@ +@@ -1725,6 +1769,7 @@ return process.env.PI_CODING_AGENT_DIR ? resolve3(process.env.PI_CODING_AGENT_DIR) : join4(homedir4(), ".pi", "agent"); } function getEnableSkillCommands(cwd) { @@ -348,7 +379,7 @@ const merged = getMergedSettings(cwd); const direct = merged.enableSkillCommands; if (typeof direct === "boolean") return direct; -@@ -1733,6 +1768,7 @@ +@@ -1733,6 +1778,7 @@ return true; } function getQuietStartup(cwd) { @@ -356,7 +387,7 @@ const merged = getMergedSettings(cwd); const direct = merged.quietStartup; if (typeof direct === "boolean") return direct; -@@ -1824,6 +1860,7 @@ +@@ -1824,6 +1870,7 @@ const out = []; const seen = /* @__PURE__ */ new Set(); for (const c of [...a, ...b]) { @@ -364,7 +395,7 @@ if (seen.has(c.name)) continue; seen.add(c.name); out.push(c); -@@ -1884,11 +1921,13 @@ +@@ -1884,11 +1931,13 @@ throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`); } const cwd = opts?.cwd ?? stored.cwd; @@ -378,7 +409,7 @@ piCommand: process.env.PI_ACP_PI_COMMAND }); } catch (e) { -@@ -1897,7 +1936,7 @@ +@@ -1897,7 +1946,7 @@ } throw e; } @@ -387,7 +418,7 @@ const session = this.sessions.getOrCreate(sessionId, { cwd, mcpServers: opts?.mcpServers ?? [], -@@ -1917,6 +1956,7 @@ +@@ -1917,6 +1966,7 @@ } } async initialize(params) { @@ -395,7 +426,7 @@ const supportedVersion = 1; const requested = params.protocolVersion; return { -@@ -1933,7 +1973,8 @@ +@@ -1933,7 +1983,8 @@ }), agentCapabilities: { loadSession: true, @@ -405,7 +436,7 @@ promptCapabilities: { image: true, audio: false, -@@ -1942,8 +1983,7 @@ +@@ -1942,8 +1993,7 @@ sessionCapabilities: { // **UNSTABLE** ACP capability used by Zed's codex-acp adapter. // Enables a native session picker in clients that support it. @@ -415,7 +446,7 @@ } } }; -@@ -1953,7 +1993,7 @@ +@@ -1953,7 +2003,7 @@ throw RequestError3.invalidParams(`cwd must be an absolute path: ${params.cwd}`); } this.lastSessionCwd = params.cwd; @@ -424,7 +455,7 @@ const enableSkillCommands = getEnableSkillCommands(params.cwd); const session = await this.sessions.create({ cwd: params.cwd, -@@ -1994,14 +2034,14 @@ +@@ -1994,14 +2044,14 @@ this.cleanupFailedNewSession(session.sessionId, state); throw RequestError3.authRequired( { authMethods: getAuthMethods() }, @@ -441,7 +472,7 @@ ); } const { configOptions, models, modes } = await getSessionConfiguration(session.proc, { -@@ -2064,34 +2104,27 @@ +@@ -2064,34 +2114,27 @@ } async prompt(params) { const session = await this.restoreSession(params.sessionId); @@ -488,7 +519,7 @@ } if (cmd === "session") { const stats = await session.proc.getSessionStats(); -@@ -2432,8 +2465,18 @@ +@@ -2432,8 +2475,18 @@ } } const result = await session.prompt(message, images); @@ -509,7 +540,7 @@ } async cancel(params) { const session = this.sessions.maybeGet(params.sessionId); -@@ -2473,7 +2516,7 @@ +@@ -2473,7 +2526,7 @@ mcpServers: params.mcpServers }); const proc = session.proc; @@ -518,7 +549,7 @@ this.sessions.closeAllExcept?.(session.sessionId); this.store.upsert({ sessionId: params.sessionId, -@@ -2607,6 +2650,7 @@ +@@ -2607,6 +2660,7 @@ return response; } async deleteSession(params) { @@ -526,7 +557,7 @@ const stored = this.store.get(params.sessionId); const piSession = findPiSession(params.sessionId); if (!stored && !piSession) { -@@ -2828,6 +2872,7 @@ +@@ -2828,6 +2882,7 @@ return 0; } function buildUpdateNotice() { @@ -534,7 +565,7 @@ try { const piVersion = spawnSync("pi", ["--version"], { encoding: "utf-8" }); const installed = (String(piVersion.stdout ?? "").trim() || String(piVersion.stderr ?? "").trim()).replace( -@@ -2848,6 +2893,7 @@ +@@ -2848,6 +2903,7 @@ } } function buildStartupInfo(opts) { @@ -542,7 +573,7 @@ void opts.fileCommands; const md = []; try { -@@ -2980,6 +3026,7 @@ +@@ -2980,6 +3036,7 @@ // src/index.ts if (process.argv.includes("--terminal-login")) { @@ -550,7 +581,7 @@ const { spawnSync: spawnSync2 } = await import("child_process"); const cmd = getPiCommand(process.env.PI_ACP_PI_COMMAND); const res = spawnSync2(cmd, [], { -@@ -3019,11 +3066,12 @@ +@@ -3019,11 +3076,12 @@ } }); var stream = ndJsonStream(input, output);