import { mkdirSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { Type } from "typebox"; import { afterEach, describe, expect, it } from "vitest"; import { calls, createTestSession, says, type TestSession, when, } from "../../../test/harness"; function extPath() { return path.resolve(import.meta.dirname, "../index.ts"); } function captureExtension(pi: { registerTool(tool: Record): void; }) { pi.registerTool({ name: "capture_value", label: "capture value", description: "Return the provided value for integration testing.", parameters: { type: "object", properties: { value: { type: "string" } }, required: ["value"], additionalProperties: false, }, async execute(_toolCallId: string, params: { value: string }) { return { content: [{ type: "text", text: params.value }], details: {} }; }, }); pi.registerTool({ name: "capture_object", label: "capture object", description: "Return property names for integration testing.", parameters: Type.Record(Type.String(), Type.String()), async execute(_toolCallId: string, params: Record) { return { content: [{ type: "text", text: Object.keys(params).join(",") }], details: {}, }; }, }); } function latestPlaceholder(session: TestSession) { const entry = session.session.sessionManager .getBranch() .toReversed() .find( (item) => item.type === "custom" && item.customType === "leaks-mapping-v1", ); if (entry?.type !== "custom") throw new Error("missing mapping"); return (entry.data as { placeholder: string }).placeholder; } const secret = "sk-or-v1-" + "d".repeat(64); const dotenvSecret = "dotenv-fixture-secret-123456789"; describe("leaks Pi provider boundary hooks", () => { let t: TestSession | undefined; afterEach(() => { t?.dispose(); t = undefined; }); it("loads in real Pi runtime with one command and no tools", async () => { t = await createTestSession({ extensions: [extPath()] }); const extension = t.session.extensionRunner.extensions[0]; expect(extension.path).toBe(extPath()); expect([...extension.commands.keys()]).toEqual(["leaks"]); expect([...extension.tools.keys()]).toEqual([]); }); it("redacts context copies without mutating originals", async () => { t = await createTestSession({ extensions: [extPath()] }); const messages = [{ role: "user", content: `send ${secret}` }]; const result = await t.session.extensionRunner.emitContext( messages as never, ); expect(JSON.stringify(result)).not.toContain(secret); expect(JSON.stringify(result)).toMatch( /__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__/, ); expect(messages[0].content).toContain(secret); }); it("does not nest mappings across context and provider passes", async () => { const cwd = path.join(os.tmpdir(), `leaks-double-pass-${Date.now()}`); mkdirSync(path.join(cwd, ".pi"), { recursive: true }); writeFileSync( path.join(cwd, ".pi", "settings.json"), JSON.stringify({ leaks: { regex: [ { pattern: "(__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__)", label: "PLACEHOLDER", }, ], }, }), ); t = await createTestSession({ cwd, extensions: [extPath()] }); const context = await t.session.extensionRunner.emitContext([ { role: "user", content: secret }, ] as never); const provider = await t.session.extensionRunner.emitBeforeProviderRequest({ messages: context, }); const placeholder = JSON.stringify(provider).match( /__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__/, )?.[0] as string; const mappings = t.session.sessionManager .getBranch() .filter( (entry) => entry.type === "custom" && entry.customType === "leaks-mapping-v1", ); expect(mappings).toHaveLength(1); const event = { type: "tool_call", toolName: "custom", toolCallId: "double-pass", input: { value: placeholder }, }; const blocked = await t.session.extensionRunner.emitToolCall( event as never, ); expect(blocked).toBeUndefined(); expect(event.input.value).toBe(secret); }); it("redacts provider payload authoritatively and preserves auth headers", async () => { t = await createTestSession({ extensions: [extPath()] }); const payload = { headers: { authorization: "Bearer provider-auth-header" }, messages: [{ role: "user", content: `send ${secret}` }], }; const result = await t.session.extensionRunner.emitBeforeProviderRequest(payload); expect(JSON.stringify(result)).not.toContain(secret); expect((result as typeof payload).headers.authorization).toBe( "Bearer provider-auth-header", ); }); it("restores tool args and finalized assistant messages locally", async () => { t = await createTestSession({ extensions: [extPath()] }); const redacted = await t.session.extensionRunner.emitBeforeProviderRequest({ text: secret, }); const placeholder = JSON.stringify(redacted).match( /__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__/, )?.[0]; expect(placeholder).toBeTruthy(); const event = { type: "tool_call", toolName: "bash", toolCallId: "1", input: { command: `echo ${placeholder}` }, }; await t.session.extensionRunner.emitToolCall(event as never); expect(event.input.command).toBe(`echo ${secret}`); const message = await t.session.extensionRunner.emitMessageEnd({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: `saw ${placeholder}` }], }, } as never); expect(JSON.stringify(message)).toContain(secret); }); it("rebuilds mappings from only the active tree branch", async () => { t = await createTestSession({ extensions: [extPath()] }); const manager = t.session.sessionManager; const runner = t.session.extensionRunner; const firstResult = await runner.emitBeforeProviderRequest({ text: secret, }); const firstPlaceholder = JSON.stringify(firstResult).match( /__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__/, )?.[0] as string; const firstMapping = manager .getBranch() .find( (entry) => entry.type === "custom" && entry.customType === "leaks-mapping-v1", ); if (!firstMapping) throw new Error("missing first mapping"); const generation = manager .getBranch() .find( (entry) => entry.type === "custom" && entry.customType === "leaks-generation-v1", ); if (!generation) throw new Error("missing generation"); manager.branch(generation.id); await runner.emit({ type: "session_tree", oldLeafId: firstMapping.id, newLeafId: generation.id, }); const siblingFixture = "sk-or-v1-" + "e".repeat(64); const secondResult = await runner.emitBeforeProviderRequest({ text: siblingFixture, }); const secondPlaceholder = JSON.stringify(secondResult).match( /__LEAK_V1_[A-Z0-9_]+_[a-f0-9]{32}__/, )?.[0] as string; const firstCall = { type: "tool_call", toolName: "custom", toolCallId: "first-branch", input: { value: firstPlaceholder }, }; expect(await runner.emitToolCall(firstCall as never)).toMatchObject({ block: true, }); const secondCall = { type: "tool_call", toolName: "custom", toolCallId: "second-branch", input: { value: secondPlaceholder }, }; expect(await runner.emitToolCall(secondCall as never)).toBeUndefined(); expect(secondCall.input.value).toBe(siblingFixture); const siblingLeaf = manager.getLeafId(); manager.branch(firstMapping.id); await runner.emit({ type: "session_tree", oldLeafId: siblingLeaf, newLeafId: firstMapping.id, }); const restoredFirst = { type: "tool_call", toolName: "custom", toolCallId: "restored-first", input: { value: firstPlaceholder }, }; expect(await runner.emitToolCall(restoredFirst as never)).toBeUndefined(); expect(restoredFirst.input.value).toBe(secret); }); it("hydrates built-in tool input through the real agent loop", async () => { let received = ""; t = await createTestSession({ extensions: [extPath()], mockTools: { write: (params: { content: string }) => { received = params.content; return "written"; }, }, }); await t.run( when(`store ${secret}`, [ calls("write", () => ({ path: "result.txt", content: latestPlaceholder(t as TestSession), })), says("done"), ]), ); expect(received).toBe(secret); }); it("hydrates custom tool input through the real agent loop", async () => { t = await createTestSession({ extensions: [extPath()], extensionFactories: [captureExtension as never], }); await t.run( when(`capture ${secret}`, [ calls("capture_value", () => ({ value: latestPlaceholder(t as TestSession), })), says("done"), ]), ); expect(t.events.toolResultsFor("capture_value")[0].text).toBe(secret); }); it("hydrates property names before an actual custom tool", async () => { t = await createTestSession({ extensions: [extPath()], extensionFactories: [captureExtension as never], }); await t.run( when(`capture key ${secret}`, [ calls("capture_object", () => ({ [latestPlaceholder(t as TestSession)]: "value", })), says("done"), ]), ); expect(t.events.toolResultsFor("capture_object")[0].text).toBe(secret); }); it("blocks unresolved property names before actual tool execution", async () => { t = await createTestSession({ extensions: [extPath()], extensionFactories: [captureExtension as never], }); await t.run( when("capture blocked input", [ calls("capture_object", { __LEAK_TOKEN_abcdef123456__: "unknown", }), says("done"), ]), ); expect(t.events.toolResultsFor("capture_object")[0].text).toContain( "Blocked capture_object", ); }); it("persists encrypted dotenv mappings without plaintext", async () => { const cwd = path.join(os.tmpdir(), `leaks-harness-${Date.now()}`); mkdirSync(cwd, { recursive: true }); writeFileSync(path.join(cwd, ".env"), `TOKEN=${dotenvSecret}\n`, "utf8"); t = await createTestSession({ cwd, extensions: [extPath()] }); const result = await t.session.extensionRunner.emitBeforeProviderRequest({ text: dotenvSecret, }); expect(JSON.stringify(result)).not.toContain(dotenvSecret); const entries = JSON.stringify(t.session.sessionManager.getEntries()); expect(entries).toContain("leaks-generation-v1"); expect(entries).toContain("leaks-mapping-v1"); expect(entries).not.toContain(dotenvSecret); }); });