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 d9aa850f131..10dd9da4d26 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts @@ -1,10 +1,13 @@ import { cp, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { once } from "node:events"; +import { stripTypeScriptTypes } from "node:module"; import { createHash } from "node:crypto"; import { StringDecoder } from "node:string_decoder"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { PI_DISTRIBUTION_CLOSURE_SHA256 } from "./pi-closure-pins.js"; +import { PI_NODE_VERSION } from "./pi-node-pins.js"; import { assertPiInstallationProfile, verifyPiInstallation } from "./pi-installation.js"; import { QUALIFIED_ACPX_PROFILES, type QualifiedAcpxProfile } from "./qualified-profiles.js"; @@ -24,10 +27,28 @@ 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.v6\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}`); + const hash = (bytes: string | Uint8Array) => createHash("sha256").update(bytes).digest("hex"); + const canonical = (value: any): string => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` + : value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value); + const identity = JSON.parse(await readFile(new URL("../../../test-fixtures/pi-acp/profile-v6-identity.json", import.meta.url), "utf8")); + const declaration = identity.declaration; + expect(identity.commandDigest).toBe(`sha256:${hash(canonical(declaration))}`); + expect(QUALIFIED_ACPX_PROFILES.pi.commandDigest).toBe(identity.commandDigest); + for (const key of ["agent", "agentProfileVersion", "acpxVersion", "agentServerVersion", "agentRuntimeVersion"] as const) { + expect(declaration[key]).toBe(QUALIFIED_ACPX_PROFILES.pi[key]); + } + expect(declaration.closure).toEqual(PI_DISTRIBUTION_CLOSURE_SHA256); + expect(declaration.nodeVersion).toBe(PI_NODE_VERSION); + const helper = stripTypeScriptTypes(await readFile(new URL("./pi-acp-runtime.ts", import.meta.url), "utf8")).split("\n").map(line => line.trimEnd()).join("\n"); + const extension = stripTypeScriptTypes(await readFile(new URL("./pi-runtime-extension.ts", import.meta.url), "utf8")).replace('from "./pi-acp-runtime.js"', 'from "../node_modules/pi-acp/dist/paperclip-runtime.js"'); + expect(hash(helper)).toBe(declaration.helperSha256); + expect(hash(extension)).toBe(declaration.extensionSha256); + const materializer = await readFile(new URL("../../../scripts/materialize-pi-distribution.mjs", import.meta.url), "utf8"); + expect(materializer).toContain(`wrapperSha256: "${declaration.wrapperSha256}"`); + expect(materializer).toContain(`helperSha256: "${declaration.helperSha256}"`); + // This exact patch produced the independently verified v6 wrapper/closure. + // Pin it separately so wrapper-only edits cannot keep an unchanged declaration. + expect(hash(await readFile(new URL("../../../../../patches/pi-acp@0.0.33.patch", import.meta.url)))).toBe("bae0f2d9c866852a8d72883ddb7cc83af3e157d1638f9aa494670304913f6aea"); }); it("rejects legacy profiles and caller-selected identities", () => { diff --git a/packages/paperclip-runner/test/pi-native-package-contract.test.mjs b/packages/paperclip-runner/test/pi-native-package-contract.test.mjs index 32096a917ff..0d77a39788d 100644 --- a/packages/paperclip-runner/test/pi-native-package-contract.test.mjs +++ b/packages/paperclip-runner/test/pi-native-package-contract.test.mjs @@ -219,3 +219,52 @@ test("real pinned Pi executes all four owned native question methods without per assert.deepEqual(results.map(event => event.result.details), [{ status: "answered", optionId: "blue" }, { status: "negative_or_cancelled", confirmed: false }, { status: "answered", value: "Ada" }, { status: "answered", value: "New\ntext" }]); } finally { session?.dispose(); await rm(root, { recursive: true, force: true }); } }); + +test("real pinned Pi tool dispatch admits registered agent files and rejects unassigned roots", { timeout: 20_000 }, async () => { + const load = (name) => import(pathToFileURL(join(packageRoot, `dist/core/${name}.js`)).href); + const [{ createAgentSession }, { DefaultResourceLoader }, { ModelRuntime }, { SessionManager }, { SettingsManager }, { AuthStorage }] = await Promise.all( + ["sdk", "resource-loader", "model-runtime", "session-manager", "settings-manager", "auth-storage"].map(load), + ); + const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-pi-native-agent-files-"))); + let session; + try { + const workspace = join(root, "workspace"); const agentHome = join(root, "agent-files"); const privateRoot = join(root, "private"); const outside = join(root, "outside"); + for (const directory of [workspace, agentHome, privateRoot, outside]) await mkdir(directory); + await symlink(outside, join(agentHome, "escape")); + await writeFile(join(root, "extension.mjs"), stripTypeScriptTypes(extensionSource)); + await writeFile(join(root, "pi-acp-runtime.js"), stripTypeScriptTypes(await readFile(new URL("../src/drivers/acpx/pi-acp-runtime.ts", import.meta.url), "utf8"))); + const { installPiRuntimeExtension } = await import(pathToFileURL(join(root, "extension.mjs")).href); + const settings = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false } }); + const modelRuntime = await ModelRuntime.create({ credentials: AuthStorage.inMemory({}), modelsPath: null, refreshOnCreate: false, allowModelNetwork: false }); + const model = { id: "fixture", name: "Fixture", api: "openai-completions", provider: "fixture", baseUrl: "http://127.0.0.1:1", reasoning: false, input: ["text"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 64 }; + const resourceLoader = new DefaultResourceLoader({ cwd: workspace, agentDir: privateRoot, settingsManager: settings, noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, + extensionFactories: [pi => installPiRuntimeExtension(pi, { invocationNamespace: "00000000-0000-4000-8000-000000000000", workspace, agentHome, readOnly: false, readRoots: [], protectedRoots: [privateRoot], instructions: "", servers: [] })] }); + await resourceLoader.reload(); + ({ session } = await createAgentSession({ cwd: workspace, agentDir: privateRoot, model, modelRuntime, settingsManager: settings, sessionManager: SessionManager.inMemory(workspace), resourceLoader, thinkingLevel: "off" })); + const dialogs = []; const results = []; const errors = []; + const uiContext = { select: async (title) => { dialogs.push(title); return "Allow once"; }, notify() {}, setStatus() {}, setWidget() {}, setTitle() {}, setEditorText() {}, getEditorText: () => "", setWorkingMessage() {} }; + await session.bindExtensions({ uiContext, onError: error => errors.push(error.event) }); + session.subscribe(event => { if (event.type === "tool_execution_end") results.push(event); }); + const memory = join(agentHome, "memory.txt"); + const requests = [ + { name: "write", arguments: { path: memory, content: "private memory nonce\n" } }, + { name: "read", arguments: { path: memory } }, + { name: "write", arguments: { path: join(outside, "denied.txt"), content: "forbidden" } }, + { name: "write", arguments: { path: join(agentHome, "escape/denied.txt"), content: "forbidden" } }, + { name: "write", arguments: { path: join(privateRoot, "denied.txt"), content: "forbidden" } }, + ]; + let streams = 0; + session.agent.streamFunction = () => { + const request = requests[streams++]; + const message = { role: "assistant", content: request ? [{ type: "toolCall", id: "call_0", ...request }] : [{ type: "text", text: "done" }], api: model.api, provider: model.provider, model: model.id, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: request ? "toolUse" : "stop", timestamp: streams }; + return { async *[Symbol.asyncIterator]() { yield { type: "start", partial: message }; yield { type: "done", reason: message.stopReason, message }; }, result: async () => message }; + }; + await session.agent.prompt("fixture native agent files"); await session.agent.waitForIdle(); + assert.deepEqual(errors, []); assert.equal(results.length, 5); + assert.deepEqual(results.map(event => Boolean(event.isError)), [false, false, true, true, true]); + assert.equal(await readFile(memory, "utf8"), "private memory nonce\n"); + assert.match(JSON.stringify(results[1].result), /private memory nonce/); + for (const path of [join(outside, "denied.txt"), join(privateRoot, "denied.txt")]) await assert.rejects(readFile(path), { code: "ENOENT" }); + assert.equal(dialogs.length, 2); assert.ok(dialogs.every(title => title.startsWith("paperclip.pi.permission.v1:"))); + } finally { session?.dispose(); await rm(root, { recursive: true, force: true }); } +});