: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): move Pi auto-publish into an extension (#81926)
Jonathan Mielooc14edf8193f0
diff --git a/products/desktop/packages/agent/src/pi/rpc-client.test.ts b/products/desktop/packages/agent/src/pi/rpc-client.test.tsindex 3b21c7d46869..cd3081b58542 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.test.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.test.ts@@ -105,6 +105,7 @@ process.stdin.resume();cliPath: hostPath,cwd: directory,projectTrusted: true,+ extensions: ["auto-publish"],providerOptions: { apiKey: "proxy-key" },});@@ -115,7 +116,7 @@ process.stdin.resume();JSON.stringify({providerOptions: { apiKey: "proxy-key" },projectTrusted: true,- channelMode: false,+ extensions: ["auto-publish"],}),);});@@ -125,7 +126,7 @@ process.stdin.resume();}});- it("passes channel mode privately and enables Electron's Node mode", async () => {+ it("passes requested extensions privately and enables Electron's Node mode", async () => {const directory = await mkdtemp(join(tmpdir(), "pi-electron-node-mode-"));const hostPath = join(directory, "host.mjs");const capturePath = join(directory, "capture.txt");@@ -138,7 +139,7 @@ const bootstrap = JSON.parse(readFileSync(3, "utf8"));closeSync(3);writeFileSync(${JSON.stringify(capturePath)}, JSON.stringify({nodeMode: process.env.ELECTRON_RUN_AS_NODE ?? "",- channelMode: bootstrap.channelMode,+ extensions: bootstrap.extensions,apiKey: bootstrap.providerOptions.apiKey,}));process.stdin.resume();@@ -148,7 +149,7 @@ process.stdin.resume();cliPath: hostPath,cwd: directory,providerOptions: { apiKey: "proxy-key" },- channelMode: true,+ extensions: ["repository-tools"],});try {@@ -157,7 +158,7 @@ process.stdin.resume();await expect(readFile(capturePath, "utf8")).resolves.toBe(JSON.stringify({nodeMode: "1",- channelMode: true,+ extensions: ["repository-tools"],apiKey: "proxy-key",}),);diff --git a/products/desktop/packages/agent/src/pi/rpc-client.ts b/products/desktop/packages/agent/src/pi/rpc-client.tsindex 0785704ee7e0..663eead80f9f 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.ts@@ -24,6 +24,7 @@ import type {} from "./types";export type PiRpcEvent = AgentSessionEvent | PiExtensionEvent;+export type PiRuntimeExtension = "repository-tools" | "auto-publish";type PiRpcEventListener = (event: PiRpcEvent) => void;@@ -47,12 +48,12 @@ export interface PiRpcProviderOptions {baseUrl?: string;}-interface PiRpcBootstrap {+export interface PiRpcBootstrap {providerOptions: PiRpcProviderOptions;runtimeMcpServers?: PiRuntimeMcpServers;mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;- channelMode?: boolean;+ extensions?: PiRuntimeExtension[];}type RpcClientProcessAccess = {@@ -428,7 +429,7 @@ export type PiRpcClientOptions = Pick<runtimeMcpServers?: PiRuntimeMcpServers;mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;- channelMode?: boolean;+ extensions?: PiRuntimeExtension[];};export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {@@ -438,7 +439,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {runtimeMcpServers,mcpToolPolicies,projectTrusted,- channelMode,+ extensions,...rpcOptions} = options;const args = sessionFile ? ["--session-file", sessionFile] : [];@@ -457,7 +458,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {runtimeMcpServers,mcpToolPolicies,projectTrusted: projectTrusted ?? false,- channelMode: channelMode === true,+ extensions,} satisfies PiRpcBootstrap,);}diff --git a/products/desktop/packages/agent/src/pi/rpc-host.ts b/products/desktop/packages/agent/src/pi/rpc-host.tsindex 1752a4239040..2de5282f3152 100644--- a/products/desktop/packages/agent/src/pi/rpc-host.ts+++ b/products/desktop/packages/agent/src/pi/rpc-host.ts@@ -1,29 +1,23 @@import { readFileSync } from "node:fs";-import { SessionManager } from "@earendil-works/pi-coding-agent";+import {+ type InlineExtension,+ SessionManager,+} from "@earendil-works/pi-coding-agent";import { createHarnessRuntime, runRpcMode } from "@posthog/harness";-import type { McpConfig } from "@posthog/harness/extensions/mcp/config";-import type { PosthogProviderOptions } from "@posthog/harness/extensions/posthog-provider/provider";+import { createAutoPublishExtension } from "@posthog/harness/extensions/auto-publish";import { createPiRuntimeTrustResolver } from "@posthog/harness/project-trust";import type {McpToolPermissionDecision,McpToolPermissionRequest,- McpToolPolicy,} from "@posthog/shared";import {POSTHOG_PI_QUEUE_ENTRY_TYPE,readPersistedPiQueue,} from "./queue-persistence";import { createPiRepositoryToolsExtension } from "./repository-tools-extension";+import type { PiRpcBootstrap, PiRuntimeExtension } from "./rpc-client";import { sanitizePiHostEnvironment } from "./rpc-environment";-interface PiRpcBootstrap {- providerOptions?: PosthogProviderOptions;- runtimeMcpServers?: McpConfig["mcpServers"];- mcpToolPolicies?: McpToolPolicy[];- projectTrusted?: boolean;- channelMode?: boolean;-}-interface PiHostRequest {type: "posthog_pi_host_request";id: string;@@ -35,7 +29,9 @@ function argumentValue(name: string): string | undefined {return index === -1 ? undefined : process.argv[index + 1];}-const bootstrap = JSON.parse(readFileSync(3, "utf8")) as PiRpcBootstrap;+const bootstrap = JSON.parse(+ readFileSync(3, "utf8"),+) as Partial<PiRpcBootstrap>;const providerOptions = bootstrap.providerOptions;if (!providerOptions?.apiKey) {throw new Error("Pi RPC host requires PostHog provider credentials");@@ -72,6 +68,17 @@ function requestMcpToolPermission(});}+const extensionFactories: Record<PiRuntimeExtension, InlineExtension> = {+ "repository-tools": createPiRepositoryToolsExtension(cwd),+ "auto-publish": {+ name: "posthog-auto-publish",+ factory: createAutoPublishExtension(),+ },+};+const runtimeExtensions = (bootstrap.extensions ?? []).map(+ (extension) => extensionFactories[extension],+);+const runtime = await createHarnessRuntime({cwd,sessionManager,@@ -79,13 +86,7 @@ const runtime = await createHarnessRuntime({cwd,bootstrap.projectTrusted ?? false,),- ...(bootstrap.channelMode- ? {- resourceLoaderOptions: {- extensionFactories: [createPiRepositoryToolsExtension(cwd)],- },- }- : {}),+ resourceLoaderOptions: { extensionFactories: runtimeExtensions },...providerOptions,runtimeMcpServers: bootstrap.runtimeMcpServers,mcpToolPolicies: bootstrap.mcpToolPolicies,diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts b/products/desktop/packages/agent/src/server/pi-agent-server.test.tsindex adf63d8cd67a..3d4fa92f6dd0 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.test.ts@@ -304,7 +304,7 @@ describe("PiAgentServer", () => {});});- it("injects auto-publish instructions into the first native Pi prompt", async () => {+ it("preserves the native Pi user prompt when auto-publish is enabled", async () => {const sendCommand = vi.fn(async (_command: Record<string, unknown>) => ({}),);@@ -325,79 +325,10 @@ describe("PiAgentServer", () => {};await server.executeCommand("user_message", { content: "fix it" });- await server.executeCommand("user_message", { content: "one more thing" });- expect(sendCommand.mock.calls[0]?.[0].message).toContain(- "auto-publish enabled",- );- expect(sendCommand.mock.calls[0]?.[0].message).toContain(- "gh pr create --draft",- );- expect(sendCommand.mock.calls[1]?.[0].message).toBe("one more thing");- });-- it("retries Pi auto-publish instructions when the first send fails", async () => {- const sendCommand = vi- .fn(async (_command: Record<string, unknown>) => ({}))- .mockRejectedValueOnce(new Error("send failed"));- const server = new PiAgentServer(- config({ autoPublish: true, createPr: true }),- ) as unknown as {- session: unknown;- executeCommand(- method: string,- params: Record<string, unknown>,- ): Promise<unknown>;- };- server.session = {- runtime: {- client: { getState: vi.fn(async () => ({ isStreaming: false })) },- sendCommand,- },- };-- await expect(- server.executeCommand("user_message", { content: "fix it" }),- ).rejects.toThrow("send failed");- await server.executeCommand("user_message", { content: "fix it" });-- expect(sendCommand.mock.calls[0]?.[0].message).toContain(- "auto-publish enabled",- );- expect(sendCommand.mock.calls[1]?.[0].message).toContain(- "auto-publish enabled",- );+ expect(sendCommand.mock.calls[0]?.[0].message).toBe("fix it");});- it.each([- [{ autoPublish: false }, "auto-publish disabled"],- [{ autoPublish: true, createPr: false }, "PR creation disabled"],- ])(- "does not inject Pi auto-publish instructions when %s",- async (overrides, _label) => {- const sendCommand = vi.fn(- async (_command: Record<string, unknown>) => ({}),- );- const server = new PiAgentServer(config(overrides)) as unknown as {- session: unknown;- executeCommand(- method: string,- params: Record<string, unknown>,- ): Promise<unknown>;- };- server.session = {- runtime: {- client: { getState: vi.fn(async () => ({ isStreaming: false })) },- sendCommand,- },- };-- await server.executeCommand("user_message", { content: "fix it" });-- expect(sendCommand.mock.calls[0]?.[0].message).toBe("fix it");- },- );-it("hydrates cloud artifacts into native Pi prompt inputs", async () => {const repositoryPath = await mkdtemp(join(tmpdir(), "pi-attachments-"));const sendCommand = vi.fn(diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex 5b1e30824842..de109655c6a6 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -24,6 +24,7 @@ import {createRuntimeMcpServers,createRuntimeMcpStdioServers,type PiRpcClient,+ type PiRuntimeExtension,} from "../pi/rpc-client";import { piRpcCommandSchema, type RpcCommand } from "../pi/rpc-transport";import { PiRuntime } from "../pi/runtime";@@ -127,7 +128,6 @@ export class PiAgentServer {private logFlushQueue: Promise<void> = Promise.resolve();private logFlushActive = false;private logFlushRequested = false;- private autoPublishInstructionDelivered = false;private readonly canceledSseControllers = new WeakSet<SseController>();private readonly pendingMcpPermissions = new Map<string,@@ -529,6 +529,13 @@ export class PiAgentServer {...createRuntimeMcpStdioServers(localTools ? [localTools] : []),};+ const extensions: PiRuntimeExtension[] = [];+ if (!this.config.repositoryPath) {+ extensions.push("repository-tools");+ }+ if (this.config.autoPublish === true && this.config.createPr !== false) {+ extensions.push("auto-publish");+ }const client = createPiRpcClient({cliPath: this.config.piRpcHostPath,cwd,@@ -543,7 +550,7 @@ export class PiAgentServer {this.config.apiUrl,),},- channelMode: !this.config.repositoryPath,+ extensions,});const runtime = new PiRuntime(client);const unsubscribeConversation = runtime.onConversationEvent((event) =>@@ -712,9 +719,6 @@ export class PiAgentServer {typeof params.messageId === "string" ? params.messageId : randomUUID(),params.steer === true,);- if (message.includesAutoPublishInstruction) {- this.autoPublishInstructionDelivered = true;- }return result;}@@ -724,7 +728,6 @@ export class PiAgentServer {): Promise<{content: string;images: Parameters<PiRpcClient["prompt"]>[1];- includesAutoPublishInstruction: boolean;}> {const images: NonNullable<Parameters<PiRpcClient["prompt"]>[1]> = [];const filePaths: string[] = [];@@ -768,38 +771,12 @@ export class PiAgentServer {const attachmentText = filePaths.length? `Attached files:\n${filePaths.map((filePath) => `- ${filePath}`).join("\n")}`: "";- const autoPublishInstruction = this.buildAutoPublishInstruction();return {- content: [autoPublishInstruction, content, attachmentText]- .filter(Boolean)- .join("\n\n"),+ content: [content, attachmentText].filter(Boolean).join("\n\n"),images,- includesAutoPublishInstruction: autoPublishInstruction !== null,};}- /**- * Pi does not consume AgentServer's ACP session system prompt. Carry the- * user's cloud auto-publish choice into its first prompt explicitly, just as- * prewarmed ACP sessions inject a first-message override after reading run- * state. Without this, Pi sees the task but never sees the instruction to- * publish the completed change.- */- private buildAutoPublishInstruction(): string | null {- if (- this.autoPublishInstructionDelivered ||- this.config.autoPublish !== true ||- this.config.createPr === false- ) {- return null;- }- return [- "IMPORTANT — the user has auto-publish enabled for this cloud run.",- "After completing and verifying code changes, create a `posthog/` branch, stage the changes, use the `git_signed_commit` tool to create a signed commit, and open a draft pull request with `gh pr create --draft`. Do not stop with local changes waiting for review.",- "Do not use `git commit` or `git push`. If this task already has an open pull request for the same work, continue on that PR instead of opening another one.",- ].join("\n");- }-private async dispatchUserMessage(runtime: PiRuntime,content: string,diff --git a/products/desktop/packages/harness/package.json b/products/desktop/packages/harness/package.jsonindex 9ddb5277d084..b4c4cc4dd891 100644--- a/products/desktop/packages/harness/package.json+++ b/products/desktop/packages/harness/package.json@@ -28,6 +28,14 @@"types": "./dist/extensions/registry.d.ts","import": "./dist/extensions/registry.js"},+ "./extensions/auto-publish": {+ "types": "./dist/extensions/auto-publish/index.d.ts",+ "import": "./dist/extensions/auto-publish/index.js"+ },+ "./extensions/auto-publish/*": {+ "types": "./dist/extensions/auto-publish/*.d.ts",+ "import": "./dist/extensions/auto-publish/*.js"+ },"./extensions/hog-branding": {"types": "./dist/extensions/hog-branding/extension.d.ts","import": "./dist/extensions/hog-branding/extension.js"diff --git a/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.ts b/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.tsnew file mode 100644index 000000000000..abf720f0726f--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/auto-publish/extension.test.ts@@ -0,0 +1,23 @@+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";+import { describe, expect, it } from "vitest";+import { createAutoPublishExtension } from "./extension";++describe("createAutoPublishExtension", () => {+ it("adds publishing instructions to Pi's system prompt", () => {+ const handlers = new Map<string, unknown>();+ const extension = createAutoPublishExtension();++ extension({+ on: (event: string, handler: unknown) => handlers.set(event, handler),+ } as unknown as ExtensionAPI);++ const beforeAgentStart = handlers.get("before_agent_start") as (event: {+ systemPrompt: string;+ }) => { systemPrompt: string };+ const result = beforeAgentStart({ systemPrompt: "Base system prompt" });++ expect(result.systemPrompt).toContain("Base system prompt");+ expect(result.systemPrompt).toContain("gh pr create --draft");+ expect(result.systemPrompt).toContain("git_signed_commit");+ });+});diff --git a/products/desktop/packages/harness/src/extensions/auto-publish/extension.ts b/products/desktop/packages/harness/src/extensions/auto-publish/extension.tsnew file mode 100644index 000000000000..977f06ed14cf--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/auto-publish/extension.ts@@ -0,0 +1,18 @@+import type {+ ExtensionAPI,+ ExtensionFactory,+} from "@earendil-works/pi-coding-agent";++const AUTO_PUBLISH_SYSTEM_PROMPT = [+ "The user has auto-publish enabled for this cloud run.",+ "After completing and verifying code changes, create a `posthog/` branch, stage the changes, use the `git_signed_commit` tool to create a signed commit, and open a draft pull request with `gh pr create --draft`. Do not stop with local changes waiting for review.",+ "Do not use `git commit` or `git push`. If this task already has an open pull request for the same work, continue on that PR instead of opening another one.",+].join("\n");++export function createAutoPublishExtension(): ExtensionFactory {+ return (pi: ExtensionAPI) => {+ pi.on("before_agent_start", (event) => ({+ systemPrompt: `${event.systemPrompt}\n\n${AUTO_PUBLISH_SYSTEM_PROMPT}`,+ }));+ };+}diff --git a/products/desktop/packages/harness/src/extensions/auto-publish/index.ts b/products/desktop/packages/harness/src/extensions/auto-publish/index.tsnew file mode 100644index 000000000000..85af170002ac--- /dev/null+++ b/products/desktop/packages/harness/src/extensions/auto-publish/index.ts@@ -0,0 +1 @@+export { createAutoPublishExtension } from "./extension";diff --git a/products/desktop/packages/harness/tsup.config.ts b/products/desktop/packages/harness/tsup.config.tsindex 39706204dcce..9b0cddbd82a5 100644--- a/products/desktop/packages/harness/tsup.config.ts+++ b/products/desktop/packages/harness/tsup.config.ts@@ -8,6 +8,8 @@ export default defineConfig({"src/runtime.ts","src/project-trust.ts","src/extensions/registry.ts",+ "src/extensions/auto-publish/extension.ts",+ "src/extensions/auto-publish/index.ts","src/extensions/hog-branding/extension.ts","src/extensions/hog-branding/index.ts","src/extensions/posthog-provider/extension.ts",