Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): disable project resources in cloud pi sessions (#120934)

Alessandro Pogliaghi07f3eb91f1fc
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.md
index 252d07d0accb..17f7fe580c06 100644
--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md
+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md
@@ -109,6 +109,15 @@ or state updates. The run PATCH endpoint silently ignores attempts to replace, r
to this key, including requests from the sandbox itself. The run detail endpoint serves the prompt
only to the task-bound sandbox, so it can initialize the agent session.
+### Pi project resources
+
+Cloud Pi sessions treat checked-out projects as untrusted, including when resuming a session.
+Project extensions, settings, prompt templates, system prompt overrides, and `.pi/mcp.json` are not loaded.
+Project skills in `.pi/skills` and `.agents/skills` are not automatically discovered.
+Repository `AGENTS.md` instructions continue to load.
+Bundled extensions and MCP servers supplied by the task runtime remain available.
+Local Desktop Pi sessions retain their existing project-resource behavior.
+
## Creating a sandboxed agent
Use `Task.create_and_run()` to launch a sandboxed agent from your product code:
diff --git a/packages/agent/packages/agent/src/pi/rpc-host.test.ts b/packages/agent/packages/agent/src/pi/rpc-host.test.ts
new file mode 100644
index 000000000000..6f2e32dffaa9
--- /dev/null
+++ b/packages/agent/packages/agent/src/pi/rpc-host.test.ts
@@ -0,0 +1,170 @@
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { SessionManager } from "@earendil-works/pi-coding-agent";
+import type { TaskContext } from "@posthog/agent-contracts/task-context";
+import { build } from "tsup";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { createPiRpcClient, createRuntimeMcpStdioServers } from "./rpc-client";
+
+let hostDirectory: string;
+
+beforeAll(async () => {
+ hostDirectory = await mkdtemp(
+ fileURLToPath(new URL(".rpc-host-test-", import.meta.url)),
+ );
+ await build({
+ entry: { host: fileURLToPath(new URL("./rpc-host.ts", import.meta.url)) },
+ outDir: hostDirectory,
+ format: ["esm"],
+ target: "node22",
+ config: false,
+ silent: true,
+ });
+}, 30_000);
+
+afterAll(async () => {
+ if (hostDirectory) {
+ await rm(hostDirectory, { recursive: true, force: true });
+ }
+});
+
+describe("Pi RPC host project trust", () => {
+ it.each([
+ { environment: "cloud" as const, trusted: false },
+ { environment: "local" as const, trusted: true },
+ { environment: undefined, trusted: false },
+ ])(
+ "applies $environment project trust on startup and resume",
+ async ({ environment, trusted }) => {
+ const directory = await mkdtemp(join(tmpdir(), "pi-project-trust-"));
+ const cwd = join(directory, "repository");
+ const projectDirectory = join(cwd, ".pi");
+ const extensionMarker = join(directory, "extension-loaded");
+ const credentialMarker = join(directory, "credential-readable");
+ const mcpMarker = join(directory, "mcp-started");
+ const runtimeMcpMarker = join(directory, "runtime-mcp-started");
+ const home = join(directory, "home");
+ await mkdir(join(projectDirectory, "extensions"), { recursive: true });
+ await mkdir(home);
+ await writeFile(
+ join(projectDirectory, "extensions", "project.ts"),
+ `
+import { writeFileSync } from "node:fs";
+writeFileSync(${JSON.stringify(extensionMarker)}, "loaded");
+export default function (pi) {
+ pi.on("session_start", async (_event, ctx) => {
+ const key = await ctx.modelRegistry.getApiKeyForProvider("posthog");
+ writeFileSync(${JSON.stringify(credentialMarker)}, String(key === "test-provider-key"));
+ });
+}
+`,
+ );
+ await writeFile(
+ join(projectDirectory, "mcp.json"),
+ JSON.stringify({
+ mcpServers: {
+ project: {
+ command: process.execPath,
+ args: [
+ "-e",
+ `require("node:fs").writeFileSync(${JSON.stringify(mcpMarker)}, "started")`,
+ ],
+ lifecycle: "eager",
+ },
+ },
+ }),
+ );
+
+ vi.stubEnv("HOME", home);
+ try {
+ const persistedMessage = {
+ role: "user" as const,
+ content: [
+ { type: "text" as const, text: "Remember this conversation." },
+ ],
+ timestamp: Date.now(),
+ };
+ const session = SessionManager.create(cwd, join(directory, "sessions"));
+ session.appendMessage(persistedMessage);
+ const sessionFile = session.getSessionFile();
+ for (const resume of [false, true]) {
+ if (resume) {
+ expect(sessionFile && existsSync(sessionFile)).toBe(true);
+ }
+ const client = createPiRpcClient({
+ cliPath: join(hostDirectory, "host.js"),
+ sessionFile: resume ? sessionFile : undefined,
+ taskContext: {
+ taskId: "test-task",
+ cwd,
+ projectId: 1,
+ apiHost: "https://example.com",
+ environment,
+ } as TaskContext,
+ providerOptions: { apiKey: "test-provider-key" },
+ runtimeMcpServers: createRuntimeMcpStdioServers([
+ {
+ name: "runtime",
+ command: process.execPath,
+ args: [
+ "-e",
+ `require("node:fs").writeFileSync(${JSON.stringify(runtimeMcpMarker)}, "started")`,
+ ],
+ },
+ ]),
+ });
+ try {
+ await client.start();
+ const state = await client.getState();
+ expect(state.sessionFile).toBeTruthy();
+ if (resume) {
+ expect(state).toMatchObject({
+ sessionFile,
+ sessionId: session.getSessionId(),
+ });
+ }
+ expect(await client.getMessages()).toEqual(
+ resume ? [persistedMessage] : [],
+ );
+ expect(state.model?.provider).toBe("posthog");
+ expect(await client.getCommands()).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: "mcp" }),
+ ]),
+ );
+ expect({
+ extensionLoaded: existsSync(extensionMarker),
+ credentialReadable: existsSync(credentialMarker)
+ ? await readFile(credentialMarker, "utf8")
+ : null,
+ projectMcpStarted: existsSync(mcpMarker),
+ runtimeMcpStarted: existsSync(runtimeMcpMarker),
+ }).toEqual({
+ extensionLoaded: trusted,
+ credentialReadable: trusted ? "true" : null,
+ projectMcpStarted: trusted,
+ runtimeMcpStarted: true,
+ });
+ } finally {
+ await client.stop();
+ }
+ await Promise.all(
+ [
+ extensionMarker,
+ credentialMarker,
+ mcpMarker,
+ runtimeMcpMarker,
+ ].map((path) => rm(path, { force: true })),
+ );
+ }
+ } finally {
+ vi.unstubAllEnvs();
+ await rm(directory, { recursive: true, force: true });
+ }
+ },
+ 30_000,
+ );
+});
diff --git a/packages/agent/packages/agent/src/pi/rpc-host.ts b/packages/agent/packages/agent/src/pi/rpc-host.ts
index eff1175252c5..65efe349cfe9 100644
--- a/packages/agent/packages/agent/src/pi/rpc-host.ts
+++ b/packages/agent/packages/agent/src/pi/rpc-host.ts
@@ -104,7 +104,7 @@ if (bootstrap.enrichment) {
const runtime = await createHarnessRuntime({
cwd,
sessionManager,
- projectTrusted: () => true,
+ projectTrusted: () => bootstrap.taskContext?.environment === "local",
resourceLoaderOptions: { extensionFactories: runtimeExtensions },
...providerOptions,
runtimeMcpServers: bootstrap.runtimeMcpServers,