: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(posthog-ai): deliver run prompts to sandbox agents (#96810)
Thiago Salvatore09537094dd4a
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 332c7d001141..32745030ac67 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -575,6 +575,116 @@ describe("AgentServer HTTP Mode", () => {});}, 30000);+ it.each([+ {+ label: "uses a valid run-state system prompt",+ systemPrompt: {+ type: "preset",+ preset: "claude_code",+ append: "Run-state system prompt.",+ },+ includesRunStatePrompt: true,+ },+ {+ label: "ignores an invalid run-state system prompt",+ systemPrompt: {+ type: "preset",+ preset: "unknown",+ append: "Run-state system prompt.",+ },+ includesRunStatePrompt: false,+ },+ ])(+ "$label",+ async ({ systemPrompt, includesRunStatePrompt }) => {+ mswServer.use(+ http.get(+ "http://localhost:8000/api/projects/:projectId/tasks/:taskId/runs/:runId/",+ () =>+ HttpResponse.json(+ createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: { systemPrompt },+ }),+ ),+ ),+ );++ const testServer = createServer() as unknown as {+ start(): Promise<void>;+ session: {+ sessionMeta: { systemPrompt: string | { append: string } };+ } | null;+ };+ await testServer.start();++ const systemPromptValue = testServer.session?.sessionMeta.systemPrompt;+ const prompt =+ typeof systemPromptValue === "string"+ ? systemPromptValue+ : systemPromptValue?.append;++ expect(prompt?.includes("Run-state system prompt.")).toBe(+ includesRunStatePrompt,+ );+ if (includesRunStatePrompt) {+ expect(+ prompt?.indexOf("Operate as an expert product engineer."),+ ).toBeLessThan(prompt?.indexOf("Run-state system prompt.") ?? -1);+ expect(prompt?.indexOf("Run-state system prompt.")).toBeLessThan(+ prompt?.indexOf("# Cloud Task Execution") ?? -1,+ );+ }+ },+ 30000,+ );++ it("keeps the run-state system prompt after a transient run fetch failure", async () => {+ let attempts = 0;+ mswServer.use(+ http.get(+ "http://localhost:8000/api/projects/:projectId/tasks/:taskId/runs/:runId/",+ () => {+ attempts += 1;+ if (attempts === 1) {+ return new HttpResponse(null, { status: 503 });+ }+ return HttpResponse.json(+ createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: {+ systemPrompt: {+ type: "preset",+ preset: "claude_code",+ append: "Run-state system prompt.",+ },+ },+ }),+ );+ },+ ),+ );++ const testServer = createServer() as unknown as {+ start(): Promise<void>;+ session: {+ sessionMeta: { systemPrompt: string | { append: string } };+ } | null;+ };+ await testServer.start();++ const systemPromptValue = testServer.session?.sessionMeta.systemPrompt;+ const prompt =+ typeof systemPromptValue === "string"+ ? systemPromptValue+ : systemPromptValue?.append;++ expect(attempts).toBeGreaterThan(1);+ expect(prompt).toContain("Run-state system prompt.");+ }, 30000);+it("enables repository tools for a repository-less cloud session", async () => {await mkdir("/tmp/workspace", { recursive: true });mswServer.use(diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex 4cf326c6e98b..e0bd9eb7bbc3 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -146,6 +146,7 @@ import { createRtkSavingsNotification } from "./rtk-savings";import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";import {type CredentialResponseParams,+ claudeCodeConfigSchema,jsonRpcRequestSchema,validateCommandParams,} from "./schemas";@@ -1830,22 +1831,20 @@ export class AgentServer {}/**- * The task's origin decides which origin-gated local tools load, so a transient failure here- * would silently drop report_activity from an analysis run. Retry, then give up so a task that+ * The transport retries a rejected token but not a 5xx or a socket error, so one blip+ * would silently degrade the session. Retry, then give up so a task or run that* genuinely does not exist still starts the session.*/- private async fetchTaskForSessionContext(- taskId: string,- ): Promise<Task | null> {+ private async fetchForSessionContext<T>(+ fetch: () => Promise<T>,+ onGiveUp: (error: unknown) => void,+ ): Promise<T | null> {for (let attempt = 0; attempt < 3; attempt++) {try {- return await this.posthogAPI.getTask(taskId);+ return await fetch();} catch (err) {if (attempt === 2) {- this.logger.warn("Failed to fetch task for session context", {- taskId,- error: err,- });+ onGiveUp(err);return null;}await sleepWithBackoff(attempt, {@@ -1857,6 +1856,43 @@ export class AgentServer {return null;}+ /**+ * The task's origin decides which origin-gated local tools load, so a transient failure here+ * would silently drop report_activity from an analysis run.+ */+ private async fetchTaskForSessionContext(+ taskId: string,+ ): Promise<Task | null> {+ return this.fetchForSessionContext(+ () => this.posthogAPI.getTask(taskId),+ (error) =>+ this.logger.warn("Failed to fetch task for session context", {+ taskId,+ error,+ }),+ );+ }++ /**+ * The run carries the session's system prompt, which newSession fixes once, so a later+ * refresh cannot repair a run lost to a blip here. Without the run the stage is also+ * unknown, so routing falls back to the env product.+ */+ private async fetchTaskRunForSessionContext(+ taskId: string,+ runId: string,+ ): Promise<TaskRun | null> {+ return this.fetchForSessionContext(+ () => this.posthogAPI.getTaskRun(taskId, runId),+ (error) =>+ this.logger.warn("Failed to fetch task run for session context", {+ taskId,+ runId,+ error,+ }),+ );+ }+private async _doInitializeSession(payload: JwtPayload): Promise<void> {if (this.session) {await this.cleanupSession();@@ -1885,17 +1921,7 @@ export class AgentServer {"context_fetch",() =>Promise.all([- this.posthogAPI- .getTaskRun(payload.task_id, payload.run_id)- .catch((err) => {- // Without the run the stage is unknown, so routing falls back to the env product.- this.logger.warn("Failed to fetch task run for session context", {- taskId: payload.task_id,- runId: payload.run_id,- error: err,- });- return null;- }),+ this.fetchTaskRunForSessionContext(payload.task_id, payload.run_id),this.fetchTaskForSessionContext(payload.task_id),]),);@@ -1953,6 +1979,7 @@ export class AgentServer {preTaskRun,"slack_thread_url",);+ const runState = preTaskRun?.state;// Unconditional for the same reason as detectedPrUrl: a re-init on this// instance must not keep the previous run's delivery capability.@@ -1972,13 +1999,19 @@ export class AgentServer {await this.installStoreSkills(payload.task_id,payload.run_id,- preTaskRun?.state ?? null,+ runState ?? null,);+ const runStateSystemPrompt =+ claudeCodeConfigSchema.shape.systemPrompt.safeParse(+ runState?.systemPrompt,+ );+const sessionSystemPrompt = this.buildSessionSystemPrompt(prUrl,slackThreadUrl,inboxReportUrl,+ runStateSystemPrompt.success ? runStateSystemPrompt.data : undefined,);const codexInstructions =runtimeAdapter === "codex"@@ -2102,7 +2135,6 @@ export class AgentServer {const conversationClear =extractConversationClearCapability(initializeResult);- const runState = preTaskRun?.state;// Preserve native Codex modes for cloud runs so they behave the same as// local sessions. Claude keeps the historical auto-approved default when// PostHog Desktop has not explicitly selected a mode.@@ -4105,13 +4137,15 @@ export class AgentServer {prUrl?: string | null,slackThreadUrl?: string | null,inboxReportUrl?: string | null,+ runStateSystemPrompt?: ClaudeCodeConfig["systemPrompt"],): string | { append: string } {const cloudAppend = this.buildCloudSystemPrompt(prUrl,slackThreadUrl,inboxReportUrl,);- const userPrompt = this.config.claudeCode?.systemPrompt;+ const userPrompt =+ this.config.claudeCode?.systemPrompt ?? runStateSystemPrompt;const sessionPrompt = buildCloudSessionSystemPrompt(cloudAppend,diff --git a/products/posthog_ai/backend/services/system_prompt/prompt.py b/products/posthog_ai/backend/services/system_prompt/prompt.pyindex c4c8503b0826..5c0d2e916d45 100644--- a/products/posthog_ai/backend/services/system_prompt/prompt.py+++ b/products/posthog_ai/backend/services/system_prompt/prompt.py@@ -13,6 +13,7 @@ def governed_metrics_catalog_prompt() -> str:For any named business or operational measure, call `metric-list` before making a data-bearing call. It lists the complete governed catalog and outranks typed domain tools, `query-*` tools, product skills, and raw SQL. Use `metric-describe` to inspect any candidate's full definition, including its stored HogQL or SQL, before adapting it. When an approved, non-drifted metric exactly answers the request, run it with `data-catalog-metric-run` rather than re-deriving the number.+- Treat these as named measures even when they are phrased descriptively: counts of active entities; failure and error rates; latency percentiles; ticket, submission, and hit volumes; cost per run; and conversion rates. A product skill's query recipe does not exempt the request from this catalog-first step.- For a request that needs a drill-down, run the canonical metric for the headline first. You may then provide a label-level breakdown, but describe that breakdown as noncanonical.- When materially different catalog matches could answer the request, ask one clarifying question and end your turn. Do not acknowledge ambiguity and then run one of the alternatives anyway.- If no metric matches, say that you consulted the catalog and label any derived result noncanonical.diff --git a/products/posthog_ai/backend/tests/test_system_prompt.py b/products/posthog_ai/backend/tests/test_system_prompt.pyindex 35618ef33ab4..9009d95257a4 100644--- a/products/posthog_ai/backend/tests/test_system_prompt.py+++ b/products/posthog_ai/backend/tests/test_system_prompt.py@@ -24,6 +24,13 @@ class TestPostHogAISystemPrompt(APIBaseTest):assert "`metric-describe`" in promptassert "`data-catalog-metric-run`" in promptassert "complete governed catalog" in prompt+ assert "counts of active entities" in prompt+ assert "failure and error rates" in prompt+ assert "latency percentiles" in prompt+ assert "ticket, submission, and hit volumes" in prompt+ assert "cost per run" in prompt+ assert "conversion rates" in prompt+ assert "product skill's query recipe does not exempt" in promptdef test_includes_core_sections(self):prompt = self._build()["append"]