: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
refactor(agent): move slack and signals behavior into products folder (#119725)
Jonathan Mieloo0569ec100a2c
diff --git a/packages/agent/biome.jsonc b/packages/agent/biome.jsoncindex b72d995eaff7..a7f8f91440a7 100644--- a/packages/agent/biome.jsonc+++ b/packages/agent/biome.jsonc@@ -82,6 +82,55 @@}}},+ {+ "includes": [+ "packages/agent/src/sdk/**/*.ts",+ "packages/agent/src/server/agent-server.ts",+ "packages/agent/src/server/pi-agent-server.ts",+ "packages/agent/src/server/product/**/*.ts"+ ],+ "linter": {+ "rules": {+ "style": {+ "noRestrictedImports": {+ "level": "error",+ "options": {+ "patterns": [+ {+ "group": ["@posthog/shared", "@posthog/shared/*"],+ "message": "The agent runtime must not depend on desktop code. Import from @posthog/agent-contracts."+ },+ {+ "group": ["**/products/**"],+ "message": "The server and SDK receive one product definition from application boot. Do not import products into the runtime."+ }+ ]+ }+ }+ }+ }+ }+ },+ {+ "includes": ["packages/agent/src/products/**/*.ts"],+ "linter": {+ "rules": {+ "style": {+ "noRestrictedImports": {+ "level": "error",+ "options": {+ "patterns": [+ {+ "group": ["**/server/**", "**/boot/**"],+ "message": "Products use the agent SDK in src/sdk. Do not import runtime internals."+ }+ ]+ }+ }+ }+ }+ }+ },{"includes": ["packages/agent-contracts/**/*.ts"],"linter": {diff --git a/packages/agent/packages/agent/src/boot/select-product.test.ts b/packages/agent/packages/agent/src/boot/select-product.test.tsnew file mode 100644index 000000000000..17031948353b--- /dev/null+++ b/packages/agent/packages/agent/src/boot/select-product.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { selectProduct } from "./select-product";++describe("selectProduct", () => {+ it.each([+ ["slack", {}, "slack"],+ ["signal_report", {}, "signal_report"],+ ["workflow", { slack_reply_context: true }, "slack"],+ ["desktop", { slack_thread_url: "https://example.com/t" }, "slack"],+ ["desktop", { slack_reply_context: false }, undefined],+ [undefined, {}, undefined],+ ] as const)(+ "selects the product for origin %s with %o",+ (originProduct, launchOptions, expected) => {+ const product = selectProduct({+ taskId: "task-1",+ runId: "run-1",+ originProduct,+ launchOptions,+ });++ expect(product?.id).toBe(expected);+ },+ );+});diff --git a/packages/agent/packages/agent/src/boot/select-product.ts b/packages/agent/packages/agent/src/boot/select-product.tsnew file mode 100644index 000000000000..d699aa0ff47d--- /dev/null+++ b/packages/agent/packages/agent/src/boot/select-product.ts@@ -0,0 +1,18 @@+import {+ SIGNAL_REPORT_ORIGIN,+ signalReportProduct,+} from "../products/signal-report/product";+import { isSlackLaunch, slackProduct } from "../products/slack/product";+import type { AgentProduct, ProductLaunchConfiguration } from "../sdk/product";++export function selectProduct(+ launch: ProductLaunchConfiguration,+): AgentProduct | undefined {+ if (launch.originProduct === SIGNAL_REPORT_ORIGIN) {+ return signalReportProduct();+ }+ if (isSlackLaunch(launch.originProduct, launch.launchOptions)) {+ return slackProduct();+ }+ return undefined;+}diff --git a/packages/agent/packages/agent/src/products/signal-report/product.ts b/packages/agent/packages/agent/src/products/signal-report/product.tsnew file mode 100644index 000000000000..6d71189ba8d2--- /dev/null+++ b/packages/agent/packages/agent/src/products/signal-report/product.ts@@ -0,0 +1,23 @@+import type { AgentProduct } from "../../sdk/product";+import { buildPullRequestFooter } from "../../sdk/product";++export const SIGNAL_REPORT_ORIGIN = "signal_report";++export function signalReportProduct(): AgentProduct {+ return {+ id: SIGNAL_REPORT_ORIGIN,+ configureSession: ({ launch }) => {+ const threadUrl = launch.launchOptions.slack_thread_url;+ const source =+ typeof threadUrl === "string" && threadUrl+ ? { label: "Slack thread", url: threadUrl }+ : launch.source;+ return {+ pullRequests: {+ autoPublish: true,+ footer: buildPullRequestFooter(launch, { automated: true, source }),+ },+ };+ },+ };+}diff --git a/packages/agent/packages/agent/src/products/slack/product.test.ts b/packages/agent/packages/agent/src/products/slack/product.test.tsnew file mode 100644index 000000000000..2a27123ebb69--- /dev/null+++ b/packages/agent/packages/agent/src/products/slack/product.test.ts@@ -0,0 +1,205 @@+import { SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION } from "@posthog/harness/extensions/benjamin";+import { afterEach, describe, expect, it, vi } from "vitest";+import type {+ ProductServices,+ QuestionRequest,+ SessionBehavior,+} from "../../sdk/product";+import { slackProduct } from "./product";++const question: QuestionRequest = {+ questions: [+ {+ question: "Which license?",+ options: [{ label: "MIT", description: "Permissive" }],+ },+ { question: "Which branch?" },+ ],+};++async function configure(+ launchOptions: Record<string, unknown>,+ originProduct?: string,+ services: ProductServices = {+ sendReply: vi.fn().mockResolvedValue(undefined),+ },+): Promise<SessionBehavior> {+ return slackProduct().configureSession({+ launch: { taskId: "task-1", runId: "run-1", originProduct, launchOptions },+ services,+ });+}++describe("Slack product", () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ // Charts need only the rollout flag, while canvas/file also needs Slack scopes still in+ // review, so the chart offer has to be independent of the delivery mode in both+ // directions: present on a message-only workspace, absent on a canvas_file one whose+ // backend never sent the key.+ it.each([+ [null, false],+ [null, true],+ ["none", false],+ ["none", true],+ ["message", false],+ ["message", true],+ ["canvas_file", false],+ ["canvas_file", true],+ ] as const)(+ "offers only supported delivery routes (delivery: %s, charts: %s)",+ async (delivery, charts) => {+ const { deliveryInstructions = "" } = await configure({+ slack_artifact_delivery: delivery,+ slack_chart_delivery: charts,+ });+ const supportsArtifacts =+ delivery === "message" || delivery === "canvas_file";++ expect(deliveryInstructions.includes("## Delivering to Slack")).toBe(+ delivery !== null,+ );+ expect(+ deliveryInstructions.includes(+ "You do not have artifact delivery in this workspace",+ ),+ ).toBe(delivery === "none");+ expect(+ deliveryInstructions.includes(+ "You do not have canvas or file delivery",+ ),+ ).toBe(delivery === "message");+ expect(+ deliveryInstructions.includes(+ "`slack_canvas`, `slack_message`, `slack_file`",+ ),+ ).toBe(delivery === "canvas_file");+ expect(deliveryInstructions.includes("living_artifacts/chart/")).toBe(+ supportsArtifacts && charts,+ );+ // Without this the two bullets contradict each other: one forbids file delivery, the+ // other tells the agent to deliver an image.+ expect(+ deliveryInstructions.includes("Chart images are the one exception"),+ ).toBe(delivery === "message" && charts);+ },+ );++ it.each([+ ["slack", {}, true],+ ["workflow", { slack_reply_context: true }, true],+ ["workflow", { slack_thread_url: "https://example.com/t" }, false],+ ] as const)(+ "uses the Slack reply style only for Slack replies (origin: %s, %o)",+ async (origin, launchOptions, slackReply) => {+ vi.stubEnv("POSTHOG_BENJAMIN", "1");+ const session = await configure(launchOptions, origin);++ expect(+ (session.identityInstructions ?? "").includes("PostHog Slack app"),+ ).toBe(slackReply);+ expect(session.replySurface).toBe(slackReply ? "slack" : undefined);+ expect(session.closingInstructions).toBe(+ slackReply ? SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION : undefined,+ );+ },+ );++ it.each([false, true])(+ "asks for a task list only when the checklist is visible: %s",+ async (checklist) => {+ // The checklist is the Slack progress UI. Without it the task list is invisible,+ // and asking for one only costs the agent turns.+ const session = await configure(+ { slack_app_agent_design_enabled: checklist },+ "slack",+ );++ expect(+ session.identityInstructions?.includes("# Progress checklist"),+ ).toBe(checklist);+ },+ );++ it.each([+ [+ "slack",+ { slack_thread_url: "https://example.com/t" },+ true,+ "*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](https://example.com/t)*",+ ],+ [+ "workflow",+ { slack_reply_context: true },+ false,+ "*Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)*",+ ],+ ] as const)(+ "publishes only for the Slack app origin (origin: %s)",+ async (origin, launchOptions, autoPublish, footer) => {+ const session = await configure(launchOptions, origin);++ expect(session.pullRequests).toEqual({+ autoPublish,+ existingUrl: null,+ footer,+ });+ },+ );++ it("keeps defaults for malformed launch options", async () => {+ const session = await configure(+ {+ slack_artifact_delivery: "unknown",+ slack_chart_delivery: "true",+ slack_app_agent_design_enabled: 1,+ slack_thread_url: 123,+ slack_notified_pr_url: [],+ },+ "slack",+ );++ expect(session.deliveryInstructions).toBe("");+ expect(session.identityInstructions).not.toContain("# Progress checklist");+ expect(session.pullRequests?.existingUrl).toBeNull();+ });++ it.each([+ {+ name: "relays the first question and asks the agent to wait",+ request: question,+ relayed: true,+ },+ {+ name: "asks the agent to wait without a relay for invalid question data",+ request: { questions: [] },+ relayed: false,+ },+ ])("$name", async ({ request, relayed }) => {+ const sendReply = vi.fn().mockResolvedValue(undefined);+ const session = await configure({}, "slack", { sendReply });++ const response = session.handleQuestions?.(request);++ expect(response).toEqual({+ message: expect.stringContaining("relayed to the Slack thread"),+ awaitingReply: relayed,+ });+ if (relayed) {+ expect(sendReply).toHaveBeenCalledExactlyOnceWith({+ message:+ "*Which license?*\n\n1. *MIT* — Permissive\n\nReply in this thread with your choice.",+ });+ } else {+ expect(sendReply).not.toHaveBeenCalled();+ }+ });++ it("leaves questions to the default flow outside the Slack app", async () => {+ const session = await configure({ slack_reply_context: true }, "workflow");++ expect(session.handleQuestions).toBeUndefined();+ });+});diff --git a/packages/agent/packages/agent/src/products/slack/product.ts b/packages/agent/packages/agent/src/products/slack/product.tsnew file mode 100644index 000000000000..bfc4b92ceb0a--- /dev/null+++ b/packages/agent/packages/agent/src/products/slack/product.ts@@ -0,0 +1,118 @@+import {+ isBenjaminEnabled,+ SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION,+} from "@posthog/harness/extensions/benjamin";+import { z } from "zod";+import type {+ AgentProduct,+ Question,+ QuestionRequest,+} from "../../sdk/product";+import { buildPullRequestFooter, defineProduct } from "../../sdk/product";+import {+ buildSlackDeliveryInstructions,+ buildSlackIdentityInstructions,+} from "./prompt";++const SLACK_ORIGIN = "slack";++const AWAITING_REPLY_MESSAGE =+ "This question has been relayed to the Slack thread where this task originated. " ++ "The user will reply there. Do NOT re-ask the question or pick an answer yourself. " ++ "Simply let the user know you are waiting for their reply.";++const slackLaunchOptionsSchema = z.object({+ slack_reply_context: z.boolean().catch(false),+ // The backend resolves delivery routes from flags and Slack scopes. An unset key means it+ // told us nothing, so emit no constraints rather than offer a route delivery would reject.+ slack_artifact_delivery: z+ .enum(["none", "message", "canvas_file"])+ .nullable()+ .catch(null),+ // Charts need only the rollout flag, while canvas and file delivery also need Slack+ // scopes, so a workspace can have charts and nothing else.+ slack_chart_delivery: z.boolean().catch(false),+ slack_app_agent_design_enabled: z.boolean().catch(false),+ slack_thread_url: z.string().nullable().catch(null),+ slack_notified_pr_url: z.string().nullable().catch(null),+ client_platform: z.string().optional().catch(undefined),+});++export function isSlackLaunch(+ originProduct: string | undefined,+ launchOptions: Record<string, unknown>,+): boolean {+ if (originProduct === SLACK_ORIGIN) {+ return true;+ }+ return Object.entries(launchOptions).some(+ ([key, value]) => key.startsWith("slack_") && Boolean(value),+ );+}++function formatQuestion(question: Question): string {+ let message = `*${question.question}*\n\n`;+ for (const [index, option] of (question.options ?? []).entries()) {+ message += `${index + 1}. *${option.label}*`;+ if (option.description) {+ message += ` — ${option.description}`;+ }+ message += "\n";+ }+ message += "\nReply in this thread with your choice.";+ return message;+}++export function slackProduct(): AgentProduct {+ return defineProduct({+ id: SLACK_ORIGIN,+ launchOptionsSchema: slackLaunchOptionsSchema,+ configureSession({ launch, services }) {+ const { launchOptions } = launch;+ const slackOrigin = launch.originProduct === SLACK_ORIGIN;+ const slackReply = slackOrigin || launchOptions.slack_reply_context;+ const promptOptions = {+ slackArtifactDelivery: launchOptions.slack_artifact_delivery,+ slackChartDelivery: launchOptions.slack_chart_delivery,+ slackProgressChecklist: launchOptions.slack_app_agent_design_enabled,+ };+ const threadUrl = launchOptions.slack_thread_url;+ const footerSource = threadUrl+ ? { label: "Slack thread", url: threadUrl }+ : launch.source;+ const closingInstructions =+ slackReply && isBenjaminEnabled()+ ? SIMPLIFIED_TECHNICAL_ENGLISH_INSTRUCTION+ : undefined;++ const handleQuestions = ({ questions }: QuestionRequest) => {+ const question = questions[0];+ if (question) {+ void services.sendReply({ message: formatQuestion(question) });+ }+ return {+ message: AWAITING_REPLY_MESSAGE,+ awaitingReply: Boolean(question),+ };+ };++ return {+ identityInstructions: slackReply+ ? buildSlackIdentityInstructions(promptOptions)+ : undefined,+ deliveryInstructions: buildSlackDeliveryInstructions(promptOptions),+ closingInstructions,+ replySurface: slackReply ? SLACK_ORIGIN : undefined,+ pullRequests: {+ autoPublish: slackOrigin,+ existingUrl: launchOptions.slack_notified_pr_url,+ footer: buildPullRequestFooter(launch, {+ automated: slackOrigin,+ source: footerSource,+ }),+ },+ handleQuestions: slackOrigin ? handleQuestions : undefined,+ };+ },+ });+}diff --git a/packages/agent/packages/agent/src/products/slack/prompt.ts b/packages/agent/packages/agent/src/products/slack/prompt.tsnew file mode 100644index 000000000000..d36f978e2141--- /dev/null+++ b/packages/agent/packages/agent/src/products/slack/prompt.ts@@ -0,0 +1,100 @@+export type SlackArtifactDelivery = "none" | "message" | "canvas_file";++export interface SlackPromptOptions {+ slackArtifactDelivery: SlackArtifactDelivery | null;+ slackChartDelivery: boolean;+ slackProgressChecklist: boolean;+}++export function buildSlackDeliveryInstructions(+ options: SlackPromptOptions,+): string {+ if (options.slackArtifactDelivery === null) {+ return "";+ }++ if (options.slackArtifactDelivery === "none") {+ return `+## Delivering to Slack+- You do not have artifact delivery in this workspace: you cannot create or share artifacts (files, canvases, documents) from this run, so do not attempt to. Deliver results as plain text in your reply.+- Do not attach, upload, link to, or expose run artifacts or local working files, including /tmp/workspace paths.`;+ }++ const endpoint = `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/`;+ const preamble = `+## Delivering to Slack+- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.+- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.+- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, user uploads) are internal: never deliver them to Slack or mention them in your reply.`;++ // Charts attach to both modes: they post as an image block referencing a PostHog-hosted+ // URL, so they work wherever the workspace can post at all.+ const chartBullets = options.slackChartDelivery+ ? `+- When an analytics answer is naturally visual (a trend over time, funnel, breakdown comparison, retention curve), deliver a chart image by default alongside the summary. Do not wait for the user to say "chart". Skip the image only when the result is a single number, a short list, or the user asked for raw data.+- To show a chart in Slack (a saved insight or an ad-hoc analytics query result), make a single call: POST to \`${endpoint}chart/\` with \`$POSTHOG_PERSONAL_API_KEY\` and body \`{"name": "<chart title>", "query": <query JSON, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}>}\`, or \`{"name": "<chart title>", "insight_id": <numeric insight id>}\` for a saved insight. It renders the chart server-side and registers it for Slack delivery in one step, blocking until done (typically a few seconds).+- The chart renders directly under your answer text with its name as the title, so do not restate the title or announce the chart ("Here's a chart of…"). Spend your answer text on the takeaway instead: the trend, inflection points, spikes, or drops a reader should notice, with numbers where they matter. Each chart is delivered with an "Open in PostHog" button, so do not paste the response \`url\` into your answer unless the user explicitly asks for a link. Do not download, view, or re-upload the image yourself.+- Report a chart failure rather than retrying blindly: a 400 carries the reason in \`error\`, or in \`detail\` when the request body itself was rejected, and a 429 means the project's chart render limit is saturated, so answer without the chart.+- SQL results cannot be charted yet, because the chart endpoint rejects SQL queries. Chart with an insight query (e.g. TrendsQuery) when the question can be expressed as one; otherwise summarize the SQL result in your answer text.`+ : "";++ if (options.slackArtifactDelivery === "message") {+ const chartException = options.slackChartDelivery+ ? " Chart images are the one exception: deliver them through the dedicated chart endpoint below, never through the generic living-artifacts endpoint."+ : "";+ const unsupportedDeliverable = options.slackChartDelivery+ ? "- If a deliverable cannot be expressed as a Slack message or a chart image (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead."+ : "- If a deliverable cannot be expressed as a Slack message (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead.";+ return `${preamble}+- You do not have canvas or file delivery in this workspace: do not use the \`slack_canvas\` or \`slack_file\` adapters, and do not promise a canvas, uploaded spreadsheet, or downloadable file.${chartException}+- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\` using adapter \`slack_message\`. To update a prior deliverable, GET the returned artifact id or POST new \`content\` to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}+${unsupportedDeliverable}`;+ }++ return `${preamble}+- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\`; choose adapter \`slack_canvas\`, \`slack_message\`, \`slack_file\`, or \`document_connector\`. Use \`adapter=slack_file\` with \`content_base64\` for binary deliverables such as .xlsx/.pdf/.docx, or \`source_artifact_id\` / \`source_storage_path\` for a file you already uploaded as a \`type=output\` run artifact.+- To update a prior deliverable, GET the returned artifact id or POST new \`content\`, \`content_base64\`, or source artifact fields to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}+- Do not paste living-artifact Slack file links or permalinks into your final Slack answer unless the user explicitly asks for the URL. The Slack relay attaches pending files and canvas cards to your final answer automatically after you finish, so mention the artifact by name only if useful.+- A pending delivery status only means the artifact waits for your final answer. Do not check it again, and do not tell the user that a link or file has not arrived.+- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead.`;+}++export function buildSlackIdentityInstructions(+ options: SlackPromptOptions,+): string {+ const slackIdentityInstructions = `+# Identity+You are the PostHog Slack app, PostHog's agent for helping users with their product data and coding tasks from Slack. When introducing yourself or referring to yourself in messages to the user, identify as "PostHog Slack app". Do NOT refer to yourself as Claude, an Anthropic assistant, or any underlying model name.++# Response Style+You are replying in a Slack thread. Slack readers want short, skimmable answers — be concise by default.+- Answer simple questions in a single sentence. Keep everything else brief — a few sentences at most.+- Lead with the answer or the outcome. Skip preamble, restating the question, and sign-offs.+- Prefer plain prose. Treat bullet lists as the exception, not the norm, and avoid headers and tables unless they genuinely make a complex answer clearer.+- Do not narrate your thinking or list every step you took; report what matters and the result.+- This is a default, not a hard rule. If the user (or their saved memory) asks for more depth or a specific format, follow that instead.++# PostHog products first+PostHog is a product suite, not just analytics — session replay, feature flags, experiments, surveys, error tracking, logs, data warehouse, CDP, messaging, and customer support all ship as PostHog products.+- When someone asks how to set up, enable, configure, or use a capability, assume they mean PostHog's version of it and answer about that.+- Search our docs with the \`docs-search\` tool before you answer, and ground the answer in what it returns rather than in what you remember. The product changes faster than your training data.+- Never send the user to a third-party product for something PostHog does. If you are unsure whether we cover it, search the docs before concluding we don't — and if we genuinely don't, say so plainly instead of recommending a competitor. Pointing at a third party we integrate with, as a source or destination, is fine.+- When a request could mean either a PostHog feature or something in the user's own codebase, ask which they mean instead of guessing.++# Mentioning users+To ping a Slack user, reuse a \`<@U…|displayname>\` token that already appears in the message context — copy it verbatim, including the \`U…\` ID. Do NOT construct a mention token from a name, and do NOT substitute the display name (or any other string) for the \`U…\` ID — \`<@Jane|Jane Doe>\` is not a valid mention; only the form with the real ID like \`<@U01ABCDEF23|Jane Doe>\` is. If the person you want to refer to has no \`<@U…|displayname>\` token anywhere in the thread context, write their name as plain text instead of inventing one. These \`<@U…>\` tokens are Slack-only: never carry one — or a name or handle derived from it — into a GitHub PR, commit message, or review request as an \`@\`-mention. A Slack display name or handle is NOT a GitHub username; see the pull-request instructions below.++# Suggesting code changes+You can also open pull requests directly from this Slack thread. When the user's question describes a problem with a plausible code-side fix — a bug visible in errors or logs, missing or broken instrumentation, a broken funnel step traceable to UI code, a stale config that lives in a repo — end your reply with a one-sentence offer to open a PR for the fix and ask if they want you to proceed. Skip the offer for pure data lookups with no actionable code change (e.g. "what was DAU yesterday?"), and skip it when the fix would clearly live outside any repo you can reach.+`;+ const slackProgressInstructions = options.slackProgressChecklist+ ? `+# Progress checklist+The Slack thread shows your task list as a live checklist, and it is the only progress the user sees while you work. Before your first tool call, create the task list with your task tools (TaskCreate and TaskUpdate, or update_plan): 2 to 5 tasks, each one outcome the user cares about. Mark a task in progress when you start it and completed when you finish it. Add a task when the work grows.+- Write each task in plain words for someone who does not read code, for example "Find the signup event" or "Count weekly signups".+- Do not put tool names, file paths, SQL, or IDs in a task.+- Skip the list only when you answer without any tool call.+`+ : "";+ return `${slackIdentityInstructions}${slackProgressInstructions}`;+}diff --git a/packages/agent/packages/agent/src/sdk/product.test.ts b/packages/agent/packages/agent/src/sdk/product.test.tsnew file mode 100644index 000000000000..e6c67f77bbe0--- /dev/null+++ b/packages/agent/packages/agent/src/sdk/product.test.ts@@ -0,0 +1,100 @@+import { describe, expect, expectTypeOf, it, vi } from "vitest";+import { z } from "zod";+import {+ type AgentSessionConfiguration,+ buildPullRequestFooter,+ defineProduct,+ type ProductLaunchConfiguration,+} from "./product";++function launch(+ launchOptions: Record<string, unknown> = {},+): ProductLaunchConfiguration {+ return { taskId: "task-1", runId: "run-1", launchOptions };+}++function session(+ launchOptions: Record<string, unknown>,+): AgentSessionConfiguration {+ return {+ launch: launch(launchOptions),+ services: { sendReply: vi.fn().mockResolvedValue(undefined) },+ };+}++describe("defineProduct", () => {+ it("passes parsed launch options to the session without changing the input", () => {+ const raw = { topic: " Promises ", unrelated: true };+ const input = session(raw);+ const product = defineProduct({+ id: "tutor",+ launchOptionsSchema: z.object({+ topic: z.string().trim(),+ level: z.number().default(1),+ }),+ configureSession({ launch: { launchOptions } }) {+ expectTypeOf(launchOptions).toEqualTypeOf<+ Readonly<{ topic: string; level: number }>+ >();+ return {+ identityInstructions: `${launchOptions.topic}, level ${launchOptions.level}`,+ };+ },+ });++ expect(product.configureSession(input)).toEqual({+ identityInstructions: "Promises, level 1",+ });+ expect(input.launch.launchOptions).toBe(raw);+ expect(raw).toEqual({ topic: " Promises ", unrelated: true });+ });++ it("rejects invalid launch options before the product runs", () => {+ const configureSession = vi.fn(() => ({}));+ const product = defineProduct({+ id: "tutor",+ launchOptionsSchema: z.object({ topic: z.string() }),+ configureSession,+ });++ expect(() => product.configureSession(session({}))).toThrow();+ expect(configureSession).not.toHaveBeenCalled();+ });+});++describe("buildPullRequestFooter", () => {+ it.each([+ [+ "desktop",+ {},+ {},+ "*Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)*",+ ],+ [+ "mobile overrides automated",+ { client_platform: "mobile" },+ { automated: true },+ "*Created with [PostHog Mobile](https://posthog.com?ref=pr)*",+ ],+ [+ "automated with an inbox report",+ {},+ {+ automated: true,+ source: { label: "inbox report", url: "https://example.com/r" },+ },+ "*Created with [PostHog](https://posthog.com?ref=pr) from an [inbox report](https://example.com/r)*",+ ],+ [+ "Slack thread",+ {},+ {+ automated: true,+ source: { label: "Slack thread", url: "https://example.com/t" },+ },+ "*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](https://example.com/t)*",+ ],+ ] as const)("formats the %s footer", (_name, options, footer, expected) => {+ expect(buildPullRequestFooter(launch(options), footer)).toBe(expected);+ });+});diff --git a/packages/agent/packages/agent/src/sdk/product.ts b/packages/agent/packages/agent/src/sdk/product.tsnew file mode 100644index 000000000000..bd2ba13146b6--- /dev/null+++ b/packages/agent/packages/agent/src/sdk/product.ts@@ -0,0 +1,152 @@+/** Configures product behavior for an agent session. */+export interface AgentProduct {+ /** Stable product identifier. */+ readonly id: string;+ /** Configures behavior for one agent session. */+ configureSession(+ session: AgentSessionConfiguration,+ ): MaybePromise<SessionBehavior>;+}++/** Selects the product for a task run at application boot. */+export type ProductSelector = (+ launch: ProductLaunchConfiguration,+) => AgentProduct | undefined;++/** Behavior that applies for an agent session. */+export interface SessionBehavior {+ /** Instructions added to the identity section of the system prompt. */+ identityInstructions?: string;+ /** Instructions added to the result delivery section of the system prompt. */+ deliveryInstructions?: string;+ /** Instructions added at the end of the system prompt. */+ closingInstructions?: string;+ /** Surface that shows the agent replies. Sets the output formatting rules. */+ replySurface?: string;+ /** Pull request settings for the session. */+ pullRequests?: PullRequestOptions;+ /** Handles questions that the agent asks. */+ handleQuestions?(request: QuestionRequest): QuestionResponse;+}++/** Inputs and services for session configuration. */+export interface AgentSessionConfiguration<+ LaunchOptions extends object = Record<string, unknown>,+> {+ /** Task run data provided at launch. */+ readonly launch: ProductLaunchConfiguration<LaunchOptions>;+ /** Task-run operations available to the product. */+ readonly services: ProductServices;+}++/** Task run data passed to a product at launch. */+export interface ProductLaunchConfiguration<+ LaunchOptions extends object = Record<string, unknown>,+> {+ /** Task identifier. */+ readonly taskId: string;+ /** Task run identifier. */+ readonly runId: string;+ /** Product that started the run. */+ readonly originProduct?: string;+ /** Product-specific launch data. */+ readonly launchOptions: Readonly<LaunchOptions>;+ /** Optional source that started the task. */+ readonly source?: TaskSource;+}++/** A link to the source that started a task. */+export interface TaskSource {+ /** Source name, such as "inbox report". */+ readonly label: string;+ /** Source URL. */+ readonly url: string;+}++/** A request for answers to agent questions. */+export interface QuestionRequest {+ /** Questions from the agent. Empty when the question data is not valid. */+ readonly questions: readonly Question[];+}++/** One question from the agent. */+export interface Question {+ /** Question text. */+ readonly question: string;+ /** Available answer options. */+ readonly options?: ReadonlyArray<{ label: string; description?: string }>;+}++/** The answer the agent gets for its question tool call. */+export interface QuestionResponse {+ /** Message for the agent. */+ message: string;+ /** Skips the relay of the agent reply at the end of the turn when true. */+ awaitingReply: boolean;+}++/** Task-run operations available to products. */+export interface ProductServices {+ /** Sends a reply to the task source. The runtime reports delivery failures. */+ sendReply(reply: Reply): Promise<void>;+}++/** A reply sent to the task source. */+export interface Reply {+ /** Reply text. */+ message: string;+}++/** Pull request settings for a session. */+export interface PullRequestOptions {+ /** Publishes the pull request without an explicit request when true. */+ autoPublish?: boolean;+ /** Existing pull request URL. */+ existingUrl?: string | null;+ /** Footer line for pull request descriptions. */+ footer?: string;+}++export type MaybePromise<T> = T | Promise<T>;++export function defineProduct<LaunchOptions extends object>(definition: {+ readonly id: string;+ launchOptionsSchema: { parse(launchOptions: unknown): LaunchOptions };+ configureSession(+ session: AgentSessionConfiguration<LaunchOptions>,+ ): MaybePromise<SessionBehavior>;+}): AgentProduct {+ return {+ id: definition.id,+ configureSession(session) {+ const launchOptions = definition.launchOptionsSchema.parse(+ session.launch.launchOptions,+ );+ return definition.configureSession({+ ...session,+ launch: { ...session.launch, launchOptions },+ });+ },+ };+}++export function buildPullRequestFooter(+ launch: ProductLaunchConfiguration,+ options: { automated?: boolean; source?: TaskSource } = {},+): string {+ const mobile = launch.launchOptions.client_platform === "mobile";+ let createdWith =+ "Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)";+ if (mobile) {+ createdWith = "Created with [PostHog Mobile](https://posthog.com?ref=pr)";+ } else if (options.automated) {+ createdWith = "Created with [PostHog](https://posthog.com?ref=pr)";+ }++ const { source } = options;+ if (!source) {+ return `*${createdWith}*`;+ }+ const article = /^[aeiou]/i.test(source.label) ? "an" : "a";+ return `*${createdWith} from ${article} [${source.label}](${source.url})*`;+}diff --git a/packages/agent/packages/agent/src/server/agent-server.test.ts b/packages/agent/packages/agent/src/server/agent-server.test.tsindex 3b353975e8f8..4565aa42ef86 100644--- a/packages/agent/packages/agent/src/server/agent-server.test.ts+++ b/packages/agent/packages/agent/src/server/agent-server.test.ts@@ -34,10 +34,12 @@ import {} from "vitest";import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";import { getSessionJsonlPath } from "../adapters/claude/session/jsonl-hydration";+import { selectProduct } from "../boot/select-product";import type { ContextSelectionResponse } from "../context-selection/schemas";import type { PermissionMode } from "../execution-mode";import type { PostHogAPIClient } from "../posthog-api";import { formatConversationForResume, type ResumeState } from "../resume";+import type { ProductLaunchConfiguration, TaskSource } from "../sdk/product";import { SessionLogWriter } from "../session-log-writer";import {createMockApiClient,@@ -60,6 +62,31 @@ import { ContextSelection, type HumanMessage } from "./context-selection";import { type JwtPayload, SANDBOX_CONNECTION_AUDIENCE } from "./jwt";import type { ExistingPrCheckoutResult } from "./pr-checkout";+const SLACK_THREAD_URL = "https://posthog.slack.com/archives/C123/p456";+const INBOX_REPORT = {+ label: "inbox report",+ url: "http://localhost:8000/project/1/inbox/rep_1",+};++async function openProduct(+ server: AgentServer,+ originProduct?: string,+ launchOptions: Record<string, unknown> = {},+ source?: TaskSource,+): Promise<void> {+ await (+ server as unknown as {+ openProductSession(launch: ProductLaunchConfiguration): Promise<void>;+ }+ ).openProductSession({+ taskId: "test-task-id",+ runId: "test-run-id",+ originProduct,+ launchOptions,+ source,+ });+}+const mockedClaudeSdk = vi.hoisted(() => {const createSuccessResult = () => ({type: "result",@@ -252,15 +279,7 @@ interface TestableServer {run: TaskRun | null,): Promise<void>;detectedPrUrl: string | null;- slackArtifactDelivery: "none" | "message" | "canvas_file" | null;- slackChartDelivery: boolean;- slackProgressChecklist: boolean;- slackReplyContext: boolean;- buildCloudSystemPrompt(- prUrl?: string | null,- slackThreadUrl?: string | null,- inboxReportUrl?: string | null,- ): string;+ buildCloudSystemPrompt(prUrl?: string | null): string;buildDetectedPrContext(prUrl: string): string;buildExistingPrCheckoutPromise(prUrl: string | null,@@ -269,11 +288,7 @@ interface TestableServer {prUrl: string | null,result: ExistingPrCheckoutResult,): void;- buildSessionSystemPrompt(- prUrl?: string | null,- slackThreadUrl?: string | null,- inboxReportUrl?: string | null,- ): string | { append: string };+ buildSessionSystemPrompt(prUrl?: string | null): string | { append: string };buildCodexInstructions(systemPrompt: string | { append: string }): string;getRuntimeAdapter(): Adapter;buildClaudeCodeSessionMeta(@@ -640,6 +655,7 @@ describe("AgentServer HTTP Mode", () => {taskId: "test-task-id",runId: "test-run-id",resolveRtkSavings: async () => null,+ selectProduct,...overrides,});return server;@@ -6582,20 +6598,27 @@ describe("AgentServer HTTP Mode", () => {).toContain("BENJAMIN-PLUS MODE ACTIVE");});- it("injects STE100 guidance into Slack prompts when POSTHOG_BENJAMIN is set", () => {- vi.stubEnv("POSTHOG_BENJAMIN", "1");- vi.stubEnv("POSTHOG_CODE_INTERACTION_ORIGIN", "slack");- const s = createServer();- const sessionPrompt = (- s as unknown as TestableServer- ).buildSessionSystemPrompt();+ it.each([+ ["slack", {}],+ ["workflow", { slack_reply_context: true }],+ ])(+ "ends Slack reply prompts with STE100 guidance and no rich output (origin: %s)",+ async (origin, launchOptions) => {+ vi.stubEnv("POSTHOG_BENJAMIN", "1");+ const s = createServer();+ await openProduct(s, origin, launchOptions);+ const sessionPrompt = (+ s as unknown as TestableServer+ ).buildSessionSystemPrompt();+ const prompt =+ typeof sessionPrompt === "string"+ ? sessionPrompt+ : sessionPrompt.append;- expect(- typeof sessionPrompt === "string"- ? sessionPrompt- : sessionPrompt.append,- ).toContain(STE100_INSTRUCTION);- });+ expect(prompt.endsWith(STE100_INSTRUCTION)).toBe(true);+ expect(prompt).not.toContain("Rich output in replies");+ },+ );it("does not inject STE100 guidance into user-created prompts", () => {vi.stubEnv("POSTHOG_BENJAMIN", "1");@@ -7338,96 +7361,26 @@ describe("AgentServer HTTP Mode", () => {vi.unstubAllEnvs();});- it.each([- {- delivery: "canvas_file" as const,- expected: "`slack_canvas`, `slack_message`, `slack_file`",- notExpected: "You do not have canvas or file delivery",- },- {- delivery: "message" as const,- expected: "You do not have canvas or file delivery in this workspace",- notExpected: "`slack_canvas`, `slack_message`, `slack_file`",- },- {- delivery: "none" as const,- expected: "You do not have artifact delivery in this workspace",- notExpected: "create a living artifact before claiming delivery",- },- ])(- "offers only the Slack delivery routes the workspace has: $delivery",- ({ delivery, expected, notExpected }) => {- const s = createServer() as unknown as TestableServer;- s.slackArtifactDelivery = delivery;-- const prompt = s.buildCloudSystemPrompt();-- expect(prompt).toContain("## Delivering to Slack");- expect(prompt).toContain(expected);- expect(prompt).not.toContain(notExpected);- },- );+ it("places product delivery instructions with the other delivery instructions", async () => {+ const s = createServer();+ await openProduct(s, "slack", { slack_artifact_delivery: "message" });- it("says nothing about Slack delivery when the backend did not resolve it", () => {- const s = createServer() as unknown as TestableServer;- s.slackArtifactDelivery = null;+ const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();+ const delivery = prompt.indexOf("## Delivering to Slack");- expect(s.buildCloudSystemPrompt()).not.toContain(- "## Delivering to Slack",+ expect(delivery).toBeGreaterThan(+ prompt.indexOf("## Delivering non-code files"),);+ expect(delivery).toBeLessThan(prompt.indexOf("## GitHub access"));});- // Charts need only the rollout flag, while canvas/file also needs Slack scopes still in- // review, so the chart offer has to be independent of the delivery mode in both- // directions: present on a message-only workspace, absent on a canvas_file one whose- // backend never sent the key.- it.each([- { delivery: "canvas_file" as const, charts: true },- { delivery: "message" as const, charts: true },- ])(- "offers the chart endpoint on a $delivery workspace when charts are on",- ({ delivery, charts }) => {- const s = createServer() as unknown as TestableServer;- s.slackArtifactDelivery = delivery;- s.slackChartDelivery = charts;-- const prompt = s.buildCloudSystemPrompt();-- expect(prompt).toContain("living_artifacts/chart/");- expect(prompt).toContain("deliver a chart image by default");- },- );-- it.each([- { delivery: "canvas_file" as const },- { delivery: "message" as const },- { delivery: "none" as const },- ])(- "never mentions charts on a $delivery workspace when charts are off",- ({ delivery }) => {- const s = createServer() as unknown as TestableServer;- s.slackArtifactDelivery = delivery;- s.slackChartDelivery = false;-- expect(s.buildCloudSystemPrompt()).not.toContain(- "living_artifacts/chart/",- );- },- );-- it("tells a message-only workspace that charts are the exception to the no-file rule", () => {- // Without this the two bullets contradict each other: one forbids file delivery, the- // other tells the agent to deliver an image.- const s = createServer() as unknown as TestableServer;- s.slackArtifactDelivery = "message";- s.slackChartDelivery = true;-- const prompt = s.buildCloudSystemPrompt();+ it("says nothing about Slack delivery when the backend did not resolve it", async () => {+ const s = createServer();+ await openProduct(s, "slack");- expect(prompt).toContain("Chart images are the one exception");- expect(prompt).toContain(- "cannot be expressed as a Slack message or a chart image",- );+ expect(+ (s as unknown as TestableServer).buildCloudSystemPrompt(),+ ).not.toContain("## Delivering to Slack");});it("describes every repository in a shared multi-repository workspace", () => {@@ -7589,9 +7542,10 @@ describe("AgentServer HTTP Mode", () => {},);- it("returns auto-PR prompt for Slack-origin runs", () => {+ it("returns auto-PR prompt for Slack-origin runs", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();expect(prompt).toContain("posthog/");expect(prompt).toContain("Create a draft pull request");@@ -7640,15 +7594,15 @@ describe("AgentServer HTTP Mode", () => {it.each(["slack", "signal_report"])("carries the GitHub identity guidance on %s-origin runs",- (origin) => {+ async (origin) => {// Non-Slack runs open issues under a person's credentials too, so this must not// sit behind `isSlack`.vi.stubEnv("GITHUB_TOKEN", "ghu_actor");- vi.stubEnv("POSTHOG_CODE_INTERACTION_ORIGIN", origin);- const s = createServer() as unknown as TestableServer;- expect(s.buildCloudSystemPrompt()).toContain(- "# Whose GitHub account you are using",- );+ const s = createServer();+ await openProduct(s, origin);+ expect(+ (s as unknown as TestableServer).buildCloudSystemPrompt(),+ ).toContain("# Whose GitHub account you are using");},);@@ -7664,9 +7618,10 @@ describe("AgentServer HTTP Mode", () => {);});- it("returns auto-PR prompt for signal_report-origin runs", () => {+ it("returns auto-PR prompt for signal_report-origin runs", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "signal_report";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();expect(prompt).toContain("posthog/");expect(prompt).toContain("Create a draft pull request");@@ -7861,9 +7816,10 @@ describe("AgentServer HTTP Mode", () => {{ label: "signal_report", origin: "signal_report" },])("guards the auto-PR prompt against duplicating an existing PR on $label-origin runs",- ({ origin }) => {+ async ({ origin }) => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = origin;const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();@@ -7877,9 +7833,10 @@ describe("AgentServer HTTP Mode", () => {},);- it("returns PR-update prompt for existing PRs on Slack-origin runs", () => {+ it("returns PR-update prompt for existing PRs on Slack-origin runs", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt("https://github.com/org/repo/pull/1",);@@ -7903,7 +7860,7 @@ describe("AgentServer HTTP Mode", () => {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;});- it("includes --base flag when baseBranch is configured", () => {+ it("includes --base flag when baseBranch is configured", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";server = new AgentServer({port,@@ -7916,7 +7873,9 @@ describe("AgentServer HTTP Mode", () => {taskId: "test-task-id",runId: "test-run-id",baseBranch: "add-yolo-to-readme",+ selectProduct,});+ await openProduct(server, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (server as unknown as TestableServer).buildCloudSystemPrompt();@@ -7926,9 +7885,10 @@ describe("AgentServer HTTP Mode", () => {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;});- it("omits --base flag when baseBranch is not configured", () => {+ it("omits --base flag when baseBranch is not configured", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();expect(prompt).toContain("gh pr create --draft`");// Scoped to the create command; other sections mention the flag legitimately.@@ -7936,7 +7896,7 @@ describe("AgentServer HTTP Mode", () => {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;});- it("disables auto-publish for Slack-origin runs when createPr is false", () => {+ it("disables auto-publish for Slack-origin runs when createPr is false", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";server = new AgentServer({port,@@ -7949,7 +7909,9 @@ describe("AgentServer HTTP Mode", () => {taskId: "test-task-id",runId: "test-run-id",createPr: false,+ selectProduct,});+ await openProduct(server, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (server as unknown as TestableServer).buildCloudSystemPrompt();@@ -7958,7 +7920,7 @@ describe("AgentServer HTTP Mode", () => {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;});- it("disables auto-publish for existing PRs when createPr is false", () => {+ it("disables auto-publish for existing PRs when createPr is false", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";server = new AgentServer({port,@@ -7971,7 +7933,9 @@ describe("AgentServer HTTP Mode", () => {taskId: "test-task-id",runId: "test-run-id",createPr: false,+ selectProduct,});+ await openProduct(server, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (server as unknown as TestableServer).buildCloudSystemPrompt("https://github.com/org/repo/pull/1");@@ -7982,12 +7946,13 @@ describe("AgentServer HTTP Mode", () => {});describe("identity instructions", () => {- it("injects Slack identity for workflow Slack replies", () => {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- const s = createServer() as unknown as TestableServer;- s.slackReplyContext = true;+ it("injects Slack identity for workflow Slack replies", async () => {+ const s = createServer();+ await openProduct(s, "workflow", { slack_reply_context: true });- const prompt = s.buildCloudSystemPrompt();+ const prompt = (+ s as unknown as TestableServer+ ).buildCloudSystemPrompt();expect(prompt).toContain("# Identity");expect(prompt).toContain("You are replying in a Slack thread");@@ -8001,9 +7966,10 @@ describe("AgentServer HTTP Mode", () => {{ label: "repository, no PR", config: {} },])("injects PostHog Slack app identity for Slack-origin runs ($label)",- ({ config }) => {+ async ({ config }) => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer(config);+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();@@ -8026,9 +7992,10 @@ describe("AgentServer HTTP Mode", () => {{ label: "repository, no PR", config: {} },])("injects concise response-style guidance for Slack-origin runs ($label)",- ({ config }) => {+ async ({ config }) => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer(config);+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();@@ -8041,38 +8008,20 @@ describe("AgentServer HTTP Mode", () => {},);- it.each([- { checklist: true, expected: true },- { checklist: false, expected: false },- ])(- "asks for a plain-language task list only when the Slack reply streams it (checklist: $checklist)",- ({ checklist, expected }) => {- // The checklist is the Slack progress UI. Without it the task list is invisible,- // and asking for one only costs the agent turns.- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";- const s = createServer() as unknown as TestableServer;- s.slackProgressChecklist = checklist;-- const prompt = s.buildCloudSystemPrompt();-- expect(prompt.includes("# Progress checklist")).toBe(expected);- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- },- );-it.each([{ label: "no origin set", origin: undefined },{ label: "signal_report origin", origin: "signal_report" },{ label: "posthog_code origin", origin: "posthog_code" },])("omits response-style guidance for non-Slack runs ($label)",- ({ origin }) => {+ async ({ origin }) => {if (origin) {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = origin;} else {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;}const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();@@ -8081,9 +8030,10 @@ describe("AgentServer HTTP Mode", () => {},);- it("injects identity for Slack-origin runs with an existing PR", () => {+ it("injects identity for Slack-origin runs with an existing PR", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt("https://github.com/org/repo/pull/1",);@@ -8096,104 +8046,104 @@ describe("AgentServer HTTP Mode", () => {{ label: "no origin set", origin: undefined },{ label: "signal_report origin", origin: "signal_report" },{ label: "posthog_code origin", origin: "posthog_code" },- ])("omits identity block for non-Slack runs ($label)", ({ origin }) => {- if (origin) {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = origin;- } else {+ ])(+ "omits identity block for non-Slack runs ($label)",+ async ({ origin }) => {+ if (origin) {+ process.env.POSTHOG_CODE_INTERACTION_ORIGIN = origin;+ } else {+ delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;+ }+ const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);+ const prompt = (+ s as unknown as TestableServer+ ).buildCloudSystemPrompt();+ expect(prompt).not.toContain("# Identity");+ expect(prompt).not.toContain("PostHog Slack app");+ expect(prompt).not.toContain("# PostHog products first");delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- }+ },+ );+ });++ describe("PR body guidance (why context + brevity + footer)", () => {+ it("instructs Why, brevity, and the plain footer (no Slack link) when auto-creating a Slack PR without a thread URL", async () => {const s = createServer();+ await openProduct(s, "slack");+const prompt = (s as unknown as TestableServer).buildCloudSystemPrompt();- expect(prompt).not.toContain("# Identity");- expect(prompt).not.toContain("PostHog Slack app");- expect(prompt).not.toContain("# PostHog products first");- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;++ expect(prompt).toContain("gh pr create --draft");+ // why context+ expect(prompt).toContain("**Why**");+ expect(prompt).toContain("the reason the user asked for this change");+ // brevity+ expect(prompt).toContain("Keep the PR description brief");+ expect(prompt).toContain("do NOT enumerate every change");+ // plain footer, no Slack link; Slack-origin PRs are branded "PostHog"+ expect(prompt).toContain(+ "*Created with [PostHog](https://posthog.com?ref=pr)*",+ );+ expect(prompt).not.toContain("from a [Slack thread]");+ expect(prompt).not.toContain("PostHog Desktop](https://posthog.com");});- });- describe("PR body guidance (why context + brevity + footer)", () => {- it("instructs Why, brevity, and the plain footer (no Slack link) when auto-creating a Slack PR without a thread URL", () => {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";- try {+ it.each([+ {+ label: "Slack thread",+ origin: "slack",+ launchOptions: { slack_thread_url: SLACK_THREAD_URL },+ source: undefined,+ footer: `*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](${SLACK_THREAD_URL})*`,+ },+ {+ label: "inbox report on a signal_report run",+ origin: "signal_report",+ launchOptions: {},+ source: INBOX_REPORT,+ footer: `*Created with [PostHog](https://posthog.com?ref=pr) from an [inbox report](${INBOX_REPORT.url})*`,+ },+ {+ label: "Slack thread over the inbox report",+ origin: "slack",+ launchOptions: { slack_thread_url: SLACK_THREAD_URL },+ source: INBOX_REPORT,+ footer: `*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](${SLACK_THREAD_URL})*`,+ },+ {+ label: "inbox report on a desktop run",+ origin: "desktop",+ launchOptions: {},+ source: INBOX_REPORT,+ footer: `*Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr) from an [inbox report](${INBOX_REPORT.url})*`,+ },+ {+ label: "mobile client",+ origin: undefined,+ launchOptions: { client_platform: "mobile" },+ source: undefined,+ footer: "*Created with [PostHog Mobile](https://posthog.com?ref=pr)*",+ },+ ])(+ "embeds the $label footer",+ async ({ origin, launchOptions, source, footer }) => {+ const s = createServer({ autoPublish: true });+ await openProduct(s, origin, launchOptions, source);+const prompt = (- createServer() as unknown as TestableServer+ s as unknown as TestableServer).buildCloudSystemPrompt();- expect(prompt).toContain("gh pr create --draft");- // why context- expect(prompt).toContain("**Why**");- expect(prompt).toContain("the reason the user asked for this change");- // brevity- expect(prompt).toContain("Keep the PR description brief");- expect(prompt).toContain("do NOT enumerate every change");- // plain footer, no Slack link; Slack-origin PRs are branded "PostHog"- expect(prompt).toContain(- "*Created with [PostHog](https://posthog.com?ref=pr)*",- );- expect(prompt).not.toContain("from a [Slack thread]");- expect(prompt).not.toContain("PostHog Desktop](https://posthog.com");- } finally {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- }- });- it("embeds the Slack thread link in the footer when one is available", () => {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";- try {- const prompt = (- createServer() as unknown as TestableServer- ).buildCloudSystemPrompt(- null,- "https://posthog.slack.com/archives/C123/p456",- );- expect(prompt).toContain(- "*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](https://posthog.slack.com/archives/C123/p456)*",- );+ expect(prompt).toContain(footer);// The Why bullet no longer carries the thread link.expect(prompt).not.toContain("this task started from a Slack thread, also link it",);- } finally {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- }- });-- it("embeds the inbox report link in the footer for a signal_report run", () => {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "signal_report";- try {- const prompt = (- createServer() as unknown as TestableServer- ).buildCloudSystemPrompt(- null,- null,- "http://localhost:8000/project/1/inbox/rep_1",- );- expect(prompt).toContain(- "*Created with [PostHog](https://posthog.com?ref=pr) from an [inbox report](http://localhost:8000/project/1/inbox/rep_1)*",- );- expect(prompt).not.toContain("from a [Slack thread]");- } finally {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- }- });-- it("prefers the Slack thread link over the inbox report link when both are present", () => {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";- try {- const prompt = (- createServer() as unknown as TestableServer- ).buildCloudSystemPrompt(- null,- "https://posthog.slack.com/archives/C123/p456",- "http://localhost:8000/project/1/inbox/rep_1",- );- expect(prompt).toContain("from a [Slack thread]");- expect(prompt).not.toContain("from an [inbox report]");- } finally {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- }- });+ },+ );it("instructs Why, brevity, and the plain footer on the non-Slack no-repository path", () => {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;@@ -8211,23 +8161,17 @@ describe("AgentServer HTTP Mode", () => {expect(prompt).not.toContain("from a [Slack thread]");});- it("embeds the Slack thread link in the footer on the no-repository path when one is available", () => {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";- try {- const prompt = (- createServer({- repositoryPath: undefined,- }) as unknown as TestableServer- ).buildCloudSystemPrompt(- null,- "https://posthog.slack.com/archives/C123/p456",- );- expect(prompt).toContain(- "*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](https://posthog.slack.com/archives/C123/p456)*",- );- } finally {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;- }+ it("embeds the Slack thread link in the footer on the no-repository path when one is available", async () => {+ const s = createServer({ repositoryPath: undefined });+ await openProduct(s, "slack", { slack_thread_url: SLACK_THREAD_URL });++ const prompt = (+ s as unknown as TestableServer+ ).buildCloudSystemPrompt();++ expect(prompt).toContain(+ `*Created with [PostHog](https://posthog.com?ref=pr) from a [Slack thread](${SLACK_THREAD_URL})*`,+ );});});});@@ -8247,9 +8191,10 @@ describe("AgentServer HTTP Mode", () => {expect(context).not.toContain("gh pr checkout");});- it("avoids redundant PR checkout for auto-update runs", () => {+ it("avoids redundant PR checkout for auto-update runs", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const context = (s as unknown as TestableServer).buildDetectedPrContext(prUrl,);@@ -8265,7 +8210,7 @@ describe("AgentServer HTTP Mode", () => {delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;});- it("returns review-first PR context when createPr is false", () => {+ it("returns review-first PR context when createPr is false", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";server = new AgentServer({port,@@ -8278,7 +8223,9 @@ describe("AgentServer HTTP Mode", () => {taskId: "test-task-id",runId: "test-run-id",createPr: false,+ selectProduct,});+ await openProduct(server, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const context = (server as unknown as TestableServer).buildDetectedPrContext(prUrl);@@ -8306,36 +8253,40 @@ describe("AgentServer HTTP Mode", () => {expect(promise).toBeNull();});- it("does not check out when there is no prUrl", () => {+ it("does not check out when there is no prUrl", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const promise = (s as unknown as TestableServer).buildExistingPrCheckoutPromise(null);expect(promise).toBeNull();});- it("does not check out when createPr is false, even on a Slack-origin run", () => {+ it("does not check out when createPr is false, even on a Slack-origin run", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer({ createPr: false });+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const promise = (s as unknown as TestableServer).buildExistingPrCheckoutPromise(prUrl);expect(promise).toBeNull();});- it("does not check out when no repository is connected", () => {+ it("does not check out when no repository is connected", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer({ repositoryPath: undefined });+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const promise = (s as unknown as TestableServer).buildExistingPrCheckoutPromise(prUrl);expect(promise).toBeNull();});- it("starts a checkout when auto-publish is on for a Slack-origin run", () => {+ it("starts a checkout when auto-publish is on for a Slack-origin run", async () => {process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";const s = createServer();+ await openProduct(s, process.env.POSTHOG_CODE_INTERACTION_ORIGIN);const promise = (s as unknown as TestableServer).buildExistingPrCheckoutPromise(prUrl);diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.tsindex 523accfa9886..9d9d0386cd74 100644--- a/packages/agent/packages/agent/src/server/agent-server.ts+++ b/packages/agent/packages/agent/src/server/agent-server.ts@@ -46,7 +46,6 @@ import {} from "@posthog/harness/extensions/agent-instructions";import {appendBenjaminGuidance,- appendSte100Guidance,BENJAMIN_UPSTREAM_COMMIT,isBenjaminEnabled,} from "@posthog/harness/extensions/benjamin";@@ -119,6 +118,10 @@ import {type ResumeState,resumeFromLog,} from "../resume";+import type {+ ProductLaunchConfiguration,+ SessionBehavior,+} from "../sdk/product";import { SessionLogWriter } from "../session-log-writer";import type {AgentMode,@@ -166,6 +169,13 @@ import {checkoutExistingPullRequest,type ExistingPrCheckoutResult,} from "./pr-checkout";+import {+ appendClosingInstructions,+ openProductSession,+ readOriginProduct,+ readQuestionRequest,+ resolvePullRequestFooter,+} from "./product/session";import { createRtkSavingsNotification } from "./rtk-savings";import { RunUsageAccumulator, reportRunUsage, seedRunUsage } from "./run-usage";import {@@ -443,37 +453,6 @@ type SteerDeclineReason =| "adapter_rejected"| `adapter_${SteerDeclineCause}`;-/** Which delivery routes a Slack run has, as resolved by the backend from flags and Slack scopes. */-type SlackArtifactDelivery = "none" | "message" | "canvas_file";--const SLACK_ARTIFACT_DELIVERY_MODES: SlackArtifactDelivery[] = [- "none",- "message",- "canvas_file",-];--/**- * An unset key means the backend told us nothing — any non-Slack run, or a Slack run that- * predates this. Emit no constraints rather than guessing: the agent must never be offered a- * route delivery would reject, nor told it has none while it actually does.- */-function readSlackArtifactDelivery(- taskRun: TaskRun | null,-): SlackArtifactDelivery | null {- const mode = getTaskRunStateString(taskRun, "slack_artifact_delivery");- return SLACK_ARTIFACT_DELIVERY_MODES.find((known) => known === mode) ?? null;-}--/**- * Charts ride on their own key rather than a delivery mode: they need only the rollout- * flag, while canvas and file delivery also needs Slack scopes that are still in review,- * so a workspace can have charts and nothing else. Absent or non-boolean means a backend- * that predates charts, which is the same as off.- */-function readSlackChartDelivery(taskRun: TaskRun | null): boolean {- return taskRun?.state.slack_chart_delivery === true;-}-// Prompt block we hand the agent when the user attached files but we could not// load any of them into the session (missing from the run manifest, no storage// path, etc.). Without this the caller falls back to the bare task description —@@ -558,7 +537,7 @@ export class AgentServer {private eventStreamSender: TaskRunEventStreamSender | null = null;private readonly nextEventId = createEventIdSource();private rtkSavingsAttempted = false;- private questionRelayedToSlack = false;+ private questionAwaitingReply = false;private adapterEmittedTurnComplete = false;private suppressAdapterTurnComplete = false;private readonly cancelledStartupSessions = new WeakSet<ActiveSession>();@@ -566,11 +545,8 @@ export class AgentServer {private runUsageRunId: string | null = null;private detectedPrUrl: string | null = null;private stampedRunTraceId: string | null = null;- private slackArtifactDelivery: SlackArtifactDelivery | null = null;- private slackChartDelivery = false;- private slackProgressChecklist = false;- private slackReplyContext = false;- private mobileClient = false;+ private productSession: SessionBehavior = {};+ private productLaunch: ProductLaunchConfiguration;private taskRepositories: string[] = [];// Reset per session. `evaluatedPrUrls` dedupes per URL; `prAttributionChain` serializes// attributions so the most recently created PR in a run wins.@@ -701,6 +677,11 @@ export class AgentServer {constructor(config: AgentServerConfig) {this.config = config;+ this.productLaunch = {+ taskId: config.taskId,+ runId: config.runId,+ launchOptions: {},+ };this.bootTracker = new AgentBootTracker(config.runId,undefined,@@ -2238,27 +2219,8 @@ export class AgentServer {}).catch(() => {});}- const prUrl = getTaskRunStateString(preTaskRun, "slack_notified_pr_url");-- // Unconditional so a re-init on the same instance drops a stale PR URL.- this.detectedPrUrl = prUrl;-- const slackThreadUrl = getTaskRunStateString(- 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.- this.slackArtifactDelivery = readSlackArtifactDelivery(preTaskRun);- this.slackChartDelivery = readSlackChartDelivery(preTaskRun);- this.slackReplyContext = preTaskRun?.state.slack_reply_context === true;- this.mobileClient = preTaskRun?.state.client_platform === "mobile";- // Set by the backend on runs whose Slack reply streams the agent's task list.- this.slackProgressChecklist =- preTaskRun?.state.slack_app_agent_design_enabled === true;-// Web backlink to the inbox report that spawned this task, so the// auto-generated PR can point back at it. Built from the same pieces as the// report's `_posthogUrl`: <apiUrl>/project/<projectId>/inbox/<reportId>.@@ -2267,6 +2229,19 @@ export class AgentServer {? `${this.config.apiUrl.replace(/\/$/, "")}/project/${this.config.projectId}/inbox/${signalReportId}`: null;+ // Unconditional so a re-init on the same instance drops the previous run's product+ // behavior and PR URL.+ await this.openProductSession({+ taskId: payload.task_id,+ runId: payload.run_id,+ originProduct: readOriginProduct(),+ launchOptions: structuredClone(runState ?? {}),+ source: inboxReportUrl+ ? { label: "inbox report", url: inboxReportUrl }+ : undefined,+ });+ const prUrl = this.detectedPrUrl;+// Before the prompt: its skills-store section counts the stubs on disk.await this.installStoreSkills(payload.task_id,@@ -2299,8 +2274,6 @@ export class AgentServer {const sessionSystemPrompt = this.buildSessionSystemPrompt(prUrl,- slackThreadUrl,- inboxReportUrl,runStateSystemPromptData,);const codexInstructions =@@ -4545,27 +4518,21 @@ export class AgentServer {private buildSessionSystemPrompt(prUrl?: string | null,- slackThreadUrl?: string | null,- inboxReportUrl?: string | null,runStateSystemPrompt?: ClaudeCodeConfig["systemPrompt"],): string | { append: string } {- const cloudAppend = this.buildCloudSystemPrompt(- prUrl,- slackThreadUrl,- inboxReportUrl,- );+ const cloudAppend = this.buildCloudSystemPrompt(prUrl);const userPrompt =this.config.claudeCode?.systemPrompt ?? runStateSystemPrompt;+ const replySurface =+ this.productSession.replySurface ?? this.productLaunch.originProduct;const sessionPrompt = buildCloudSessionSystemPrompt(cloudAppend,userPrompt,- this.isSlackReplyContext() ? "slack" : this.getCloudInteractionOrigin(),+ replySurface,getProjectWebUrl(this.config.apiUrl, this.config.projectId),);- return this.isSlackReplyContext()- ? appendSte100Guidance(sessionPrompt)- : sessionPrompt;+ return appendClosingInstructions(sessionPrompt, this.productSession);}private buildCodexInstructions(@@ -4608,39 +4575,33 @@ export class AgentServer {return { claudeCode: { options } };}- private getCloudInteractionOrigin(): string | undefined {- return (- process.env.POSTHOG_CODE_INTERACTION_ORIGIN ??- process.env.CODE_INTERACTION_ORIGIN ??- process.env.TWIG_INTERACTION_ORIGIN- );- }-- private isSlackReplyContext(): boolean {- return (- this.slackReplyContext || this.getCloudInteractionOrigin() === "slack"+ private async openProductSession(+ launch: ProductLaunchConfiguration,+ ): Promise<void> {+ this.productLaunch = launch;+ this.productSession = {};+ this.productSession = await openProductSession(+ this.config.selectProduct,+ launch,+ this.posthogAPI,+ (message, error) => this.reportProductFailure(message, error),);+ this.detectedPrUrl = this.productSession.pullRequests?.existingUrl ?? null;}- /**- * Automated, PostHog-branded origins: the Slack app and the Self-driving- * inbox. These both auto-publish by default and attribute their PRs to- * "PostHog" rather than the PostHog Desktop app.- */- private isAutomatedOrigin(): boolean {- const origin = this.getCloudInteractionOrigin();- return origin === "slack" || origin === "signal_report";+ private productAutoPublishes(): boolean {+ return this.productSession.pullRequests?.autoPublish === true;}/**- * Automated-origin cloud runs auto-publish by default, and manual runs- * auto-publish when the user opted in (Settings → Advanced, sent as+ * Products such as the Slack app and the Self-driving inbox auto-publish by+ * default, and manual runs auto-publish when the user opted in (Settings → Advanced, sent as* autoPublish). Every other run is review-first unless the user explicitly* asks, and createPr=false always disables publishing.*/private shouldAutoPublishCloudChanges(): boolean {return (- (this.isAutomatedOrigin() || this.config.autoPublish === true) &&+ (this.productAutoPublishes() || this.config.autoPublish === true) &&this.config.createPr !== false);}@@ -4668,7 +4629,7 @@ export class AgentServer {!this.autoPublishStateResolved &&this.config.autoPublish !== true &&this.config.createPr !== false &&- !this.isAutomatedOrigin();+ !this.productAutoPublishes();if (!shouldResolveReasoning &&!shouldResolveStoreSkills &&@@ -4770,7 +4731,7 @@ export class AgentServer {if (this.config.autoPublish === true ||this.config.createPr === false ||- this.isAutomatedOrigin()+ this.productAutoPublishes()) {// The boot decision already publishes (or never may) — nothing to upgrade.this.autoPublishStateResolved = true;@@ -4832,15 +4793,11 @@ export class AgentServer {baseBranch: this.config.baseBranch,createPr: this.config.createPr,hasGithubToken: Boolean(resolveGithubToken()),- isAutomatedOrigin: this.isAutomatedOrigin(),- mobileClient: this.mobileClient,- isSlack: this.isSlackReplyContext(),+ identityInstructions: this.productSession.identityInstructions,+ deliveryInstructions: this.productSession.deliveryInstructions,projectId: this.config.projectId,repositoryAttached: Boolean(this.config.repositoryPath),shouldAutoPublish: this.shouldAutoPublishCloudChanges(),- slackArtifactDelivery: this.slackArtifactDelivery,- slackChartDelivery: this.slackChartDelivery,- slackProgressChecklist: this.slackProgressChecklist,storeSkillsInstalledCount: this.storeSkillsInstalledCount,taskId: this.config.taskId,taskRepositories: this.taskRepositories,@@ -4851,15 +4808,10 @@ export class AgentServer {return this.getCloudTaskPrompt().buildDetectedPrContext(prUrl);}- private buildCloudSystemPrompt(- prUrl?: string | null,- slackThreadUrl?: string | null,- inboxReportUrl?: string | null,- ): string {+ private buildCloudSystemPrompt(prUrl?: string | null): string {return this.getCloudTaskPrompt().buildCloudSystemPrompt(prUrl,- slackThreadUrl,- inboxReportUrl,+ resolvePullRequestFooter(this.productSession, this.productLaunch),);}@@ -5069,19 +5021,19 @@ export class AgentServer {return gatewayEnv;}- private buildSlackQuestionRelayResponse(- payload: JwtPayload,- toolMeta: Record<string, unknown> | null | undefined,+ private handleProductQuestion(+ params: RequestPermissionRequest,+ handleQuestions: NonNullable<SessionBehavior["handleQuestions"]>,): RequestPermissionResponse {- this.relaySlackQuestion(payload, toolMeta);+ const response = handleQuestions(+ readQuestionRequest(params.toolCall._meta?.questions),+ );+ if (response.awaitingReply) {+ this.questionAwaitingReply = true;+ }return {- outcome: { outcome: "cancelled" as const },- _meta: {- message:- "This question has been relayed to the Slack thread where this task originated. " +- "The user will reply there. Do NOT re-ask the question or pick an answer yourself. " +- "Simply let the user know you are waiting for their reply.",- },+ outcome: { outcome: "cancelled" },+ _meta: { message: response.message },};}@@ -5145,10 +5097,7 @@ export class AgentServer {private createCloudClient(payload: JwtPayload) {const mode = this.getEffectiveMode(payload);- const interactionOrigin =- process.env.POSTHOG_CODE_INTERACTION_ORIGIN ??- process.env.CODE_INTERACTION_ORIGIN ??- process.env.TWIG_INTERACTION_ORIGIN;+ const originProduct = this.productLaunch.originProduct;return {requestPermission: async (@@ -5156,7 +5105,7 @@ export class AgentServer {): Promise<RequestPermissionResponse> => {this.logger.debug("Permission request", {mode,- interactionOrigin,+ originProduct,kind: params.toolCall?.kind,options: params.options,});@@ -5170,14 +5119,14 @@ export class AgentServer {const codeToolKind = params.toolCall?._meta?.codeToolKind;const isPlanApproval = params.toolCall?.kind === "switch_mode";- // Relay questions to Slack when interaction originated there- if (interactionOrigin === "slack") {- if (codeToolKind === "question") {- return this.buildSlackQuestionRelayResponse(- payload,- params.toolCall?._meta,- );- }+ if (+ codeToolKind === "question" &&+ this.productSession.handleQuestions+ ) {+ return this.handleProductQuestion(+ params,+ this.productSession.handleQuestions,+ );}// Tools on relayed MCP servers execute on the user's machine with@@ -5357,15 +5306,15 @@ export class AgentServer {return;}- if (this.questionRelayedToSlack) {- this.questionRelayedToSlack = false;+ if (this.questionAwaitingReply) {+ this.questionAwaitingReply = false;return;}try {await this.session.logWriter.flush(payload.run_id, { coalesce: true });} catch (error) {- this.logger.debug("Failed to flush logs before Slack relay", {+ this.logger.debug("Failed to flush logs before relaying the reply", {taskId: payload.task_id,runId: payload.run_id,error,@@ -5374,7 +5323,7 @@ export class AgentServer {const message = this.session.logWriter.getFullAgentResponse(payload.run_id);if (!message) {- this.logger.debug("No agent message found for Slack relay", {+ this.logger.debug("No agent message found to relay", {taskId: payload.task_id,runId: payload.run_id,sessionRegistered: this.session.logWriter.isRegistered(payload.run_id),@@ -5400,89 +5349,25 @@ export class AgentServer {traceId,);} catch (error) {- this.logger.debug("Failed to relay initial agent response to Slack", {- taskId: payload.task_id,- runId: payload.run_id,- error,+ this.reportProductFailure("Failed to relay the agent reply", error, {+ messageId,});}}- private relaySlackQuestion(- payload: JwtPayload,- toolMeta: Record<string, unknown> | null | undefined,+ private reportProductFailure(+ message: string,+ error: unknown,+ details: Record<string, unknown> = {},): void {- const firstQuestion = this.getFirstQuestionMeta(toolMeta);- if (!this.isQuestionMeta(firstQuestion)) {- return;- }-- let message = `*${firstQuestion.question}*\n\n`;- if (firstQuestion.options?.length) {- firstQuestion.options.forEach(- (opt: { label: string; description?: string }, i: number) => {- message += `${i + 1}. *${opt.label}*`;- if (opt.description) message += ` — ${opt.description}`;- message += "\n";- },- );- }- message += "\nReply in this thread with your choice.";-- this.questionRelayedToSlack = true;- this.posthogAPI- .relayMessage(payload.task_id, payload.run_id, message)- .catch((err) =>- this.logger.debug("Failed to relay question to Slack", { err }),- );- }-- private getFirstQuestionMeta(- toolMeta: Record<string, unknown> | null | undefined,- ): unknown {- if (!toolMeta) {- return null;- }-- const questionsValue = toolMeta.questions;- if (!Array.isArray(questionsValue) || questionsValue.length === 0) {- return null;- }-- return questionsValue[0];- }-- private isQuestionMeta(value: unknown): value is {- question: string;- options?: Array<{ label: string; description?: string }>;- } {- if (!value || typeof value !== "object") {- return false;- }-- const candidate = value as {- question?: unknown;- options?: unknown;+ const data = {+ taskId: this.config.taskId,+ runId: this.config.runId,+ error: getErrorMessage(error),+ ...details,};-- if (typeof candidate.question !== "string") {- return false;- }-- if (candidate.options === undefined) {- return true;- }-- if (!Array.isArray(candidate.options)) {- return false;- }-- return candidate.options.every(- (option) =>- !!option &&- typeof option === "object" &&- typeof (option as { label?: unknown }).label === "string",- );+ this.logger.error(message, data);+ this.emitConsoleLog("error", "product", message, data);}private maybeAttachCreatedPr(diff --git a/packages/agent/packages/agent/src/server/bin.ts b/packages/agent/packages/agent/src/server/bin.tsindex f515366fa8bc..de6b65257157 100644--- a/packages/agent/packages/agent/src/server/bin.ts+++ b/packages/agent/packages/agent/src/server/bin.ts@@ -9,6 +9,7 @@ import { DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE } from "@posthog/harness/eimport { Command } from "commander";import { z } from "zod/v4";import { isSupportedReasoningEffort } from "../adapters/reasoning-effort";+import { selectProduct } from "../boot/select-product";import { AgentServer } from "./agent-server";import { launcherToProcessMs } from "./boot-phases";import { CredentialRelayError } from "./credential-relay";@@ -304,6 +305,7 @@ programconst serverConfig: AgentServerConfig = {port: parseInt(options.port, 10),+ selectProduct,agentStateDir: env.POSTHOG_AGENT_STATE_DIR,jwtPublicKey: env.JWT_PUBLIC_KEY,eventIngestToken: env.POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN,diff --git a/packages/agent/packages/agent/src/server/product/session.ts b/packages/agent/packages/agent/src/server/product/session.tsnew file mode 100644index 000000000000..69f5ae98e8bb--- /dev/null+++ b/packages/agent/packages/agent/src/server/product/session.ts@@ -0,0 +1,81 @@+import { z } from "zod";+import type { PostHogAPIClient } from "../../posthog-api";+import {+ buildPullRequestFooter,+ type ProductLaunchConfiguration,+ type ProductSelector,+ type QuestionRequest,+ type SessionBehavior,+} from "../../sdk/product";++type SystemPrompt = string | { append: string };++const questionSchema = z.object({+ question: z.string(),+ options: z+ .array(+ z.object({+ label: z.string(),+ description: z.string().optional().catch(undefined),+ }),+ )+ .optional(),+});++export function readOriginProduct(): string | undefined {+ return (+ process.env.POSTHOG_CODE_INTERACTION_ORIGIN ??+ process.env.CODE_INTERACTION_ORIGIN ??+ process.env.TWIG_INTERACTION_ORIGIN+ );+}++export async function openProductSession(+ selectProduct: ProductSelector | undefined,+ launch: ProductLaunchConfiguration,+ api: Pick<PostHogAPIClient, "relayMessage">,+ reportFailure: (message: string, error: unknown) => void,+): Promise<SessionBehavior> {+ const product = selectProduct?.(launch);+ if (!product) {+ return {};+ }+ return product.configureSession({+ launch,+ services: {+ sendReply: (reply) =>+ api+ .relayMessage(launch.taskId, launch.runId, reply.message)+ .catch((error) => reportFailure("Failed to send a reply", error)),+ },+ });+}++export function resolvePullRequestFooter(+ session: SessionBehavior,+ launch: ProductLaunchConfiguration,+): string {+ return (+ session.pullRequests?.footer ??+ buildPullRequestFooter(launch, { source: launch.source })+ );+}++export function appendClosingInstructions(+ prompt: SystemPrompt,+ session: SessionBehavior,+): SystemPrompt {+ const closing = session.closingInstructions;+ if (!closing) {+ return prompt;+ }+ const text = typeof prompt === "string" ? prompt : prompt.append;+ const combined = [text, closing].filter(Boolean).join("\n\n");+ return typeof prompt === "string" ? combined : { append: combined };+}++export function readQuestionRequest(questions: unknown): QuestionRequest {+ const firstQuestion = Array.isArray(questions) ? questions[0] : undefined;+ const parsed = questionSchema.safeParse(firstQuestion);+ return { questions: parsed.success ? [parsed.data] : [] };+}diff --git a/packages/agent/packages/agent/src/server/question-relay.test.ts b/packages/agent/packages/agent/src/server/question-relay.test.tsindex 94ddb16ce334..419befade0f0 100644--- a/packages/agent/packages/agent/src/server/question-relay.test.ts+++ b/packages/agent/packages/agent/src/server/question-relay.test.ts@@ -10,7 +10,9 @@ import {vi,} from "vitest";import { classifyAgentError } from "../adapters/error-classification";+import { selectProduct } from "../boot/select-product";import type { PostHogAPIClient } from "../posthog-api";+import type { ProductLaunchConfiguration } from "../sdk/product";import {createTaskRun,createTestRepo,@@ -29,9 +31,8 @@ import type { ContextSelection } from "./context-selection";interface TestableAgentServer {createContextSelection(runId: string): ContextSelection;posthogAPI: PostHogAPIClient;- isQuestionMeta: (value: unknown) => boolean;- getFirstQuestionMeta: (meta: unknown) => unknown;- relaySlackQuestion: (payload: Record<string, unknown>, meta: unknown) => void;+ openProductSession: (launch: ProductLaunchConfiguration) => Promise<void>;+ emitConsoleLog: (...args: unknown[]) => void;createCloudClient: (payload: Record<string, unknown>) => {requestPermission: (opts: {options: unknown[];@@ -41,7 +42,7 @@ interface TestableAgentServer {_meta?: { message?: string; answers?: Record<string, string> };}>;};- questionRelayedToSlack: boolean;+ questionAwaitingReply: boolean;session: unknown;relayAgentResponse: (payload: Record<string, unknown>,@@ -193,6 +194,7 @@ describe("Question relay", () => {mode: "interactive",taskId: "test-task-id",runId: "test-run-id",+ selectProduct,}) as unknown as TestableAgentServer;});@@ -201,121 +203,88 @@ describe("Question relay", () => {await repo.cleanup();});- describe("isQuestionMeta", () => {- it.each([- ["null", null],- ["undefined", undefined],- ["number", 42],- ["string", "not a question"],- ["object without question field", { options: [] }],- ["object with non-string question", { question: 123 }],- ["object with non-array options", { question: "Q?", options: "bad" }],- [- "object with invalid option items",- { question: "Q?", options: [{ notLabel: "x" }] },- ],- ])("rejects %s", (_label, value) => {- expect(server.isQuestionMeta(value)).toBe(false);- });-- it.each([- [- "question with options",- {- question: "Pick one",- options: [{ label: "A", description: "desc" }, { label: "B" }],- },- ],- ["question without options", { question: "What do you think?" }],- ["question with empty options", { question: "Confirm?", options: [] }],- ])("accepts %s", (_label, value) => {- expect(server.isQuestionMeta(value)).toBe(true);- });- });-- describe("getFirstQuestionMeta", () => {- it.each([- ["null meta", null],- ["undefined meta", undefined],- ["meta without questions", { other: "field" }],- ["meta with empty questions array", { questions: [] }],- ["meta with non-array questions", { questions: "not-array" }],- ])("returns null for %s", (_label, meta) => {- expect(server.getFirstQuestionMeta(meta)).toBeNull();- });-- it("returns first question from valid meta", () => {- const result = server.getFirstQuestionMeta(QUESTION_META);- expect(result).toEqual(QUESTION_META.questions[0]);- });- });-- describe("relaySlackQuestion", () => {- it("relays formatted question with options via posthogAPI", () => {- const relaySpy = vi- .spyOn(server.posthogAPI, "relayMessage")- .mockResolvedValue(undefined);-- server.relaySlackQuestion(TEST_PAYLOAD, QUESTION_META);-- expect(relaySpy).toHaveBeenCalledOnce();- const [taskId, runId, message] = relaySpy.mock.calls[0];- expect(taskId).toBe("test-task-id");- expect(runId).toBe("test-run-id");- expect(message).toContain("*Which license should I use?*");- expect(message).toContain("1. *MIT*");- expect(message).toContain("Permissive license");- expect(message).toContain("2. *Apache 2.0*");- expect(message).toContain("3. *GPL v3*");- expect(message).toContain("Reply in this thread");- });-- it("sets questionRelayedToSlack flag", () => {- vi.spyOn(server.posthogAPI, "relayMessage").mockResolvedValue(undefined);-- server.relaySlackQuestion(TEST_PAYLOAD, QUESTION_META);- expect(server.questionRelayedToSlack).toBe(true);- });-- it("does not relay when meta has no valid question", () => {- const relaySpy = vi- .spyOn(server.posthogAPI, "relayMessage")- .mockResolvedValue(undefined);-- server.relaySlackQuestion(TEST_PAYLOAD, { codeToolKind: "question" });- expect(server.questionRelayedToSlack).toBe(false);- expect(relaySpy).not.toHaveBeenCalled();- });- });-describe("createCloudClient requestPermission", () => {const ALLOW_OPTIONS = [{ kind: "allow_once", optionId: "allow", name: "Allow" },];- describe("with POSTHOG_CODE_INTERACTION_ORIGIN=slack", () => {- beforeEach(() => {- process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";+ describe("with the Slack product", () => {+ beforeEach(async () => {+ await server.openProductSession({+ taskId: "test-task-id",+ runId: "test-run-id",+ originProduct: "slack",+ launchOptions: {},+ });});- afterEach(() => {- delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;+ it("relays the question to the thread and tells the agent to wait", async () => {+ const relaySpy = vi+ .spyOn(server.posthogAPI, "relayMessage")+ .mockResolvedValue(undefined);+ const client = server.createCloudClient(TEST_PAYLOAD);++ const result = await client.requestPermission({+ options: ALLOW_OPTIONS,+ toolCall: { toolCallId: "question-1", _meta: QUESTION_META },+ });++ expect(result.outcome.outcome).toBe("cancelled");+ expect(result._meta?.message).toContain("relayed to the Slack thread");+ expect(result._meta?.message).toContain("Do NOT re-ask the question");+ expect(server.questionAwaitingReply).toBe(true);+ const [taskId, runId, message] = relaySpy.mock.calls[0];+ expect([taskId, runId]).toEqual(["test-task-id", "test-run-id"]);+ expect(message).toBe(+ "*Which license should I use?*\n\n" ++ "1. *MIT* — Permissive license\n" ++ "2. *Apache 2.0* — Patent grant included\n" ++ "3. *GPL v3* — Copyleft license\n" ++ "\nReply in this thread with your choice.",+ );});- it("returns cancelled with relay message for question tool", async () => {- vi.spyOn(server.posthogAPI, "relayMessage").mockResolvedValue(- undefined,+ it("reports a failed question relay in the run log", async () => {+ vi.spyOn(server.posthogAPI, "relayMessage").mockRejectedValue(+ new Error("relay down"),);+ server.emitConsoleLog = vi.fn();const client = server.createCloudClient(TEST_PAYLOAD);const result = await client.requestPermission({options: ALLOW_OPTIONS,- toolCall: { _meta: QUESTION_META },+ toolCall: { toolCallId: "question-1", _meta: QUESTION_META },});- expect(result.outcome.outcome).toBe("cancelled");expect(result._meta?.message).toContain("relayed to the Slack thread");- expect(result._meta?.message).toContain("Do NOT re-ask the question");+ await vi.waitFor(() =>+ expect(server.emitConsoleLog).toHaveBeenCalledWith(+ "error",+ "product",+ "Failed to send a reply",+ expect.objectContaining({ error: "relay down" }),+ ),+ );+ });++ it("does not relay a question without valid question metadata", async () => {+ const relaySpy = vi.spyOn(server.posthogAPI, "relayMessage");+ const client = server.createCloudClient({+ ...TEST_PAYLOAD,+ mode: "background",+ });++ const result = await client.requestPermission({+ options: ALLOW_OPTIONS,+ toolCall: {+ toolCallId: "question-1",+ _meta: { codeToolKind: "question" },+ },+ });++ expect(result.outcome.outcome).toBe("cancelled");+ expect(relaySpy).not.toHaveBeenCalled();+ expect(server.questionAwaitingReply).toBe(false);});it("auto-approves non-question tools", async () => {@@ -577,7 +546,7 @@ describe("Question relay", () => {});describe("relayAgentResponse duplicate suppression", () => {- it("skips relay when questionRelayedToSlack is set", async () => {+ it("skips relay when the agent waits for a question reply", async () => {const relaySpy = vi.spyOn(server.posthogAPI, "relayMessage").mockResolvedValue(undefined);@@ -591,14 +560,14 @@ describe("Question relay", () => {},};- server.questionRelayedToSlack = true;+ server.questionAwaitingReply = true;await server.relayAgentResponse(TEST_PAYLOAD);- expect(server.questionRelayedToSlack).toBe(false);+ expect(server.questionAwaitingReply).toBe(false);expect(relaySpy).not.toHaveBeenCalled();});- it("relays normally when questionRelayedToSlack is not set", async () => {+ it("relays normally when no question waits for a reply", async () => {const relaySpy = vi.spyOn(server.posthogAPI, "relayMessage").mockResolvedValue(undefined);@@ -615,7 +584,6 @@ describe("Question relay", () => {},};- server.questionRelayedToSlack = false;await server.relayAgentResponse(TEST_PAYLOAD);expect(relaySpy).toHaveBeenCalledWith(@@ -643,7 +611,6 @@ describe("Question relay", () => {},};- server.questionRelayedToSlack = false;await server.relayAgentResponse(TEST_PAYLOAD,"msg-123",@@ -674,11 +641,35 @@ describe("Question relay", () => {},};- server.questionRelayedToSlack = false;await server.relayAgentResponse(TEST_PAYLOAD);expect(relaySpy).not.toHaveBeenCalled();});++ it("reports a failed relay in the run log", async () => {+ server.emitConsoleLog = vi.fn();+ server.session = {+ payload: TEST_PAYLOAD,+ logWriter: {+ flush: vi.fn().mockResolvedValue(undefined),+ getFullAgentResponse: vi.fn().mockReturnValue("agent response"),+ getAgentResponseParts: vi.fn().mockReturnValue(["agent response"]),+ isRegistered: vi.fn().mockReturnValue(true),+ },+ };+ vi.spyOn(server.posthogAPI, "relayMessage").mockRejectedValue(+ new Error("relay down"),+ );++ await server.relayAgentResponse(TEST_PAYLOAD, "msg-1");++ expect(server.emitConsoleLog).toHaveBeenCalledWith(+ "error",+ "product",+ "Failed to relay the agent reply",+ expect.objectContaining({ messageId: "msg-1", error: "relay down" }),+ );+ });});describe("sendInitialTaskMessage prompt source", () => {diff --git a/packages/agent/packages/agent/src/server/types.ts b/packages/agent/packages/agent/src/server/types.tsindex 38ba874f9285..959028c5f8db 100644--- a/packages/agent/packages/agent/src/server/types.ts+++ b/packages/agent/packages/agent/src/server/types.ts@@ -3,6 +3,7 @@ import type {EffortLevel,ServiceTier,} from "@posthog/agent-contracts/domain-types";+import type { ProductSelector } from "../sdk/product";import type { AgentMode } from "../types";import type { RtkSavingsSummary } from "./rtk-savings";@@ -15,6 +16,7 @@ export interface ClaudeCodeConfig {export interface AgentServerConfig {port: number;+ selectProduct?: ProductSelector;agentStateDir?: string;repositoryPath?: string;repoReadyFile?: string;diff --git a/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts b/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.tsindex cbdfbd3b5b7a..3220889d7da2 100644--- a/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts+++ b/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts@@ -10,23 +10,16 @@ import {TASK_SUMMARY_TOOL_NAME,} from "./task-summary";-export type SlackArtifactDelivery = "none" | "message" | "canvas_file";-export interface CloudTaskPromptOptions {apiUrl: string;baseBranch?: string;createPr?: boolean;- isAutomatedOrigin: boolean;- mobileClient?: boolean;- isSlack: boolean;+ identityInstructions?: string;+ deliveryInstructions?: string;projectId: number;hasGithubToken: boolean;repositoryAttached: boolean;shouldAutoPublish: boolean;- slackArtifactDelivery: SlackArtifactDelivery | null;- slackChartDelivery: boolean;- // The Slack thread draws the agent's task list as a live checklist.- slackProgressChecklist: boolean;storeSkillsInstalledCount: number;taskId: string;taskRepositories: string[];@@ -58,66 +51,6 @@ export class CloudTaskPrompt {);}- /**- * How this run may hand a deliverable to the Slack thread it is answering in.- *- * The offer has to match what delivery will actually accept: naming an adapter the- * workspace cannot use gets the request rejected server-side after the agent has already- * promised the user a canvas or a spreadsheet. The backend resolves that capability from- * the workspace's feature flags and Slack scopes when the task starts and hands it to us- * on the run state, so the wording lives here and the gating stays there.- */- private buildSlackDeliveryInstructions(): string {- if (this.options.slackArtifactDelivery === null) {- return "";- }-- if (this.options.slackArtifactDelivery === "none") {- return `-## Delivering to Slack-- You do not have artifact delivery in this workspace: you cannot create or share artifacts (files, canvases, documents) from this run, so do not attempt to. Deliver results as plain text in your reply.-- Do not attach, upload, link to, or expose run artifacts or local working files, including /tmp/workspace paths.`;- }-- const endpoint = `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/`;- const preamble = `-## Delivering to Slack-- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.-- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.-- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, user uploads) are internal: never deliver them to Slack or mention them in your reply.`;-- // Charts attach to both modes: they post as an image block referencing a PostHog-hosted- // url, so they work wherever the workspace can post at all.- const chartBullets = this.options.slackChartDelivery- ? `-- When an analytics answer is naturally visual (a trend over time, funnel, breakdown comparison, retention curve), deliver a chart image by default alongside the summary. Do not wait for the user to say "chart". Skip the image only when the result is a single number, a short list, or the user asked for raw data.-- To show a chart in Slack (a saved insight or an ad-hoc analytics query result), make a single call: POST to \`${endpoint}chart/\` with \`$POSTHOG_PERSONAL_API_KEY\` and body \`{"name": "<chart title>", "query": <query JSON, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}>}\`, or \`{"name": "<chart title>", "insight_id": <numeric insight id>}\` for a saved insight. It renders the chart server-side and registers it for Slack delivery in one step, blocking until done (typically a few seconds).-- The chart renders directly under your answer text with its name as the title, so do not restate the title or announce the chart ("Here's a chart of…"). Spend your answer text on the takeaway instead: the trend, inflection points, spikes, or drops a reader should notice, with numbers where they matter. Each chart is delivered with an "Open in PostHog" button, so do not paste the response \`url\` into your answer unless the user explicitly asks for a link. Do not download, view, or re-upload the image yourself.-- Report a chart failure rather than retrying blindly: a 400 carries the reason in \`error\`, or in \`detail\` when the request body itself was rejected, and a 429 means the project's chart render limit is saturated, so answer without the chart.-- SQL results cannot be charted yet, because the chart endpoint rejects SQL queries. Chart with an insight query (e.g. TrendsQuery) when the question can be expressed as one; otherwise summarize the SQL result in your answer text.`- : "";-- if (this.options.slackArtifactDelivery === "message") {- const chartException = this.options.slackChartDelivery- ? " Chart images are the one exception: deliver them through the dedicated chart endpoint below, never through the generic living-artifacts endpoint."- : "";- const unsupportedDeliverable = this.options.slackChartDelivery- ? "- If a deliverable cannot be expressed as a Slack message or a chart image (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead."- : "- If a deliverable cannot be expressed as a Slack message (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead.";- return `${preamble}-- You do not have canvas or file delivery in this workspace: do not use the \`slack_canvas\` or \`slack_file\` adapters, and do not promise a canvas, uploaded spreadsheet, or downloadable file.${chartException}-- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\` using adapter \`slack_message\`. To update a prior deliverable, GET the returned artifact id or POST new \`content\` to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}-${unsupportedDeliverable}`;- }-- return `${preamble}-- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\`; choose adapter \`slack_canvas\`, \`slack_message\`, \`slack_file\`, or \`document_connector\`. Use \`adapter=slack_file\` with \`content_base64\` for binary deliverables such as .xlsx/.pdf/.docx, or \`source_artifact_id\` / \`source_storage_path\` for a file you already uploaded as a \`type=output\` run artifact.-- To update a prior deliverable, GET the returned artifact id or POST new \`content\`, \`content_base64\`, or source artifact fields to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}-- Do not paste living-artifact Slack file links or permalinks into your final Slack answer unless the user explicitly asks for the URL. The Slack relay attaches pending files and canvas cards to your final answer automatically after you finish, so mention the artifact by name only if useful.-- A pending delivery status only means the artifact waits for your final answer. Do not check it again, and do not tell the user that a link or file has not arrived.-- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead.`;- }-private buildGithubAccessInstructions(hasGithubToken: boolean): string {if (hasGithubToken) {return `@@ -150,12 +83,10 @@ Only when the requested work requires unavailable private repository or publishi// parallel sessions of one ReviewHog review, then send the same prefix, and the provider serves// it from its prompt cache. A per-task value breaks the cache for every token after it.buildCloudSystemPrompt(- prUrl?: string | null,- slackThreadUrl?: string | null,- inboxReportUrl?: string | null,+ prUrl: string | null | undefined,+ prFooter: string,): string {const shouldAutoCreatePr = this.options.shouldAutoPublish;- const isSlack = this.options.isSlack;// Every instruction in this section runs through `gh`, so a sandbox holding no// GitHub token cannot act on any of it. An empty token is an explicit logout.const hasGithubToken = this.options.hasGithubToken;@@ -168,44 +99,7 @@ To \`@\`-mention them in a body or a comment, read their handle with \`gh api usIf the command fails, or returns a name ending in \`[bot]\`, you are acting as the PostHog app rather than as a person: ask them for their GitHub login instead of assigning or mentioning anyone.`: "";- const slackIdentityInstructions = isSlack- ? `-# Identity-You are the PostHog Slack app, PostHog's agent for helping users with their product data and coding tasks from Slack. When introducing yourself or referring to yourself in messages to the user, identify as "PostHog Slack app". Do NOT refer to yourself as Claude, an Anthropic assistant, or any underlying model name.--# Response Style-You are replying in a Slack thread. Slack readers want short, skimmable answers — be concise by default.-- Answer simple questions in a single sentence. Keep everything else brief — a few sentences at most.-- Lead with the answer or the outcome. Skip preamble, restating the question, and sign-offs.-- Prefer plain prose. Treat bullet lists as the exception, not the norm, and avoid headers and tables unless they genuinely make a complex answer clearer.-- Do not narrate your thinking or list every step you took; report what matters and the result.-- This is a default, not a hard rule. If the user (or their saved memory) asks for more depth or a specific format, follow that instead.--# PostHog products first-PostHog is a product suite, not just analytics — session replay, feature flags, experiments, surveys, error tracking, logs, data warehouse, CDP, messaging, and customer support all ship as PostHog products.-- When someone asks how to set up, enable, configure, or use a capability, assume they mean PostHog's version of it and answer about that.-- Search our docs with the \`docs-search\` tool before you answer, and ground the answer in what it returns rather than in what you remember. The product changes faster than your training data.-- Never send the user to a third-party product for something PostHog does. If you are unsure whether we cover it, search the docs before concluding we don't — and if we genuinely don't, say so plainly instead of recommending a competitor. Pointing at a third party we integrate with, as a source or destination, is fine.-- When a request could mean either a PostHog feature or something in the user's own codebase, ask which they mean instead of guessing.--# Mentioning users-To ping a Slack user, reuse a \`<@U…|displayname>\` token that already appears in the message context — copy it verbatim, including the \`U…\` ID. Do NOT construct a mention token from a name, and do NOT substitute the display name (or any other string) for the \`U…\` ID — \`<@Jane|Jane Doe>\` is not a valid mention; only the form with the real ID like \`<@U01ABCDEF23|Jane Doe>\` is. If the person you want to refer to has no \`<@U…|displayname>\` token anywhere in the thread context, write their name as plain text instead of inventing one. These \`<@U…>\` tokens are Slack-only: never carry one — or a name or handle derived from it — into a GitHub PR, commit message, or review request as an \`@\`-mention. A Slack display name or handle is NOT a GitHub username; see the pull-request instructions below.--# Suggesting code changes-You can also open pull requests directly from this Slack thread. When the user's question describes a problem with a plausible code-side fix — a bug visible in errors or logs, missing or broken instrumentation, a broken funnel step traceable to UI code, a stale config that lives in a repo — end your reply with a one-sentence offer to open a PR for the fix and ask if they want you to proceed. Skip the offer for pure data lookups with no actionable code change (e.g. "what was DAU yesterday?"), and skip it when the fix would clearly live outside any repo you can reach.-`- : "";- const slackProgressInstructions =- isSlack && this.options.slackProgressChecklist- ? `-# Progress checklist-The Slack thread shows your task list as a live checklist, and it is the only progress the user sees while you work. Before your first tool call, create the task list with your task tools (TaskCreate and TaskUpdate, or update_plan): 2 to 5 tasks, each one outcome the user cares about. Mark a task in progress when you start it and completed when you finish it. Add a task when the work grows.-- Write each task in plain words for someone who does not read code, for example "Find the signup event" or "Count weekly signups".-- Do not put tool names, file paths, SQL, or IDs in a task.-- Skip the list only when you answer without any tool call.-`- : "";- const identityInstructions = `${slackIdentityInstructions}${slackProgressInstructions}${githubIdentityInstructions}`;+ const identityInstructions = `${this.options.identityInstructions ?? ""}${githubIdentityInstructions}`;const signedCommitInstructions = `## Committing (signed commits required)Commits MUST be signed. \`git commit\` and \`git push\` are blocked in this environment.@@ -294,7 +188,7 @@ Optimize for the fewest shell round trips.When you create a non-code file the user should be able to download (such as a report, chart, image, archive, or data file), call the \`upload_artifact\` tool with its path before your final reply. In your final reply, link to the download URL returned by the tool—never link to the file's local workspace path. Files left in the workspace don't reach the user. Don't upload source code or repository changes—those belong in a commit or PR.`;// Closes out every branch below, so a new section is added once rather than five times.- const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.buildSlackDeliveryInstructions()}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.options.storeSkillsInstalledCount)}+ const commonInstructions = `${signedCommitInstructions}${stackInstructions}${prLinkInstructions}${shellEfficiencyInstructions}${artifactInstructions}${this.options.deliveryInstructions ?? ""}${this.buildGithubAccessInstructions(hasGithubToken)}${buildStoreSkillsInstructions(this.options.storeSkillsInstalledCount)}${buildTaskSummaryInstructions()}`;// The shared block above is shaped for a run that ends with work landed. A@@ -307,19 +201,6 @@ The answer is the work of this run, so the run still needs a summary. Call the \const whyContextInstruction = ` - Add a brief **Why** to the body — one or two sentences capturing the reason the user asked for this change (the motivation, not a restatement of the diff). Keep it short.`;const publicRepoSafetyInstruction = ` - **Public-repo safety.** Treat the target repository as public-readable unless you have verified otherwise. The PR title, description, and commit messages must not contain private operational scale (exact event counts, internal row volumes, customer-usage percentages), customer names / emails / companies, references to internal tickets or incidents, the contents of Slack threads (do not quote or paraphrase what was said), or unreleased roadmap details. Linking to the originating Slack thread is fine and encouraged — Slack links are auth-gated and useful as context — as are channel references like "raised in #team-foo". Describe findings qualitatively ("present on nearly all X events, absent from Y") rather than with quantitative figures pulled from analytics queries — the reasoning that uses those numbers can stay in the thread; the PR copy cannot.`;const prMentionSafetyInstruction = ` - **Never guess a GitHub identity.** Do NOT \`@\`-mention, tag, assign, request review from, or attribute the PR to a person (in the title, description, commit message, or reviewers) using a name or handle taken from Slack or this thread. A Slack display name or handle is NOT a GitHub username. Finding a similar-looking handle in the repo's git history, CODEOWNERS, or existing PRs/issues does NOT confirm it belongs to this person: repository presence proves the handle exists, not that it is the person you mean, so treating it as a match still \`@\`-tags an unrelated account (e.g. Slack "Ross" is not necessarily GitHub \`@ross\`, even if some \`@ross\` has committed to the repo). Only \`@\`-mention a GitHub \`@handle\` the user gave you explicitly in this thread, or one you read from \`gh api user --jq .login\`, which authenticates as the person you are working for. Otherwise refer to people by plain-text name, or omit the mention entirely.`;- // Slack- and inbox-originated PRs are attributed to PostHog, not the- // PostHog Desktop app — they come from the Slack app / Self-driving- // inbox, which users know as "PostHog".- const createdWith = this.options.mobileClient- ? "Created with [PostHog Mobile](https://posthog.com?ref=pr)"- : this.options.isAutomatedOrigin- ? "Created with [PostHog](https://posthog.com?ref=pr)"- : "Created with [PostHog Desktop](https://posthog.com/desktop?ref=pr)";- const prFooter = slackThreadUrl- ? `*${createdWith} from a [Slack thread](${slackThreadUrl})*`- : inboxReportUrl- ? `*${createdWith} from an [inbox report](${inboxReportUrl})*`- : `*${createdWith}*`;const repositoryWorkspaceInstructions =this.options.taskRepositories.length > 1? `The task workspace contains these repositories:diff --git a/packages/agent/packages/harness/src/extensions/task-system-prompt/index.ts b/packages/agent/packages/harness/src/extensions/task-system-prompt/index.tsindex 762d59bdd473..e4cb42969c13 100644--- a/packages/agent/packages/harness/src/extensions/task-system-prompt/index.ts+++ b/packages/agent/packages/harness/src/extensions/task-system-prompt/index.ts@@ -1,7 +1,6 @@export {CloudTaskPrompt,type CloudTaskPromptOptions,- type SlackArtifactDelivery,} from "./cloud";export {createPiTaskSystemPromptExtension,