: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
feat(desktop): support enricher in pi (#83715)
Jonathan Mieloo7e3a39080168
diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.tsindex 1e3dad18786e..4d8c772cca92 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.test.ts@@ -35,9 +35,17 @@ describe("DesktopPiRpcClientFactory", () => {region: "eu" as const,})),getState: vi.fn(() => ({ currentProjectId: 1 })),+ getValidAccessToken: vi.fn(async () => ({+ accessToken: "access-token",+ apiHost: "https://eu.posthog.com",+ })),} as unknown as AgentAuth;const authProxy = {- start: vi.fn(async () => "http://127.0.0.1:1234"),+ start: vi.fn(async (url: string) =>+ url === "https://eu.posthog.com"+ ? "http://127.0.0.1:5678"+ : "http://127.0.0.1:1234",+ ),} as unknown as AuthProxyService;const policies = [{@@ -79,8 +87,16 @@ describe("DesktopPiRpcClientFactory", () => {getLlmGatewayUrl(getCloudUrlFromRegion("eu")),{ "X-PostHog-Project-Id": "1" },);+ expect(authProxy.start).toHaveBeenCalledWith("https://eu.posthog.com");expect(createPiRpcClient).toHaveBeenCalledWith({cwd: "/workspace",+ enrichment: {+ apiUrl: "http://127.0.0.1:5678",+ publicApiUrl: "https://eu.posthog.com",+ enableObjectReferences: true,+ projectId: 1,+ apiKey: "posthog-code-auth-proxy",+ },mcpToolPolicies: policies,runtimeMcpServers: {posthog: {diff --git a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.tsindex 3cf1bccd9f37..68d65ba44b91 100644--- a/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts+++ b/products/desktop/apps/code/src/main/platform-adapters/desktop-pi-rpc-client-factory.ts@@ -43,7 +43,11 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {if (!projectId) {throw new Error("Pi requires a selected PostHog project");}- const baseUrl = await this.getProxyUrl(credentials.region, projectId);+ const access = await this.auth.getValidAccessToken();+ const [baseUrl, enrichmentApiUrl] = await Promise.all([+ this.getProxyUrl(credentials.region, projectId),+ this.authProxy.start(access.apiHost),+ ]);const mcpConfiguration =await this.mcpServerSource.getMcpRuntimeConfiguration();@@ -54,6 +58,13 @@ export class DesktopPiRpcClientFactory implements PiRpcClientFactory {model: input.model,sessionFile: input.sessionFile,projectTrusted: input.projectTrusted,+ enrichment: {+ apiUrl: enrichmentApiUrl,+ publicApiUrl: access.apiHost,+ enableObjectReferences: true,+ projectId,+ apiKey: PROXY_API_KEY,+ },runtimeMcpServers,mcpToolPolicies: mcpConfiguration.policies,providerOptions: {diff --git a/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.tsnew file mode 100644index 000000000000..b69042e2fcd5--- /dev/null+++ b/products/desktop/apps/code/tests/e2e/tests/pi-enrichment.spec.ts@@ -0,0 +1,271 @@+import { existsSync } from "node:fs";+import { mkdir, writeFile } from "node:fs/promises";+import {+ createServer,+ type IncomingMessage,+ type ServerResponse,+} from "node:http";+import path from "node:path";+import type { PiRpcClient } from "@posthog/agent/pi/rpc-client";+import { expect, test } from "../fixtures/electron";++const HOME_ENVIRONMENT_KEYS = [+ "APPDATA",+ "HOME",+ "LOCALAPPDATA",+ "USERPROFILE",+ "XDG_CONFIG_HOME",+] as const;++function createAnthropicStream(content: "tool" | "text"): string {+ const messageStart = {+ type: "message_start",+ message: {+ id: `msg_${content}`,+ type: "message",+ role: "assistant",+ content: [],+ model: "claude-haiku-4-5",+ stop_reason: null,+ stop_sequence: null,+ usage: { input_tokens: 10, output_tokens: 0 },+ },+ };+ const events =+ content === "tool"+ ? [+ messageStart,+ {+ type: "content_block_start",+ index: 0,+ content_block: {+ type: "tool_use",+ id: "toolu_read_1",+ name: "read",+ input: {},+ },+ },+ {+ type: "content_block_delta",+ index: 0,+ delta: {+ type: "input_json_delta",+ partial_json: JSON.stringify({ path: "example.ts" }),+ },+ },+ { type: "content_block_stop", index: 0 },+ {+ type: "message_delta",+ delta: { stop_reason: "tool_use", stop_sequence: null },+ usage: { output_tokens: 10 },+ },+ { type: "message_stop" },+ ]+ : [+ messageStart,+ {+ type: "content_block_start",+ index: 0,+ content_block: { type: "text", text: "" },+ },+ {+ type: "content_block_delta",+ index: 0,+ delta: { type: "text_delta", text: "Enrichment observed." },+ },+ { type: "content_block_stop", index: 0 },+ {+ type: "message_delta",+ delta: { stop_reason: "end_turn", stop_sequence: null },+ usage: { output_tokens: 5 },+ },+ { type: "message_stop" },+ ];++ return events+ .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)+ .join("");+}++async function readJson(request: IncomingMessage): Promise<unknown> {+ const chunks: Buffer[] = [];+ for await (const chunk of request) {+ chunks.push(Buffer.from(chunk));+ }++ return JSON.parse(Buffer.concat(chunks).toString("utf8"));+}++function sendJson(response: ServerResponse, data: unknown): void {+ response.writeHead(200, { "Content-Type": "application/json" });+ response.end(JSON.stringify(data));+}++test.describe("Pi enrichment", () => {+ test("enriches a read result through the bundled RPC host", async ({+ electronApp,+ }) => {+ const { e2eHome, resourcesPath } = await electronApp.evaluate(+ async ({ app }) => ({+ e2eHome: process.env.HOME ?? app.getPath("home"),+ resourcesPath: process.resourcesPath,+ }),+ );+ const rpcHostPath = path.join(+ resourcesPath,+ "app.asar.unpacked",+ ".vite",+ "build",+ "rpc-host.js",+ );+ expect(existsSync(rpcHostPath)).toBe(true);++ const workspace = path.join(e2eHome, "enrichment-workspace");+ await mkdir(workspace, { recursive: true });+ await writeFile(+ path.join(workspace, "example.ts"),+ 'posthog.capture("checkout_completed");\n',+ );++ let initialModelRequest = "";+ let enrichedModelRequest = "";+ let eventDefinitionRequests = 0;+ let eventStatsRequests = 0;+ const server = createServer(async (request, response) => {+ const url = new URL(request.url ?? "/", "http://127.0.0.1");++ if (request.method === "GET" && url.pathname === "/v1/models") {+ sendJson(response, {+ data: [+ {+ id: "claude-haiku-4-5",+ owned_by: "anthropic",+ context_window: 200000,+ supports_vision: true,+ },+ ],+ });+ return;+ }++ if (request.method === "POST" && url.pathname === "/v1/messages") {+ const body = await readJson(request);+ const serialized = JSON.stringify(body);+ const hasToolResult = serialized.includes('"tool_result"');+ if (hasToolResult) {+ enrichedModelRequest = serialized;+ } else {+ initialModelRequest = serialized;+ }+ response.writeHead(200, {+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ });+ response.end(createAnthropicStream(hasToolResult ? "text" : "tool"));+ return;+ }++ if (+ request.method === "GET" &&+ url.pathname === "/api/projects/1/event_definitions/"+ ) {+ eventDefinitionRequests += 1;+ sendJson(response, {+ results: [+ {+ id: "event-1",+ name: "checkout_completed",+ tags: ["revenue"],+ last_seen_at: "2026-08-13T12:00:00Z",+ verified: true,+ },+ ],+ });+ return;+ }++ if (+ request.method === "POST" &&+ url.pathname === "/api/projects/1/query/"+ ) {+ eventStatsRequests += 1;+ sendJson(response, {+ results: [["checkout_completed", 321, 87, "2026-08-13T12:00:00Z"]],+ });+ return;+ }++ response.writeHead(404);+ response.end();+ });++ await new Promise<void>((resolveListening) => {+ server.listen(0, "127.0.0.1", resolveListening);+ });+ const address = server.address();+ if (!address || typeof address === "string") {+ throw new Error("Fake PostHog server did not bind a TCP port");+ }++ const previousEnvironment = new Map(+ HOME_ENVIRONMENT_KEYS.map((key) => [key, process.env[key]]),+ );+ for (const key of HOME_ENVIRONMENT_KEYS) {+ process.env[key] = e2eHome;+ }++ const baseUrl = `http://127.0.0.1:${address.port}`;+ let client: PiRpcClient | undefined;+ try {+ const { createPiRpcClient } = await import(+ "@posthog/agent/pi/rpc-client"+ );+ client = createPiRpcClient({+ cliPath: rpcHostPath,+ cwd: workspace,+ model: "claude-haiku-4-5",+ projectTrusted: false,+ providerOptions: { apiKey: "gateway-test-key", baseUrl },+ enrichment: {+ apiUrl: baseUrl,+ publicApiUrl: "https://us.posthog.com",+ enableObjectReferences: true,+ projectId: 1,+ apiKey: "posthog-test-key",+ },+ });+ await client.start();+ const settled = client.waitForIdle();+ await client.prompt("Read example.ts and report what you find.");+ await settled;++ expect(eventDefinitionRequests).toBe(1);+ expect(eventStatsRequests).toBe(1);+ expect(initialModelRequest).toContain("## Rich output in replies");+ expect(initialModelRequest).toContain('<kind id=\\"...\\">');+ expect(enrichedModelRequest).toContain(+ '[PostHog] Event: \\"checkout_completed\\"',+ );+ expect(enrichedModelRequest).toContain("321 events");+ expect(enrichedModelRequest).toContain("87 users");+ } finally {+ await client?.stop();+ for (const [key, value] of previousEnvironment) {+ if (value === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = value;+ }+ }+ await new Promise<void>((resolveClosed, rejectClosed) => {+ server.close((error) => {+ if (error) {+ rejectClosed(error);+ } else {+ resolveClosed();+ }+ });+ });+ }+ });+});diff --git a/products/desktop/packages/agent/src/enrichment/file-enricher.test.ts b/products/desktop/packages/agent/src/enrichment/file-enricher.test.tsindex d53d04eea04f..dbb480af91be 100644--- a/products/desktop/packages/agent/src/enrichment/file-enricher.test.ts+++ b/products/desktop/packages/agent/src/enrichment/file-enricher.test.ts@@ -14,13 +14,16 @@ function makeDeps(overrides: {deps: FileEnrichmentDeps;parseSpy: ReturnType<typeof vi.fn>;enrichFromApiSpy: ReturnType<typeof vi.fn>;+ toInlineCommentsSpy: ReturnType<typeof vi.fn>;getApiKeySpy: ReturnType<typeof vi.fn>;findImportsSpy: ReturnType<typeof vi.fn>;getWrappersSpy: ReturnType<typeof vi.fn>;} {+ const toInlineCommentsSpy = vi.fn(+ () => overrides.toInlineCommentsReturn ?? "enriched content",+ );const enrichFromApiSpy = vi.fn(async () => ({- toInlineComments: () =>- overrides.toInlineCommentsReturn ?? "enriched content",+ toInlineComments: toInlineCommentsSpy,}));const parseSpy = vi.fn(async () => {@@ -58,6 +61,7 @@ function makeDeps(overrides: {deps,parseSpy,enrichFromApiSpy,+ toInlineCommentsSpy,getApiKeySpy,findImportsSpy,getWrappersSpy,@@ -277,7 +281,7 @@ describe("enrichFileForAgent", () => {});test("returns enriched string when happy path completes", async () => {- const { deps, enrichFromApiSpy } = makeDeps({+ const { deps, enrichFromApiSpy, toInlineCommentsSpy } = makeDeps({toInlineCommentsReturn: "posthog.capture('x'); // [PostHog] Event: \"x\"",});const result = await enrichFileForAgent(@@ -286,6 +290,10 @@ describe("enrichFileForAgent", () => {"posthog.capture('x');",);expect(result).toBe("posthog.capture('x'); // [PostHog] Event: \"x\"");+ expect(toInlineCommentsSpy).toHaveBeenCalledWith({+ includeEventDescriptions: false,+ includeExperimentNames: false,+ });expect(enrichFromApiSpy).toHaveBeenCalledWith(expect.objectContaining({apiKey: "phx_test",diff --git a/products/desktop/packages/agent/src/enrichment/file-enricher.ts b/products/desktop/packages/agent/src/enrichment/file-enricher.tsindex 4bce2658e07d..b37d3000fbcb 100644--- a/products/desktop/packages/agent/src/enrichment/file-enricher.ts+++ b/products/desktop/packages/agent/src/enrichment/file-enricher.ts@@ -78,11 +78,15 @@ export async function enrichFileForAgent(const enriched = await parsed.enrichFromApi({apiKey,host: deps.apiConfig.apiUrl,+ publicHost: deps.apiConfig.publicApiUrl,projectId: deps.apiConfig.projectId,timeoutMs: 5_000,});- const annotated = enriched.toInlineComments();+ const annotated = enriched.toInlineComments({+ includeEventDescriptions: false,+ includeExperimentNames: false,+ });if (annotated === content) {deps.logger?.debug("File enrichment produced no changes", {filePath,diff --git a/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts b/products/desktop/packages/agent/src/pi/enrichment-extension.test.tsnew file mode 100644index 000000000000..8b08e55166c2--- /dev/null+++ b/products/desktop/packages/agent/src/pi/enrichment-extension.test.ts@@ -0,0 +1,123 @@+import type {+ ExtensionAPI,+ ExtensionContext,+ ToolResultEvent,+} from "@earendil-works/pi-coding-agent";+import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";+import { afterEach, describe, expect, it, vi } from "vitest";+import { createPiEnrichmentExtension } from "./enrichment-extension";++type ToolResultPatch = { content?: ToolResultEvent["content"] };+type BeforeAgentStartHandler = (event: { systemPrompt: string }) => {+ systemPrompt: string;+};+type ToolResultHandler = (+ event: ToolResultEvent,+ ctx: ExtensionContext,+) => Promise<ToolResultPatch | undefined> | ToolResultPatch | undefined;++describe("createPiEnrichmentExtension", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("adds live PostHog metadata to Pi read results", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ const data = url.includes("event_definitions")+ ? {+ results: [+ {+ id: "event-1",+ name: "checkout",+ tags: [],+ last_seen_at: "2026-01-01T00:00:00Z",+ verified: true,+ },+ ],+ }+ : {+ results: [["checkout", 120, 40, "2026-01-01T00:00:00Z"]],+ };+ return new Response(JSON.stringify(data), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }),+ );++ let handler: ToolResultHandler | undefined;+ let beforeAgentStartHandler: BeforeAgentStartHandler | undefined;+ const extension = createPiEnrichmentExtension({+ apiUrl: "https://us.posthog.com",+ enableObjectReferences: true,+ projectId: 1,+ apiKey: "token",+ });+ await extension.factory({+ on: (+ event: string,+ registeredHandler: ToolResultHandler | BeforeAgentStartHandler,+ ) => {+ if (event === "tool_result") {+ handler = registeredHandler as ToolResultHandler;+ }+ if (event === "before_agent_start") {+ beforeAgentStartHandler =+ registeredHandler as BeforeAgentStartHandler;+ }+ },+ } as unknown as ExtensionAPI);++ expect(+ beforeAgentStartHandler?.({ systemPrompt: "Base system prompt" })+ .systemPrompt,+ ).toContain(RICH_OUTPUT_TAGS_PROMPT);++ const result = await handler?.(+ {+ type: "tool_result",+ toolCallId: "read-1",+ toolName: "read",+ input: { path: "/tmp/example.ts" },+ content: [{ type: "text", text: 'posthog.capture("checkout");' }],+ details: undefined,+ isError: false,+ },+ { cwd: "/tmp" } as ExtensionContext,+ );++ expect(result?.content).toEqual([+ {+ type: "text",+ text: expect.stringContaining(+ '[PostHog] Event: "checkout" — (verified) — 120 events — 40 users',+ ),+ },+ ]);+ });++ it("does not add object-tag guidance unless enabled", async () => {+ let beforeAgentStartHandler: BeforeAgentStartHandler | undefined;+ const extension = createPiEnrichmentExtension({+ apiUrl: "https://us.posthog.com",+ projectId: 1,+ apiKey: "token",+ });+ await extension.factory({+ on: (+ event: string,+ registeredHandler: ToolResultHandler | BeforeAgentStartHandler,+ ) => {+ if (event === "before_agent_start") {+ beforeAgentStartHandler =+ registeredHandler as BeforeAgentStartHandler;+ }+ },+ } as unknown as ExtensionAPI);++ expect(beforeAgentStartHandler).toBeUndefined();+ });+});diff --git a/products/desktop/packages/agent/src/pi/enrichment-extension.ts b/products/desktop/packages/agent/src/pi/enrichment-extension.tsnew file mode 100644index 000000000000..ff3dc2afbe71--- /dev/null+++ b/products/desktop/packages/agent/src/pi/enrichment-extension.ts@@ -0,0 +1,82 @@+import { resolve } from "node:path";+import {+ type ExtensionAPI,+ type ExtensionFactory,+ isReadToolResult,+} from "@earendil-works/pi-coding-agent";+import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";+import {+ createEnrichment,+ enrichFileForAgent,+} from "../enrichment/file-enricher";++export interface PiEnrichmentConfig {+ apiUrl: string;+ publicApiUrl?: string;+ enableObjectReferences?: boolean;+ projectId: number;+ apiKey: string;+}++export function createPiEnrichmentExtension(config: PiEnrichmentConfig): {+ name: string;+ factory: ExtensionFactory;+} {+ return {+ name: "posthog-enricher",+ factory: (pi: ExtensionAPI) => {+ if (config.enableObjectReferences) {+ pi.on("before_agent_start", (event) => ({+ systemPrompt: `${event.systemPrompt}\n\n## Rich output in replies\n${RICH_OUTPUT_TAGS_PROMPT}`,+ }));+ }++ const enrichment = createEnrichment({+ apiUrl: config.apiUrl,+ publicApiUrl: config.publicApiUrl,+ projectId: config.projectId,+ getApiKey: () => config.apiKey,+ });+ if (!enrichment) {+ return;+ }++ pi.on("tool_result", async (event, ctx) => {+ if (!isReadToolResult(event) || event.isError) {+ return;+ }++ const rawPath = event.input.path;+ if (typeof rawPath !== "string") {+ return;+ }++ const textIndex = event.content.findIndex(+ (content) => content.type === "text",+ );+ const textContent = event.content[textIndex];+ if (!textContent || textContent.type !== "text") {+ return;+ }++ const filePath = resolve(ctx.cwd, rawPath.replace(/^@/, ""));+ const enriched = await enrichFileForAgent(+ enrichment.deps,+ filePath,+ textContent.text,+ );+ if (!enriched) {+ return;+ }++ const content = [...event.content];+ content[textIndex] = { type: "text", text: enriched };+ return { content };+ });++ pi.on("session_shutdown", () => {+ enrichment.dispose();+ });+ },+ };+}diff --git a/products/desktop/packages/agent/src/pi/rpc-client.test.ts b/products/desktop/packages/agent/src/pi/rpc-client.test.tsindex 901b8eefac5a..5cb32cbf44db 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.test.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.test.ts@@ -108,6 +108,12 @@ process.stdin.resume();projectTrusted: true,extensions: ["auto-publish"],providerOptions: { apiKey: "proxy-key" },+ enrichment: {+ apiUrl: "http://127.0.0.1:5678",+ publicApiUrl: "https://us.posthog.com",+ projectId: 2,+ apiKey: "enrichment-proxy-key",+ },});try {@@ -116,6 +122,12 @@ process.stdin.resume();await expect(readFile(capturePath, "utf8")).resolves.toBe(JSON.stringify({providerOptions: { apiKey: "proxy-key" },+ enrichment: {+ apiUrl: "http://127.0.0.1:5678",+ publicApiUrl: "https://us.posthog.com",+ projectId: 2,+ apiKey: "enrichment-proxy-key",+ },projectTrusted: true,extensions: ["auto-publish"],}),diff --git a/products/desktop/packages/agent/src/pi/rpc-client.ts b/products/desktop/packages/agent/src/pi/rpc-client.tsindex 6d33fccfc2d9..0ea88b171f31 100644--- a/products/desktop/packages/agent/src/pi/rpc-client.ts+++ b/products/desktop/packages/agent/src/pi/rpc-client.ts@@ -16,6 +16,7 @@ import type {McpToolPermissionRequest,McpToolPolicy,} from "@posthog/shared";+import type { PiEnrichmentConfig } from "./enrichment-extension";import { safePiEnvironment } from "./rpc-environment";import type {PiExtensionEvent,@@ -50,6 +51,7 @@ export interface PiRpcProviderOptions {export interface PiRpcBootstrap {providerOptions: PiRpcProviderOptions;+ enrichment?: PiEnrichmentConfig;runtimeMcpServers?: PiRuntimeMcpServers;mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;@@ -431,6 +433,7 @@ export type PiRpcClientOptions = Pick<> & {sessionFile?: string;providerOptions: PiRpcProviderOptions;+ enrichment?: PiEnrichmentConfig;runtimeMcpServers?: PiRuntimeMcpServers;mcpToolPolicies?: McpToolPolicy[];projectTrusted?: boolean;@@ -441,6 +444,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {const {sessionFile,providerOptions,+ enrichment,runtimeMcpServers,mcpToolPolicies,projectTrusted,@@ -460,6 +464,7 @@ export function createPiRpcClient(options: PiRpcClientOptions): PiRpcClient {},{providerOptions,+ enrichment,runtimeMcpServers,mcpToolPolicies,projectTrusted: projectTrusted ?? false,diff --git a/products/desktop/packages/agent/src/pi/rpc-host.ts b/products/desktop/packages/agent/src/pi/rpc-host.tsindex 2de5282f3152..a3495a1b8dee 100644--- a/products/desktop/packages/agent/src/pi/rpc-host.ts+++ b/products/desktop/packages/agent/src/pi/rpc-host.ts@@ -10,6 +10,7 @@ import type {McpToolPermissionDecision,McpToolPermissionRequest,} from "@posthog/shared";+import { createPiEnrichmentExtension } from "./enrichment-extension";import {POSTHOG_PI_QUEUE_ENTRY_TYPE,readPersistedPiQueue,@@ -78,6 +79,9 @@ const extensionFactories: Record<PiRuntimeExtension, InlineExtension> = {const runtimeExtensions = (bootstrap.extensions ?? []).map((extension) => extensionFactories[extension],);+if (bootstrap.enrichment) {+ runtimeExtensions.push(createPiEnrichmentExtension(bootstrap.enrichment));+}const runtime = await createHarnessRuntime({cwd,diff --git a/products/desktop/packages/agent/src/server/pi-agent-server.ts b/products/desktop/packages/agent/src/server/pi-agent-server.tsindex f34b90705502..b42d1d1654ae 100644--- a/products/desktop/packages/agent/src/server/pi-agent-server.ts+++ b/products/desktop/packages/agent/src/server/pi-agent-server.ts@@ -541,6 +541,11 @@ export class PiAgentServer {cwd,model: this.config.model,sessionFile: restoredSessionFile,+ enrichment: {+ apiUrl: this.config.apiUrl,+ projectId: this.config.projectId,+ apiKey: this.config.apiKey,+ },runtimeMcpServers,mcpToolPolicies: mcpConfiguration.policies,providerOptions: {diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.tsindex b8167cd2392e..2e98c6a95a49 100644--- a/products/desktop/packages/agent/tsup.config.ts+++ b/products/desktop/packages/agent/tsup.config.ts@@ -48,9 +48,17 @@ function copyAssets() {const distDir = resolve(import.meta.dirname, "dist");const templatesDir = resolve(distDir, "templates");const claudeCliDir = resolve(distDir, "claude-cli");+ const enricherGrammarsSource = resolve(+ import.meta.dirname,+ "../enricher/grammars",+ );+ const enricherGrammarsTarget = resolve(distDir, "grammars");mkdirSync(templatesDir, { recursive: true });mkdirSync(claudeCliDir, { recursive: true });+ cpSync(enricherGrammarsSource, enricherGrammarsTarget, {+ recursive: true,+ });const srcTemplatesDir = resolve(import.meta.dirname, "src/templates");if (existsSync(srcTemplatesDir)) {@@ -78,6 +86,9 @@ function copyAssets() {);}+const nodeEsmBanner =+ 'import { createRequire as __createRequire } from "node:module"; import { fileURLToPath as __fileURLToPath } from "node:url"; import { dirname as __pathDirname } from "node:path"; const require = __createRequire(import.meta.url); const __filename = __fileURLToPath(import.meta.url); const __dirname = __pathDirname(__filename);';+const sharedOptions = {sourcemap: true,splitting: false,@@ -158,9 +169,7 @@ export default defineConfig([// dynamic `require(...)` calls throw in ESM output unless a real require// exists. Entries spawned directly by node (local-tools-mcp-server.js)// crash at import time without this shim.- banner: {- js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);',- },+ banner: { js: nodeEsmBanner },...sharedOptions,onSuccess: async () => {copyAssets();@@ -187,9 +196,7 @@ export default defineConfig([format: ["esm"],dts: false,clean: false,- banner: {- js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);',- },+ banner: { js: nodeEsmBanner },...sharedOptions,noExternal: [/^(?!node:)/],external: [...builtinModules, ...builtinModules.map((m) => `node:${m}`)],diff --git a/products/desktop/packages/enricher/README.md b/products/desktop/packages/enricher/README.mdindex 9dfae9129d8c..10931f29e161 100644--- a/products/desktop/packages/enricher/README.md+++ b/products/desktop/packages/enricher/README.md@@ -130,10 +130,13 @@ Returned by `enrich()` or `enrichFromApi()`. Detection combined with PostHog coninterface EnricherApiConfig {apiKey: string;host: string; // e.g. "https://us.posthog.com"+ publicHost?: string;projectId: number;}```+Set `publicHost` when API requests use a private proxy but annotation links should use the public PostHog URL.+### `EnrichedFlag````typescriptdiff --git a/products/desktop/packages/enricher/src/comment-formatter.test.ts b/products/desktop/packages/enricher/src/comment-formatter.test.tsindex 11c1b32955bb..a220e47fc659 100644--- a/products/desktop/packages/enricher/src/comment-formatter.test.ts+++ b/products/desktop/packages/enricher/src/comment-formatter.test.ts@@ -41,6 +41,23 @@ describe("formatInlineComments", () => {);});+ test("replaces an existing inline annotation", () => {+ const source = `posthog.capture('a'); // [PostHog] Event: "old"`;+ const items = [eventItem("a", 0, false)];+ const events = new Map([["a", enrichedEvent("a")]]);+ const out = formatInlineComments(+ source,+ "javascript",+ items,+ new Map<string, EnrichedFlag>(),+ events,+ );++ expect(out.match(/\[PostHog\]/g)).toHaveLength(1);+ expect(out).toContain(`Event: "a" \u2014 (verified)`);+ expect(out).not.toContain(`Event: "old"`);+ });+test("pure JSX line uses {/* */} suffix", () => {const source = `<Button onClick={() => track('a')} />`;const items = [eventItem("a", 0, true)];@@ -57,6 +74,30 @@ describe("formatInlineComments", () => {);});+ test("keeps project metadata inside the generated comment", () => {+ const source = `<Button onClick={() => track('a')} />`;+ const items = [eventItem("a", 0, true)];+ const events = new Map([+ [+ "a",+ {+ ...enrichedEvent("a"),+ definition: { description: "details\n*/} injected" },+ } as EnrichedEvent,+ ],+ ]);+ const out = formatInlineComments(+ source,+ "javascriptreact",+ items,+ new Map<string, EnrichedFlag>(),+ events,+ );++ expect(out.split("\n")).toHaveLength(1);+ expect(out).toContain("details * /} injected");+ });+test("mixed JSX and JS items on the same line fall back to a leading JSX comment", () => {const source = ` <Button onClick={() => track('a')} />; posthog.capture('b');`;const items = [eventItem("a", 0, true), eventItem("b", 0, false)];@@ -79,6 +120,29 @@ describe("formatInlineComments", () => {expect(lines[1]).toBe(source);});+ test("replaces an existing mixed-context leading annotation", () => {+ const source = [+ `{/* [PostHog] Event: "old" */}`,+ `<Button onClick={() => track('a')} />; posthog.capture('b');`,+ ].join("\n");+ const items = [eventItem("a", 1, true), eventItem("b", 1, false)];+ const events = new Map([+ ["a", enrichedEvent("a")],+ ["b", enrichedEvent("b")],+ ]);+ const out = formatInlineComments(+ source,+ "typescriptreact",+ items,+ new Map<string, EnrichedFlag>(),+ events,+ );++ expect(out.split("\n")).toHaveLength(2);+ expect(out.match(/\[PostHog\]/g)).toHaveLength(1);+ expect(out).not.toContain(`Event: "old"`);+ });+test("multiple mixed-context lines insert leading comments without shifting indices", () => {const source = [`<A onClick={() => track('a')} />; posthog.capture('b');`,diff --git a/products/desktop/packages/enricher/src/comment-formatter.ts b/products/desktop/packages/enricher/src/comment-formatter.tsindex 35c23724b269..c08a667f4f02 100644--- a/products/desktop/packages/enricher/src/comment-formatter.ts+++ b/products/desktop/packages/enricher/src/comment-formatter.ts@@ -7,8 +7,15 @@ function commentPrefix(languageId: string): string {return "//";}+function sanitizeCommentValue(value: string): string {+ return value+ .replace(/[\r\n\u2028\u2029]+/g, " ")+ .replaceAll("*/", "* /")+ .trim();+}+function formatFlagComment(flag: EnrichedFlag): string {- const parts: string[] = [`Flag: "${flag.flagKey}"`];+ const parts: string[] = [`Flag: "${sanitizeCommentValue(flag.flagKey)}"`];if (!flag.flag) {parts.push("not in PostHog");@@ -30,20 +37,21 @@ function formatFlagComment(flag: EnrichedFlag): string {}if (flag.experiment) {const status = flag.experiment.end_date ? "complete" : "running";- parts.push(`Experiment: "${flag.experiment.name}" (${status})`);+ const experimentName = sanitizeCommentValue(flag.experiment.name);+ parts.push(`Experiment: "${experimentName}" (${status})`);}if (flag.staleness) {parts.push(`STALE (${flag.staleness})`);}if (flag.url) {- parts.push(flag.url);+ parts.push(sanitizeCommentValue(flag.url));}return parts.join(" \u2014 ");}function formatEventComment(event: EnrichedEvent): string {- const parts: string[] = [`Event: "${event.eventName}"`];+ const parts: string[] = [`Event: "${sanitizeCommentValue(event.eventName)}"`];if (event.verified) {parts.push("(verified)");}@@ -54,11 +62,18 @@ function formatEventComment(event: EnrichedEvent): string {parts.push(`${event.stats.uniqueUsers.toLocaleString()} users`);}if (event.definition?.description) {- parts.push(event.definition.description);+ parts.push(sanitizeCommentValue(event.definition.description));}return parts.join(" \u2014 ");}+function stripExistingInlineAnnotation(line: string, isJsx: boolean): string {+ const pattern = isJsx+ ? /\s+\{\/\* \[PostHog\].* \*\/\}\s*$/+ : /\s+(?:\/\/|#) \[PostHog\].*$/;+ return line.replace(pattern, "");+}+function buildCommentBody(item: EnrichedListItem,enrichedFlags: Map<string, EnrichedFlag>,@@ -73,15 +88,15 @@ function buildCommentBody(if (event) {body = formatEventComment(event);} else if (item.detail) {- body = `Event: ${item.detail}`;+ body = `Event: ${sanitizeCommentValue(item.detail)}`;}} else if (item.type === "init") {- body = `Init: token "${item.name}"`;+ body = `Init: token "${sanitizeCommentValue(item.name)}"`;}if (!body) return null;if (item.viaWrapper) {- body = `${body} (via ${item.viaWrapper})`;+ body = `${body} (via ${sanitizeCommentValue(item.viaWrapper)})`;}return body;}@@ -165,12 +180,24 @@ export function formatInlineComments(const suffix = isJsx? ` {/* [PostHog] ${joined} */}`: ` ${prefix} [PostHog] ${joined}`;- lines[lineIdx] = `${lines[lineIdx]}${suffix}`;+ const sourceLine = stripExistingInlineAnnotation(+ lines[lineIdx] ?? "",+ isJsx,+ );+ lines[lineIdx] = `${sourceLine}${suffix}`;}leadingInserts.sort((a, b) => b.atLine - a.atLine);for (const { atLine, text } of leadingInserts) {- lines.splice(atLine, 0, text);+ const previousLine = lines[atLine - 1]?.trim() ?? "";+ const hasExistingAnnotation = /^\{\/\* \[PostHog\].* \*\/\}$/.test(+ previousLine,+ );+ if (hasExistingAnnotation) {+ lines[atLine - 1] = text;+ } else {+ lines.splice(atLine, 0, text);+ }}return lines.join("\n");diff --git a/products/desktop/packages/enricher/src/enriched-result.ts b/products/desktop/packages/enricher/src/enriched-result.tsindex cebf48459258..8b47a28d2b94 100644--- a/products/desktop/packages/enricher/src/enriched-result.ts+++ b/products/desktop/packages/enricher/src/enriched-result.ts@@ -171,15 +171,27 @@ export class EnrichedResult {);}- toInlineComments(): string {+ toInlineComments(+ options: {+ includeEventDescriptions?: boolean;+ includeExperimentNames?: boolean;+ } = {},+ ): string {+ const includeEventDescriptions = options.includeEventDescriptions ?? true;+ const includeExperimentNames = options.includeExperimentNames ?? true;const flagLookup = new Map<string, EnrichedFlag>();- for (const f of this.flags) {- flagLookup.set(f.flagKey, f);+ for (const flag of this.flags) {+ const experiment = includeExperimentNames ? flag.experiment : undefined;+ flagLookup.set(flag.flagKey, { ...flag, experiment });}const eventLookup = new Map<string, EnrichedEvent>();- for (const e of this.events) {- eventLookup.set(e.eventName, e);+ for (const event of this.events) {+ const definition =+ includeEventDescriptions || !event.definition+ ? event.definition+ : { ...event.definition, description: null };+ eventLookup.set(event.eventName, { ...event, definition });}return formatInlineComments(diff --git a/products/desktop/packages/enricher/src/enricher.test.ts b/products/desktop/packages/enricher/src/enricher.test.tsindex 1f801d3d543a..a68abd75a763 100644--- a/products/desktop/packages/enricher/src/enricher.test.ts+++ b/products/desktop/packages/enricher/src/enricher.test.ts@@ -239,6 +239,52 @@ describeWithGrammars("PostHogEnricher", () => {expect(enriched.events[0].verified).toBe(true);});+ test("omits descriptions from inline comments when requested", async () => {+ const code = `posthog.capture('purchase');`;+ const result = await enricher.parse(code, "javascript");++ mockApiResponses({+ eventDefs: [+ makeEventDef("purchase", {+ description: "Project-controlled event description",+ }),+ ],+ });+ const enriched = await result.enrichFromApi(API_CONFIG);++ expect(enriched.events[0].definition?.description).toBe(+ "Project-controlled event description",+ );+ expect(enriched.toInlineComments()).toContain(+ "Project-controlled event description",+ );+ expect(+ enriched.toInlineComments({ includeEventDescriptions: false }),+ ).not.toContain("Project-controlled event description");+ });++ test("omits experiment names from inline comments when requested", async () => {+ const code = `posthog.getFeatureFlag('experiment-flag');`;+ const result = await enricher.parse(code, "javascript");++ mockApiResponses({+ flags: [makeFlag("experiment-flag")],+ experiments: [+ makeExperiment("experiment-flag", {+ name: "Project-controlled experiment name",+ }),+ ],+ });+ const enriched = await result.enrichFromApi(API_CONFIG);++ expect(enriched.toInlineComments()).toContain(+ "Project-controlled experiment name",+ );+ expect(+ enriched.toInlineComments({ includeExperimentNames: false }),+ ).not.toContain("Project-controlled experiment name");+ });+test("toList returns enriched items", async () => {const code = [`posthog.capture('purchase');`,@@ -341,6 +387,13 @@ describeWithGrammars("PostHogEnricher", () => {});const enriched = await result.enrichFromApi(API_CONFIG);+ const eventDefinitionCall = vi+ .mocked(fetch)+ .mock.calls.find(([url]) =>+ String(url).includes("/event_definitions/"),+ );+ expect(String(eventDefinitionCall?.[0])).toContain("names=a%2Cb");+const annotated = enriched.toInlineComments();const lines = annotated.split("\n");@@ -350,6 +403,40 @@ describeWithGrammars("PostHogEnricher", () => {expect(lines[0]).toContain(" | ");});+ test("falls back to exact searches when a multi-name response omits definitions", async () => {+ const code = `posthog.capture('a');\nposthog.capture('b');\nposthog.capture('c');`;+ const result = await enricher.parse(code, "javascript");+ const definitions = new Map([+ ["a", makeEventDef("a", { verified: true })],+ ["b", makeEventDef("b", { verified: true })],+ ]);+ const mockFetch = vi.fn(async (input: string | URL) => {+ const url = new URL(String(input));+ if (url.pathname.endsWith("/event_definitions/")) {+ const search = url.searchParams.get("search");+ if (search === "c") {+ return new Response("unavailable", { status: 503 });+ }+ const definition = search ? definitions.get(search) : undefined;+ return Response.json({ results: definition ? [definition] : [] });+ }+ return Response.json({ results: [] });+ });+ vi.stubGlobal("fetch", mockFetch);++ const enriched = await result.enrichFromApi(API_CONFIG);+ const annotated = enriched.toInlineComments();++ expect(annotated).toContain(`Event: "a" \u2014 (verified)`);+ expect(annotated).toContain(`Event: "b" \u2014 (verified)`);+ expect(annotated).toContain(`Event: "c"`);+ expect(+ mockFetch.mock.calls.filter(([input]) =>+ String(input).includes("/event_definitions/"),+ ),+ ).toHaveLength(4);+ });+test("enrichedEvents surfaces stats, lastSeenAt, and tags", async () => {const code = `posthog.capture('purchase');`;const result = await enricher.parse(code, "javascript");@@ -413,6 +500,22 @@ describeWithGrammars("PostHogEnricher", () => {});});+ test("uses the public host for flag links", async () => {+ const code = `posthog.getFeatureFlag('my-flag');`;+ const result = await enricher.parse(code, "javascript");++ mockApiResponses({ flags: [makeFlag("my-flag", { id: 42 })] });+ const enriched = await result.enrichFromApi({+ ...API_CONFIG,+ host: "http://127.0.0.1:1234/private-token",+ publicHost: "https://test.posthog.com",+ });++ expect(enriched.flags[0].url).toBe(+ "https://test.posthog.com/project/1/feature_flags/42",+ );+ });+test("toComments renders rich flag line with url, active, rollout, evals", async () => {const code = `posthog.getFeatureFlag('my-flag');`;const result = await enricher.parse(code, "javascript");diff --git a/products/desktop/packages/enricher/src/parse-result.ts b/products/desktop/packages/enricher/src/parse-result.tsindex b6bf22b99f6d..5a057c953b41 100644--- a/products/desktop/packages/enricher/src/parse-result.ts+++ b/products/desktop/packages/enricher/src/parse-result.ts@@ -181,7 +181,7 @@ export class ParseResult {.map((d) => [d.name, d]),);- const host = config.host.replace(/\/$/, "");+ const host = (config.publicHost ?? config.host).replace(/\/$/, "");const flagUrls = new Map<string, string>();for (const [key, flag] of flags) {flagUrls.set(diff --git a/products/desktop/packages/enricher/src/posthog-api.ts b/products/desktop/packages/enricher/src/posthog-api.tsindex 626cf91ae3d1..1d29db7c2285 100644--- a/products/desktop/packages/enricher/src/posthog-api.ts+++ b/products/desktop/packages/enricher/src/posthog-api.ts@@ -7,6 +7,9 @@ import type {FlagEvaluationStats,} from "./types.js";+const EVENT_DEFINITION_FALLBACK_BATCH_SIZE = 8;+const MAX_EVENT_DEFINITION_FALLBACKS = 64;+export class PostHogApi {private config: EnricherApiConfig;@@ -108,12 +111,55 @@ export class PostHogApi {}async getEventDefinitions(names?: string[]): Promise<EventDefinition[]> {- let path = "/event_definitions/?limit=500";- if (names && names.length > 0) {- path += `&search=${encodeURIComponent(names.join(","))}`;+ const basePath = "/event_definitions/?limit=500";+ if (!names || names.length === 0) {+ const data = await this.get<{ results: EventDefinition[] }>(basePath);+ return data.results;}++ const uniqueNames = [...new Set(names)];+ const requestedNames = new Set(uniqueNames);+ const path = `${basePath}&names=${encodeURIComponent(uniqueNames.join(","))}`;const data = await this.get<{ results: EventDefinition[] }>(path);- return data.results;+ const definitionsByName = new Map(+ data.results+ .filter((definition) => requestedNames.has(definition.name))+ .map((definition) => [definition.name, definition]),+ );+ const missingNames = uniqueNames+ .filter((name) => !definitionsByName.has(name))+ .slice(0, MAX_EVENT_DEFINITION_FALLBACKS);++ for (+ let index = 0;+ index < missingNames.length;+ index += EVENT_DEFINITION_FALLBACK_BATCH_SIZE+ ) {+ const batch = missingNames.slice(+ index,+ index + EVENT_DEFINITION_FALLBACK_BATCH_SIZE,+ );+ const fallbackResults = await Promise.allSettled(+ batch.map((name) =>+ this.get<{ results: EventDefinition[] }>(+ `${basePath}&search=${encodeURIComponent(name)}`,+ ),+ ),+ );++ for (const fallback of fallbackResults) {+ if (fallback.status !== "fulfilled") {+ continue;+ }+ for (const definition of fallback.value.results) {+ if (requestedNames.has(definition.name)) {+ definitionsByName.set(definition.name, definition);+ }+ }+ }+ }++ return [...definitionsByName.values()];}async getEventStats(diff --git a/products/desktop/packages/enricher/src/types.ts b/products/desktop/packages/enricher/src/types.tsindex fb713702612e..5bec248d9180 100644--- a/products/desktop/packages/enricher/src/types.ts+++ b/products/desktop/packages/enricher/src/types.ts@@ -285,6 +285,7 @@ export interface EnrichedEvent {export interface EnricherApiConfig {apiKey: string;host: string;+ publicHost?: string;projectId: number;/** Timeout in ms for each API request (default: 10 000). */timeoutMs?: number;diff --git a/products/desktop/packages/shared/src/task.ts b/products/desktop/packages/shared/src/task.tsindex f6593d21bf97..2fe7da36b5cb 100644--- a/products/desktop/packages/shared/src/task.ts+++ b/products/desktop/packages/shared/src/task.ts@@ -10,6 +10,7 @@ export type {export interface PostHogAPIConfig {apiUrl: string;+ publicApiUrl?: string;getApiKey: () => string | Promise<string>;refreshApiKey?: () => string | Promise<string>;projectId: number;diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.tsindex 2d5cd438aba5..8f9b4a860026 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts@@ -158,6 +158,7 @@ vi.mock("node:fs", async (importOriginal) => {// --- Import after mocks ---import { fetchGatewayModels } from "@posthog/agent/gateway-models";+import { RICH_OUTPUT_TAGS_PROMPT } from "@posthog/shared/rich-output-prompt";import {AgentService,buildAutoApproveOutcome,@@ -1035,6 +1036,10 @@ describe("AgentService", () => {).append;}+ it("uses the shared object-reference prompt", () => {+ expect(buildChannelPrompt()).toContain(RICH_OUTPUT_TAGS_PROMPT);+ });+it("requires a task-specific clone instead of an existing checkout", () => {const prompt = buildChannelPrompt();