: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
chore(phai): document how products integrate with posthog ai (#89083)
Georgiy Tarasov45e49823bd0a
diff --git a/.agents/skills/implementing-agent-modes/SKILL.md b/.agents/skills/implementing-agent-modes/SKILL.mddeleted file mode 100644index d185f6feeff5..000000000000--- a/.agents/skills/implementing-agent-modes/SKILL.md+++ /dev/null@@ -1,81 +0,0 @@-----name: implementing-agent-modes-description: Guidelines to create/update a new mode for PostHog AI agent. Modes are a way to limit what tools, prompts, and prompt injections are applied and under what conditions. Achieve better results using your plan mode.------# Agent modes--Use the steps below to plan or implement a new mode. A mode is a way to manage the context of the agent and inject tools, prompts, and mode-related behavior relevant to a product, use case, JTBD, etc. The agent has the `switch_mode` tool that allows it to switch itself to another mode, which might change tools, prompt, and executables, preserving the current context. Some previously created tools are contextual, meaning they're injected on particular pages of the frontend. The modes change the approach and always have tools in the mode context.--## Determine mode name--Explore the `ee/hogai/core/agent_modes/presets` directory and check if there are already modes that match the user's intent. If you want to create a new mode, you should scope it by a PostHog product (Product analytics), product area (SQL), or agent (Instrumentation agent).--## (optionally) Create a new mode in schema--Add a new AgentMode to `frontend/src/queries/schema/schema-assistant-messages.ts` and regenerate the schema using:--```bash-hogli build:schema-```--Alternatively, you may use this command:--```bash-pnpm run schema:build-```--## Create or update mode's scaffolding--A mode should typically contain at least two things:--- An AgentToolkit exposing tools that are specific to the mode and trajectory examples for the todo tool.-- An AgentModeDefinition containing the AgentMode, mode description that is always injected into the context window of the agent, and classes for toolkit and executables.--Note: you should only create new executables if the user needs to modify the prompt, behavior of that mode, or the execution loop itself.--## Adding tools to the mode--Relevant tools might be located in `ee/hogai/tools` or `products/<product_name>/backend/max_tools`. There is a set of tools that is always injected into the context, like the `read_data` tool, but all other tools should be specific to the mode.--Before adding a tool to the toolkit, determine if those tools have tool dependencies. If there are dependencies (like an experiment depends on feature flag creation), loop back to the user to determine whether they want to merge modes into a single one. If they don't want to do that, make sure that you later add a trajectory example clearly explaining mode switching and tool selection.--You should also verify that the tools are backend-first. If tools apply frontend changes without passing proper context back to the conversation, you should propose a way to make them backend-first so the agent has the right context.--## Review the default toolkit--If the new mode contains new Django models, you should review whether the `read_data`, `search`, and `list_data` tools have the functionality to retrieve the models. If they don't support these models, you should use or implement one of the context providers available in `ee/hogai/context/...`.--## Write JTBD-like trajectory examples--Update the AgentToolkit to include trajectory examples. These should be JTBD-style examples showing how the agent should achieve typical tasks with the available tools. Check the Product analytics preset for reference.--## Implement frontend--Update `max-constants.tsx` to include new tools and add the mode to the mode selector. You might also need to create new UI elements for displaying data from the tools.--### Example--Say you've updated the Error tracking tool to list issues. It used to be a frontend tool that only updated filters, but now it outputs error tracking issues. While the agent has the context it needs, the user also needs to see the issues in a human-readable way. In this case, you should design and implement a new component to display the tool's output.--## Add feature flag--All new modes must be feature-flagged. Example:--```ee/hogai/chat_agent/mode_manager.py- @property- def mode_registry(self) -> dict[AgentMode, AgentModeDefinition]:- registry = dict(DEFAULT_CHAT_AGENT_MODE_REGISTRY)- if has_error_tracking_mode_feature_flag(self._team, self._user):- registry[AgentMode.ERROR_TRACKING] = error_tracking_agent- return registry-```--If you have created new tools, make sure you feature flag them correctly:--1. Old tools that are being migrated should not be available if the feature flag is active.-2. New tools should only be available if the feature flag is active.--## Implement and update tests--You should test new tools, presets, executables, and optionally implement evals.diff --git a/.agents/skills/integrating-with-posthog-ai/SKILL.md b/.agents/skills/integrating-with-posthog-ai/SKILL.mdnew file mode 100644index 000000000000..3e2c33a1ab90--- /dev/null+++ b/.agents/skills/integrating-with-posthog-ai/SKILL.md@@ -0,0 +1,68 @@+---+name: integrating-with-posthog-ai+description: 'Wire a PostHog product surface into the PostHog AI agent from the frontend. Use when attaching scene or entity context, injecting instructions to steer the agent, reacting to the agent calling a tool, applying an agent edit back into an open form, or rendering a product tool card in a thread.'+---++# Integrating a product with PostHog AI++The user-facing doc is [`products/posthog_ai/README.md`](../../../products/posthog_ai/README.md). This skill is how to _do_ the work: pick the right seam, avoid the two mistakes that matter, and stop before the deep end.++## First: is this a frontend job at all?++There is **no backend integration API**. An integration has two halves, and the frontend half depends on the backend half:++1. **Capability** — the agent reads and writes your entities through **MCP tools**. If no tool can resolve the thing you want to talk about, start there: `/implementing-mcp-tools`, `products/<name>/mcp/tools.yaml`.+2. **Cooperation** — the frontend seams below.++Injected context carries _references_, not data. A reference the agent cannot resolve with a tool is a dead end, so confirm the tool exists before you inject the ref.++## Pick the seam++| The job | Seam | Import from | Use it? | Reference |+| ------------------------------------------------------------------------------------------------------------ | -------------------- | ---------------------------------- | ------------------------------- | ----------------------------------------------------------------- |+| The agent should know what the user is looking at, including unsaved work | Attached context | `api/logics` | **Recommended** | [injecting-context.md](references/injecting-context.md) |+| Steer how the agent behaves here — which tools to prefer, what "this" means on this page, or hand it a skill | Trusted instructions | `api/logics` | **Recommended** | [injecting-instructions.md](references/injecting-instructions.md) |+| The page should update when the agent does something | Tool-event bus | `api/logics` | **Recommended** | [reacting-to-tool-calls.md](references/reacting-to-tool-calls.md) |+| Your tool's calls should render as a real card, not the generic fallback | Tool registry | `api/tools` | **Recommended** | [rendering-widgets.md](references/rendering-widgets.md) |+| Build your own agent UI out of the thread, composer, and stream primitives | Run primitives | `api/runSurface`, `api/primitives` | **Not recommended** — see below | `products/posthog_ai/frontend/README.md` |++The first four are the product integration. The fifth exists for the three surfaces that _host_ an agent run — the Max scene, the signals inbox, and the tasks runner — not for products that want to cooperate with one. Reaching for it by default is the main way this goes wrong.++Whole scene at once: `useSceneAgentPanel({ sceneKey, contextItems, headlines })` from `frontend/src/scenes/max/useSceneAgentPanel.ts` bundles context, welcome headlines, and gated auto-open of the side panel. Start there for a scene; drop to the individual hooks for one component. `products/workflows/frontend/Workflows/WorkflowScene.tsx` is the exemplar.++## The import rule++Always a domain-scoped `api/<module>` entry, never a deep path, and there is deliberately no root barrel:++```ts+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'+```++Pick the narrowest module. `api/logics` and `api/types` are headless; `api/primitives` drags in markdown and virtualization; `api/tools` registers built-ins at module load, so importing it is a side effect that is not tree-shaken. A status badge that imports the wrong tier doubles its chunk.++## The two mistakes that matter++**1. Putting variable data in trusted context.** `type: 'instructions'` items land in `<posthog_trusted_context>` — guidance the agent follows. Everything else lands in `<posthog_untrusted_context>`, behind hardening prose. So:++- Instructions carry **only your own build-time strings**. Never a user-entered name, an ingested value, or anything interpolated from one. A crafted entity name in trusted context is a prompt injection against whoever reads the thread next.+- Untrusted context is where user data belongs, and injecting it freely is the point — the user's unsaved editor state is usually the most useful thing you have.+- If a pointer must vary (which id is open, which step is selected), put it on an untrusted item and have the static instruction refer to it by field name.++**2. Sending object shapes instead of identifiers.** The context block rides on _every_ message in the conversation. Send `{ type, key, label }` and let the agent fetch details through your MCP tools. The exception is unsaved state the agent cannot fetch — budget it (`workflowAgentContext.ts` caps at 64k chars and elides rather than truncates) and redact secrets, which sit in cleartext in live form state even though saved secrets never reach the frontend.++## Stop at seam 4++The run primitives are public — `RunSurface`, `ReadonlyRunSurface`, `EmbeddedRunner`, the `Thread` atoms, `runStreamLogic` — but building a custom agent UI on them is not a product integration. It means owning stream binding, composer and queue state, permission routing, and the eager-vs-lazy tier choice that decides your bundle size. There is no default layout.++If that is genuinely the task, read [`products/posthog_ai/frontend/README.md`](../../../products/posthog_ai/frontend/README.md) and [`AGENTS.md`](../../../products/posthog_ai/frontend/AGENTS.md) first, and copy one of the two reference implementations (the signals inbox detail views, or `scenes/TaskTracker/components/TaskRunChat.tsx`) rather than composing from scratch.++## Do not touch++- **The LangGraph runtime is frozen.** No new `useMaxTool` registrations, no new `MaxUIContext` fields, no new `maxContext` selectors on scene logics. Use attached context and the tool-event bus instead.+- **The coupling gate.** Nothing under `products/posthog_ai/frontend` may import `scenes/max`, `maxThreadLogic`, `maxContextLogic`, or the conversations API. Max is a consumer of that surface, not a dependency of it. If the surface is missing something you need, lift it to a generic prop or selector there — never special-case a consumer inside it.++## Verify++- `pnpm --filter=@posthog/frontend typescript:check` for the types.+- Run the app and open the side panel on your page. Context is invisible by design, so check it landed: an attached item that is not `hidden` shows as a chip in the composer's context bar, and the agent should be able to answer a question about the thing you attached without being told its id.+- For a reactivity seam, ask the agent to make the change and confirm the open page updates. Then reload the page — your handler must **not** fire again, because replay events are suppressed by default.diff --git a/.agents/skills/integrating-with-posthog-ai/references/injecting-context.md b/.agents/skills/integrating-with-posthog-ai/references/injecting-context.mdnew file mode 100644index 000000000000..f4597768c7a3--- /dev/null+++ b/.agents/skills/integrating-with-posthog-ai/references/injecting-context.md@@ -0,0 +1,81 @@+# Injecting context++Tell the agent what the user is looking at. While a provider is registered, every message sent from the surface is silently prefixed with a context block; the user sees only their own text, and history replay strips the block back off.++## The item shape++`AttachedContextItem` (`products/posthog_ai/frontend/types/contextTypes.ts`, exported from `api/types`):++| Field | Meaning |+| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `type` | **An arbitrary string**, never an enum. `'insight'`, `'dashboard'`, `'trace'`, `'text'`, `'hog_flow_editor_state'` — invent what fits. The one reserved value is `'instructions'`, which routes to trusted context. |+| `key` | The entity identifier the agent will resolve — id, `short_id`, trace id. |+| `label` | Human-readable chip label. |+| `value` | Free-text payload, for items that have no keyed entity. |+| `hidden` | Rendered into the block but never shown as a composer chip. |+| `dismissGroup` | Items sharing a group are dismissed together. |++Items are flattened across providers and deduped by `${type}:${key ?? value}` (`attachedContextItemKey`).++## Three ways to register++**A component** — the normal path:++```tsx+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'++useAttachedContext(dashboard ? [{ type: 'dashboard', key: dashboard.id, label: dashboard.name ?? undefined }] : null)+```++Pass `null` while the entity is loading, or `{ active: false }`. Real caller: `frontend/src/scenes/dashboard/Dashboard.tsx`.++**JSX only** — `<AttachedContextProvider items={items} />` from `api/primitives`, a render-null wrapper over the same hook.++**A kea logic** — register through a disposable (see `/using-kea-disposables`); the returned cleanup deregisters on unmount, so no `beforeUnmount` is needed:++```ts+afterMount(({ actions, cache, values }) => {+ cache.disposables.add(+ () => {+ actions.registerContext('my-scene', [{ type: 'dashboard', key: values.dashboard.id }])+ return () => actions.deregisterContext('my-scene')+ },+ 'attachedContext',+ { pauseOnPageHidden: false }+ )+})+```++`pauseOnPageHidden: false` is **required**, not stylistic. The registration costs nothing while idle, and the default hide-pause would silently drop context from a queued follow-up that flushes while the tab is hidden. `contextPickerLogic` is the exemplar.++Re-dispatching `registerContext` with the same provider id is an upsert — do it from a `subscriptions` handler when the resource changes.++**A whole scene** — `useSceneAgentPanel` wraps the hook plus welcome headlines plus gated auto-open of the side panel. Prefer it for a scene.++## Identifiers, not object shapes++The context block rides on **every message** in the conversation, so a serialized entity is a per-turn cost that never goes away. Send the reference and let the agent fetch details with your MCP tools — which is also why the tool has to exist first.++The exception is **unsaved progress the agent cannot fetch**: live editor or form state. When you send that, budget it. `products/workflows/frontend/Workflows/workflowAgentContext.ts` is the reference implementation:++- `EDITOR_STATE_MAX_CHARS = 64_000`. Over budget, it **elides** the heavy nested parts and replaces them with a marker telling the agent which tool to call for the full value. Elision keeps the JSON parseable; blind truncation does not.+- Derived weight is dropped before measuring — rendered html is not sent when the design it was rendered from is already there.+- A trusted instruction tells the agent to prefer the live state over a fetched definition when reading, and to fetch when it needs the persisted one.++## Redact secrets++Saved secrets never reach the frontend, but a secret typed into a form and not yet saved sits in cleartext in your live form state — and a step may carry only a `template_id`, so which fields are secret is only knowable from a loaded schema.++`redactWorkflowSecretInputs` in the same file shows the shape: redact by schema, and **fail closed** when the schema is unavailable (still loading, fetch failed, template deleted) by redacting every value. It also clears compiled bytecode of a redacted entry, because the bytecode can embed the literal.++## Untrusted by design++Non-`instructions` items land in `<posthog_untrusted_context>`, behind hardening prose that tells the agent this is data, not direction. That is what makes it safe to inject whatever the user typed — and you should, since their unsaved work is usually the most useful thing you have. Do not sanitize user text into blandness; put it in the untrusted block and leave it intact.++## Dedupe and dismissal++Deduping is automatic and **task-scoped**, covering the whole resume chain of runs, in two layers: keys marked right after each send, and the durable layer derived from context blocks found in replayed history (so it survives reloads, other tabs, and other users' sessions). `text` items are never deduped — repeated text is intentional.++Chips render **all** of `contextItems`, whatever provider contributed them. Closing a chip your provider owns dispatches `dismissContext(key)`, and dismissal **survives re-registration** — a scene bridge that upserts on every read must not resurrect a chip the user closed. This is what `dismissGroup` is for: pair a visible chip with the hidden payload items it stands for, so closing the chip actually detaches the payload instead of only hiding the chip.++Users can also attach context themselves through the composer's `@` affordance (`AttachedContextBar` from `api/primitives`, backed by `contextPickerLogic` as the `user-picker` provider). Selections become flat refs via `taxonomicItemToAttachedContext` — again no entity loading.diff --git a/.agents/skills/integrating-with-posthog-ai/references/injecting-instructions.md b/.agents/skills/integrating-with-posthog-ai/references/injecting-instructions.mdnew file mode 100644index 000000000000..e7f7f204a1d7--- /dev/null+++ b/.agents/skills/integrating-with-posthog-ai/references/injecting-instructions.md@@ -0,0 +1,73 @@+# Injecting custom instructions++`type: 'instructions'` is the one reserved item type. Its `value` lands in `<posthog_trusted_context>` — guidance the agent is told to follow — instead of the untrusted block everything else goes to.++Use it to say what the user has open, which tools to prefer, and what "this thing" means on this page.++```ts+const ISSUES_QUERY_TOOL_CONTEXT_ITEM: AttachedContextItem = {+ type: 'instructions',+ hidden: true,+ value:+ 'The user has the error tracking issue list open. When you call query-error-tracking-issues-list, the filters ' ++ 'from your query (filter group, status, date range, search, ordering, assignee) are also applied to the open ' ++ 'page, so the user sees matching issues both in this chat and on screen.',+}+```++Set `hidden: true` unless the instruction is something the user should see as a chip. Register it exactly like any other context item — the type is the only difference.++## Trusted means static++**Instructions must carry only your own build-time strings.** Never a user-entered name, an ingested value, or a string interpolated from one. Trusted context is direction the agent follows, so a crafted entity name there is a prompt injection against whoever reads the thread next — including other users on a shared task.++Programmatic and user data go on ordinary untrusted items. That split is the whole point of having two blocks.++If an instruction needs to point at something that varies — which id is open, which step is selected — do not interpolate it. Put the pointer on an untrusted item and have the static instruction refer to it **by field name**:++```ts+// Static. Names the field, carries no id.+value: `The user has the email editor open. The hog_flow_editor_state item's editing_email_action_id field names ` ++ `the open action; the latest editor state wins over anything earlier in the conversation.`+```++There is a second reason this matters. Instructions dedupe per task by **exact text**, so a varying id inside an instruction would be pruned on a reopen: open A, open B, reopen A, and B's stale pin is the newest surviving text. The editor-state item's value changes whenever the state does, so it always re-sends. `products/workflows/frontend/Workflows/workflowAgentContext.ts` documents both reasons at the call site.++If you truly must interpolate an identifier, allowlist its shape first — that file gates on `SAFE_ACTION_ID = /^[A-Za-z0-9_-]{1,128}$/` before any action id reaches trusted text, because action ids are arbitrary strings a workflow author controls.++## Injecting a skill and a tool catalog++**The two things worth putting in trusted context are your product's MCP tool names and its skills** — both of which already exist in the repo as build-time sources, which is exactly what makes them safe here.++- **Skills** come from the skill build pipeline in `products/*/skills/`. Your product's skills are already written, linted, and shipped to external agents; embedding one gives the web agent the same job-to-be-done guidance a Claude Code user gets. See `/writing-skills`.+- **MCP tool names and descriptions** come from your `products/<name>/mcp/tools.yaml` and the generated schemas. Naming the tools up front stops the agent burning turns on discovery. See `/implementing-mcp-tools`.++The richest use of trusted context is handing the agent both up front, so it does not spend turns discovering tools or reading skill files. `workflowAgentContext.ts` attaches four things:++1. A **preamble** telling the agent the skill and tool catalog are already embedded, so it should call tools directly rather than go looking.+2. The **skill content** itself, embedded as a string.+3. One instruction item **per MCP tool**, each carrying the tool's name and description.+4. A visible `type: 'skill'` chip so the user can see (and detach) what was attached.++### Generate the payload, never hand-copy it++All of it comes from `products/<product>/frontend/generated/agentContext.ts`, built by+`services/mcp/scripts/build-scene-tool-context.ts` and regenerated with `hogli build:openapi`. That script+reads two sources at build time:++- `products/<product>/mcp/*.yaml` — which tools are enabled, with their live descriptions.+- `products/<product>/skills/<skill>/` — the skill markdown, named file by file (`SKILL.md` plus whichever+ `references/*.md` are worth embedding).++To get one for your product, add an entry to that script's config: the output path, the tool YAML files with+a const name each, and the skill directories with the files to embed. The workflows entry is the model.++This is what makes the payload safe as trusted text: it is our own source, checked into the repo, not runtime+data. It is also what keeps it honest — hand-copied skill text or a pasted tool description silently drifts+from the skill or tool it claims to describe, and nothing catches it.++Tie the whole bundle together with a shared `dismissGroup` so the visible chip and the hidden payload detach as one.++## Conditional instruction sets++Instructions can change with what the user is doing on the page. The same file attaches an extra bundle only while the email takeover is open, and gates it on the URL parameters actually resolving to a real email action — a lingering `?editor=email` param must not flip the agent into the wrong framing. Compute the condition properly and pass it down, rather than trusting a query string.diff --git a/.agents/skills/integrating-with-posthog-ai/references/reacting-to-tool-calls.md b/.agents/skills/integrating-with-posthog-ai/references/reacting-to-tool-calls.mdnew file mode 100644index 000000000000..e2e663d4882c--- /dev/null+++ b/.agents/skills/integrating-with-posthog-ai/references/reacting-to-tool-calls.md@@ -0,0 +1,106 @@+# Reacting to tool calls++`toolStreamEventsLogic` (`api/logics`) is a global bus. `runStreamLogic` is its only publisher, emitting a tool-call lifecycle event with a **resolved** tool name — the inner PostHog tool, not the exec wrapper — plus turn-complete and run-terminal events.++This is what makes the side panel feel connected to the page: the user asks PostHog AI to change something, and their open page updates instead of going stale.++## The event++```ts+type ToolStreamPhase = 'started' | 'updated' | 'completed' | 'failed'++interface ToolStreamEvent {+ streamKey: string // conversation id, or run/task id+ toolCallId: string+ toolName: string // resolved inner tool+ rawToolName: string+ phase: ToolStreamPhase+ invocation: ToolInvocation+ source: 'live' | 'replay' | 'client'+}+```++## `useToolStreamListener` — plain reaction++Reload a list, refetch a record, flash a notice:++```ts+useToolStreamListener({+ tools: ['cdp-functions-partial-update'],+ onEvent: (event) => {+ if (event.phase !== 'completed' || !hogFunction?.id) {+ return+ }+ const innerInput = resolveToolCall(event.invocation).innerInput+ const targetId = typeof innerInput?.id === 'string' ? innerInput.id : null+ if (targetId && targetId !== hogFunction.id) {+ return+ }+ loadHogFunction()+ },+})+```++Note the targeting: the bus is global, so an event for _some other_ record still reaches you. Parse the inner args with `resolveToolCall` and check the call was actually about the thing you are showing. Real caller: `frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx`.++Pass `tools: '*'` to see everything, but then filter hard.++## `useMcpToolApplyBack` — apply an edit into an open editor++When the user is editing something and the agent changes it, this applies the result back into the open form:++```tsx+useMcpToolApplyBack({+ tools: ['insight-create', 'insight-update'],+ targetKey: `dashboard:${dashboard?.id ?? 'unloaded'}`,+ active: !!dashboard && canEditDashboard,+ onApply: (_event, { innerInput }) => {+ if (dashboard && insightIsAddedToDashboard(innerInput, dashboard.id)) {+ loadDashboard({ action: DashboardLoadAction.Update })+ }+ },+})+```++It is a hardened wrapper over the bus, not a convenience alias:++- **Foreground-gated.** Only the run rendered in the panel the user is watching can trigger it. A background task cannot rewrite the page under them.+- **Replay-excluded**, always.+- **Snapshotted at send time.** The active registration is captured when the prompt is sent, so navigating to a different editor mid-run cannot hand the response to the new one.+- **Fails closed on ambiguity.** If more than one claimed target matches the same tool, nothing is applied.++`targetKey` is what makes those guarantees work: it must be a **stable identity for the resource being edited**, and it must change when the resource changes. Include the id, and include a sentinel for the unloaded state (the example uses `'unloaded'`) so a not-yet-loaded editor never shares a key with a loaded one.++`applyOn` picks the timing:++- `'tool_call_completed'` (default) — fire per matching completion.+- `'turn_end'` — buffer, and apply only the last matching completion, once, when the turn finishes. Use this when the agent may call the tool several times converging on an answer and you only want the final state.++Other real callers: `frontend/src/scenes/dashboard/DashboardHeader.tsx`, `frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx`, `frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx`, `frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx`.++Pair an apply-back with a trusted instruction telling the agent that its tool calls are reflected on the open page — otherwise it does not know the user can see the result, and may narrate the change instead of making it.++## Two caveats that bite++**Replay is suppressed by default.** A reload replays the run's history through the same code path. Without suppression every handler would re-fire on every reload — creating things twice, re-applying stale edits. Set `includeReplay: true` only if you have thought about that.++**`toolName` is unreliable at `phase: 'started'`.** For exec-wrapped PostHog tools the command streams in through later updates, so the resolved name can still be `__posthog_exec_unknown__` when the call starts. It is reliable by `'completed'`. Match on `'completed'` whenever correctness depends on knowing which tool ran.++## From a kea logic++Either listen to the bus action and filter yourself:++```ts+listeners({+ [toolStreamEventsLogic.actionTypes.emitToolEvent]: ({ event }) => {+ if (event.source === 'replay' || event.phase !== 'completed') {+ return+ }+ // …+ },+})+```++Or register a subscription through a disposable, calling `registerToolListener(listenerId, { tools, onEvent })` in setup and `deregisterToolListener(listenerId)` in cleanup — with `pauseOnPageHidden: false`, because tool events fire while the tab is hidden and a missed live event is never redelivered.++Subscriber callbacks are isolated: a throwing listener is captured and reported, never breaking stream ingestion. That is a safety net, not a license — a throwing handler still means your reaction did not happen.diff --git a/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.md b/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.mdnew file mode 100644index 000000000000..9db123e4bbad--- /dev/null+++ b/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.md@@ -0,0 +1,57 @@+# Rendering tool cards in a thread++Register a renderer and your product's tool calls display as a real card instead of the generic MCP fallback. The seam is `registerToolRenderers` from `api/tools` — a module-level side effect, no hooks and no dynamic registration.++```tsx+import { registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'++registerToolRenderers([+ {+ key: 'cdp-functions-partial-update',+ displayName: 'Update function',+ icon: <IconBolt />,+ renderPermissionPreview: renderPartialUpdatePreview,+ requiresPostHogOrigin: true,+ },+])+```++Real caller: `frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx`.++## The entry++| Field | Meaning |+| ------------------------- | ----------------------------------------------------------------------- |+| `key` | The inner exec tool name, or the wire tool name for a built-in. |+| `displayName` | Card title text. |+| `icon` | Card icon. |+| `Renderer` | Draws the **result** card. Optional — omit it for a preview-only entry. |+| `renderPermissionPreview` | Draws the approval prompt shown **before** a write runs. |+| `requiresPostHogOrigin` | Only match calls that came through the trusted PostHog server. |++Set `requiresPostHogOrigin: true` for anything that renders PostHog entities. Without it, a tool of the same name from another MCP server would render through your card.++Registration is by import, so call it once from your scene's entrypoint (or a small `register*.tsx` module the entrypoint imports for its side effect). Re-registering the same `key` overwrites. Wrap a heavy `Renderer` in `lazyWithRetry` so it does not weigh down the chunk that registers it.++The built-in PostHog widgets — insights, dashboards, recordings, error tracking issues, notebooks, query results — live in `products/posthog_ai/frontend/components/tool/widgets/` and self-register the same way. Read `registerDataToolRenderers.tsx` there as the reference implementation; it is the same public seam, not a privileged path.++## A card is two header lines plus an accordion++Every renderer wraps its content in `ToolActivity`, which exposes exactly two always-visible lines:++- `title` — what happened.+- `subtitle` — the **one** most salient input: a command, a path, a name.++**Everything else your tool produces goes in the collapsible `body`** — parsed output, lists, file contents, diffs, raw text. The body auto-expands while the tool runs and collapses when it completes, so a thread with twenty tool calls stays scannable and a reader expands only the cards they care about.++Reserve `children` (always visible) for genuinely interactive payloads that would be useless collapsed — something the user must act on. Output is never that. When in doubt, it goes in the accordion.++## Permission previews++`renderPermissionPreview` runs at the approval prompt, before the tool executes, and receives the pending request record. It is worth writing for any destructive or hard-to-reverse write: show _what will change_, not just the tool name, so the user approves a real thing rather than a label. An entry can carry a preview and no `Renderer` at all.++## Not to be confused with MCP UI apps++The `@posthog/mcp-ui` components under `products/*/mcp/apps/`, declared as `ui_apps` in a product's `mcp/tools.yaml`, are a **different mechanism**. They render tool results in _external_ MCP clients such as Claude Desktop, served through `services/mcp/`, and nothing under the PostHog AI frontend imports them. They do not appear in PostHog AI threads.++If the ask is "make our tool results look good in Claude Desktop", that is `/implementing-mcp-ui-apps`. If it is "make our tool results look good in PostHog AI", it is this file.diff --git a/AGENTS.md b/AGENTS.mdindex 022258b8df15..c3cf6870a30b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -280,6 +280,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a- `/implementing-mcp-tools` — adding/modifying endpoints or `tools.yaml`- `/modifying-taxonomic-filter` — any TaxonomicFilter change- `/placing-product-frontend-code` — adding a frontend file or directory for a product, or deciding between `products/<name>/frontend/` and `frontend/src/scenes/<name>/`+- `/integrating-with-posthog-ai` — making a product surface work with PostHog AI: injecting scene context or custom instructions, reacting to the agent's tool calls, or rendering your product's tool cards in a thread- `/sending-notifications` — adding notification support- `/writing-skills` — creating or updating skills in `.agents/skills/`- `/writing-evals` — adding or changing eval suites, cases, scorers, or seeders under `products/posthog_ai/evals/` or `products/*/evals/`, touching the harness in `products/posthog_ai/eval_harness/`, or running those evalsdiff --git a/products/posthog_ai/README.md b/products/posthog_ai/README.mdindex 22b5935fec66..3c1142db1d15 100644--- a/products/posthog_ai/README.md+++ b/products/posthog_ai/README.md@@ -1,20 +1,192 @@# PostHog AI-## Skills+PostHog AI is the agent that works alongside the user inside PostHog. This README is for **engineers on other product teams**: read it to make your product work with the agent.-Agent skills live in `products/*/skills/` as Markdown or Jinja2 templates. The build system renders them into `dist/skills/` (human-readable) and packages them into `dist/skills.zip`. Both are gitignored — CI builds the ZIP from source and publishes it as a GitHub release.+> Building the agent surface itself? That's [`frontend/AGENTS.md`](./frontend/AGENTS.md). Consuming the run UI in detail? [`frontend/README.md`](./frontend/README.md). This file is the integration entry point.-### Commands+## Where PostHog AI renders-```bash-hogli build:skills # Build skills to dist/skills/ and dist/skills.zip-hogli build:skills --list # List discovered skills-hogli lint:skills # Validate skill sources without rendering-hogli init:skill --product <product> --name <name> # Scaffold a new skill-hogli init:skill --product <product> --name <name> --j2 # Scaffold as Jinja2 template+Your integration can show up in any of these:++| Surface | Where |+| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |+| **The side panel** | Anywhere in the app, beside the page the user is on. This is what makes reactivity useful — the agent works while the user watches their own form. |+| `/ai` | The full-page scene (`frontend/src/scenes/max/`). `/max` redirects here; `/ai/history` is the thread list. |+| `/home` | The AI-first homepage variant embeds an instance (`frontend/src/scenes/project-homepage/ai-first/AiFirstHomepage.tsx`). |+| `/tasks` | The standalone runner scene (`frontend/scenes/TaskTracker/`). |+| Signals inbox | Read-only embeds of a finished run. |++There are two runtimes, picked per conversation by `conversation.agent_runtime`. **`sandbox` is where all new work goes.** `langgraph` is the legacy runtime and is frozen — do not extend it.++## There is no backend integration API++Nothing you build here talks to a PostHog AI backend. An integration has two halves:++1. **Give the agent the capability** — ship **MCP tools** for your product. That is how the agent reads and writes your entities. See [`/implementing-mcp-tools`](../../.agents/skills/implementing-mcp-tools/SKILL.md) and `products/<name>/mcp/tools.yaml`.+2. **Make your UI cooperate** — the frontend seams below.++Seam 1 depends on step 1: injected context is a set of _references_, and a reference the agent has no tool to resolve is a dead end.++## The import rule++Import from a domain-scoped `api/<module>` entry. Never reach into `components/...` or `logics/...`, and note there is deliberately no root barrel:++```ts+import { useAttachedContext, useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'+import { registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'+```++Pick the narrowest module that does the job — the split preserves code-splitting, and a fat import drags the markdown/virtualization thread or the side-effectful tool registry into your chunk. The full tier table lives in [`frontend/README.md`](./frontend/README.md#2-which-surface-do-i-use).++## Seam 1 — inject context++Register what the user is looking at. While registered, every message sent from the surface is silently prefixed with a context block describing it; the user only ever sees their own text.++```tsx+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'++useAttachedContext(dashboard ? [{ type: 'dashboard', key: dashboard.id, label: dashboard.name ?? undefined }] : null)+```++Items are abstract: `type` is any string you like (`'insight'`, `'trace'`, `'text'`, `'hog_flow_editor_state'` — never an enum), plus optional `key`, `label`, `value`, `hidden`, and `dismissGroup`. JSX-only call sites can render `<AttachedContextProvider items={...} />` from `api/primitives`. From a kea logic, `connect` to `attachedContextLogic` and register through a disposable with `pauseOnPageHidden: false` — a hide-paused registration would drop context from a send that happens while the tab is hidden.++Three rules:++- **Inject identifiers, not object shapes.** The agent fetches details itself through your MCP tools. A full serialized entity costs tokens on every single message in the conversation, and large payloads risk being rejected or truncated on the way up. The one exception is **unsaved progress the agent cannot fetch** — live form state. Budget it: `products/workflows/frontend/Workflows/workflowAgentContext.ts` caps its editor state at `EDITOR_STATE_MAX_CHARS = 64_000` and _elides_ oversized parts rather than truncating, so the JSON stays parseable.+- **This context is untrusted.** It lands in `<posthog_untrusted_context>`, behind hardening prose. That is what makes it safe to inject whatever the user typed — which you should, since their unsaved work is the most useful thing you have.+- **Strip secrets before you serialize.** Saved secrets never reach the frontend, but a secret typed into a form and not yet saved sits in cleartext in your form state. `redactWorkflowSecretInputs` in the same file fails closed while the schemas that identify secret fields are still loading.++Deduping is automatic and task-scoped: an item already sent anywhere in the task's resume chain is pruned. `text` items are the exception and always resend.++## Seam 2 — inject custom instructions++The reserved `type: 'instructions'` routes the value into `<posthog_trusted_context>` instead — guidance the agent is told to follow. Use it to tell the agent what the user has open and which tools to reach for:++```ts+const ISSUES_QUERY_TOOL_CONTEXT_ITEM: AttachedContextItem = {+ type: 'instructions',+ hidden: true,+ value:+ 'The user has the error tracking issue list open. When you call query-error-tracking-issues-list, the filters ' ++ 'from your query (filter group, status, date range, search, ordering, assignee) are also applied to the open ' ++ 'page, so the user sees matching issues both in this chat and on screen.',+}+```++**Trusted means static.** Instructions must only ever carry your own build-time strings — never user-entered or ingested data, and never a value interpolated from one. A crafted entity name in trusted context is a prompt injection against the next reader. If a pointer must vary (which id is open, which step is selected), put it on a normal untrusted item and have the instruction refer to it by field name.++`workflowAgentContext.ts` is the full example: it embeds the building-workflows skill markdown and the workflows MCP tool catalog (both build-time constants from a generated module), gates any interpolated id behind an allowlist regex, and pairs each visible chip with the hidden payload it stands for via `dismissGroup` so closing the chip actually detaches the payload.++## Seam 3 — react to what the agent does++`toolStreamEventsLogic` is a global bus that publishes tool-call lifecycle events with **resolved** tool names. Two consumer APIs, both from `api/logics`.++**Reload after the agent changes something** — `useToolStreamListener`:++```ts+useToolStreamListener({+ tools: ['cdp-functions-partial-update'],+ onEvent: (event) => {+ if (event.phase === 'completed') {+ loadHogFunction()+ }+ },+})+```++**Apply an agent edit back into an open form** — `useMcpToolApplyBack`. This is the one to reach for when the side panel is open next to your editor: the user asks PostHog AI to change a feature flag, and the open form updates instead of going stale.++```tsx+useMcpToolApplyBack({+ tools: ['insight-create', 'insight-update'],+ targetKey: `dashboard:${dashboard?.id ?? 'unloaded'}`,+ active: !!dashboard && canEditDashboard,+ onApply: (_event, { innerInput }) => {+ if (dashboard && insightIsAddedToDashboard(innerInput, dashboard.id)) {+ loadDashboard({ action: DashboardLoadAction.Update })+ }+ },+})+```++Apply-back is gated to the run the user is actually watching, excludes replay, and fails closed when two targets claim the same tool — so navigating between editors cannot hand an in-flight response to the wrong one. `applyOn` defaults to `'tool_call_completed'`; `'turn_end'` applies only the last matching completion, once, when the turn finishes.++Two caveats for both hooks:++- **Replay events are suppressed by default.** A page reload replays the run's history; without suppression your handler would re-fire on every reload. Opt in with `includeReplay` only if you want that.+- **`toolName` is unreliable at `phase: 'started'`** for exec-wrapped PostHog tools — the command streams in via updates, so it can still be `__posthog_exec_unknown__`. Match on `'completed'` when you need certainty.++From a kea logic, either listen to `toolStreamEventsLogic.actionTypes.emitToolEvent` and filter `event.source` yourself, or register via `registerToolListener` / `deregisterToolListener` in a disposable — again with `pauseOnPageHidden: false`, since missed live events are not redelivered.++## Seam 4 — render your own tool cards++Register a renderer so your product's tool calls display as a real card in the thread instead of the generic MCP fallback. Call it once at module load from your scene's entrypoint:++```tsx+import { registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'++registerToolRenderers([+ {+ key: 'cdp-functions-partial-update',+ displayName: 'Update function',+ icon: <IconBolt />,+ renderPermissionPreview: renderPartialUpdatePreview,+ requiresPostHogOrigin: true,+ },+])+```++`key` is the inner exec tool name. A `Renderer` draws the result card; `renderPermissionPreview` draws the approval prompt shown _before_ a write runs. Set `requiresPostHogOrigin: true` so the entry only matches calls that came through the trusted PostHog server. Wrap a heavy renderer in `lazyWithRetry`.++**A tool card is two header lines plus an accordion.** `ToolActivity` gives you a `title` and one `subtitle` — the single most salient input. Everything else your tool produces goes in the collapsible `body`, never in always-visible `children`, so a thread with twenty tool calls stays scannable. Reserve `children` for payloads the user must act on.++The built-in PostHog widgets (insights, dashboards, recordings, error tracking, notebooks, query results) live in `frontend/components/tool/widgets/` and self-register the same way — that's the reference implementation.++> **MCP UI apps are a different mechanism.** The `@posthog/mcp-ui` components under `products/*/mcp/apps/` render tool results in _external_ clients like Claude Desktop, served through `services/mcp/`. They do not render inside PostHog AI threads. See [`/implementing-mcp-ui-apps`](../../.agents/skills/implementing-mcp-ui-apps/SKILL.md).++## Seam 5 (advanced) — build a custom UI on the run primitives++The same facade exposes the machinery for rendering and driving an agent run yourself: `ReadonlyRunSurface` (lazy read-only embed), the `RunSurface` compound (`Root` plus `.Thread` / `.Composer` / `.Resources` / `.ContextUsage` slots), `EmbeddedRunner` (the whole `/tasks` product inline), and the Tier 2 primitives — `Thread` atoms, `Composer.*`, permission and question surfaces — over `runStreamLogic` and `runInteractionLogic`.++**Avoid this unless you know exactly what you're doing.** Seams 1–4 are what a product integration needs. This one means owning stream binding, composer and queue state, permission routing, and the eager-vs-lazy choice that decides whether your surface doubles someone's bundle. There is no default layout, so you compose one.++If you genuinely need it, read [`frontend/README.md`](./frontend/README.md#3-recipes) for the recipes (read-only embed, live embed with composer, optimistically opening a run before it exists) and [`frontend/AGENTS.md`](./frontend/AGENTS.md) for the conventions first. The reference implementations are the signals inbox detail views and `frontend/scenes/TaskTracker/components/TaskRunChat.tsx`.++## Shortcut for a whole scene++`useSceneAgentPanel` does context, welcome headlines, and gated auto-open of the side panel in one call:++```ts+useSceneAgentPanel({+ sceneKey: 'workflow',+ contextItems: agentContextItems,+ headlines: editingEmail ? EMAIL_EDITOR_AGENT_HEADLINES : WORKFLOW_AGENT_HEADLINES,+ active: !!originalWorkflow || workflowSceneProps.id === 'new',+})+```++It lives in `frontend/src/scenes/max/useSceneAgentPanel.ts` rather than in this product's `api/`, because the Max scene is a consumer of the surface, not part of it. The whole integration rides a rollout flag, so nothing attaches or auto-opens for users it hasn't reached. Exemplar caller: `products/workflows/frontend/Workflows/WorkflowScene.tsx`.++## Do not use++- **`useMaxTool`** (`frontend/src/scenes/max/useMaxTool.ts`) and the `<MaxTool>` wrapper. Its callback fires on the LangGraph runtime only. New integrations use seams 1–4.+- **`MaxUIContext` / `maxContextLogic`** and the `maxContext` selector on scene logics. This is the legacy context store; add `AttachedContextItem`s instead.++## Directory map++```text+frontend/ # the agent-run surface + the api/ facade you import (see frontend/README.md)+backend/ # the run API that serves the surface — not an integration point for other products+mcp/ # this product's own MCP tools+skills/ # agent skills owned by PostHog AI, plus the repo-wide skills build (see skills/README.md)+evals/ # eval suites (see evals/AGENTS.md)+eval_harness/ # the harness those suites run on+dags/ # Dagster assets```-### Workflow+## Where to read next-1. Edit skill sources in `products/*/skills/`-2. Push to master — CI builds the ZIP and creates a GitHub release (`agent-skills-latest` + versioned)+- [`frontend/README.md`](./frontend/README.md) — the full tier table, every export, and copy-paste recipes.+- [`frontend/AGENTS.md`](./frontend/AGENTS.md) — contributor guide for the surface itself: streaming architecture, the coupling boundary, conventions.+- [`skills/README.md`](./skills/README.md) — the skills this product owns and the build pipeline.+- [`/implementing-mcp-tools`](../../.agents/skills/implementing-mcp-tools/SKILL.md) — how to give the agent a new capability.diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex b77c40485ec5..cfe027b85168 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -7,6 +7,10 @@ badge, or registering a product's tool cards, you consume it from here.> Building _on_ the surface (adding a thread-item type, a permission rule, stream telemetry)? That's the> contributor guide — [`AGENTS.md`](./AGENTS.md) — not this file.+> Integrating a **product scene** with the agent — attaching context, injecting instructions, reacting to+> tool calls, registering your product's tool cards? Start at [`../README.md`](../README.md), which walks+> those seams end to end and routes you back here for the detail.+## 1. How to import — the one ruleImport from a domain-scoped **`api/<module>`** entry. Never reach into deep internal pathsdiff --git a/products/posthog_ai/skills/README.md b/products/posthog_ai/skills/README.mdnew file mode 100644index 000000000000..04062fd42abd--- /dev/null+++ b/products/posthog_ai/skills/README.md@@ -0,0 +1,57 @@+# PostHog AI skills++Agent skills owned by PostHog AI.+Built by `hogli build:skills` and installed into sandbox containers for background agents.+Also available to Claude Code / Codex via `hogli sync:skill`.++This directory also happens to host the build pipeline for _every_ product's skills — see [Build pipeline](#build-pipeline) below.++## Skills++- **querying-posthog-data** — required reading before writing any HogQL/SQL. Indexes ~60 references covering the `system.*` table schemas, HogQL's differences from ClickHouse SQL, available functions, and the semantic layer (canonical metrics in `system.information_schema.metrics`).+- **managing-subscriptions** — scheduled email, Slack, and webhook deliveries of insight or dashboard snapshots, optionally with an AI-written summary. Covers subscriptions vs alerts, prompt subscriptions, and the AI-consent and quota gates.+- **auditing-experiments-flags** — health-checks experiments and feature flags for configuration issues, staleness, and best-practice violations, with severity-badged findings.+- **writing-simplified-technical-english** — writes English a reader cannot misread, based on ASD-STE100. Used at runtime by Signals and Review Hog for any prose an agent produces that someone else acts on.+- **checking-deploy-timing** — determines when a PostHog code change reached an environment, by reading the hidden `GIT` deploy annotations and correlating them with the merge commit on GitHub. Internal staff only.++## Adding a new skill++```bash+hogli init:skill -- --product posthog_ai --name my-new-skill+```++Read [`/writing-skills`](../../../.agents/skills/writing-skills/SKILL.md) first — it carries the naming, description, and structure rules, and the [handbook guide](../../../docs/published/handbook/engineering/ai/writing-skills.md) has the full version.++Two things worth knowing before you add one:++- **Skill count is a budgeted, shared resource.** Agents pick from a list of _all_ skill descriptions, and many harnesses truncate that list. More depth belongs in an existing skill's `references/`, not in a new skill.+- **These skills ship to users.** They are packaged into `dist/skills.zip` and published as a GitHub release. Internal, repo-only guidance for engineers working in this monorepo belongs in [`.agents/skills/`](../../../.agents/skills/) instead.++## Build pipeline++Skills live in `products/*/skills/` as Markdown or Jinja2 templates. The build renders them into `products/posthog_ai/dist/skills/` (human-readable) and packages them into `dist/skills.zip`. Both are gitignored — CI builds the ZIP from source and publishes it as a GitHub release.++```bash+hogli build:skills # Build skills to dist/skills/ and dist/skills.zip+hogli build:skills --list # List discovered skills+hogli lint:skills # Validate skill sources without rendering (syntax, frontmatter, depth, tool references)+hogli init:skill --product <product> --name <name> # Scaffold a new skill+hogli init:skill --product <product> --name <name> --j2 # Scaffold as Jinja2 template+```++`lint:skills` also cross-checks the MCP tool and skill names you reference in prose against the real registries, so a renamed tool fails the lint instead of misleading an agent.++### Local testing++```bash+hogli sync:skill -- --name <skill-name> # Copy the built skill into .agents/skills/ for Claude Code+hogli unsync:skill -- --name <skill-name> # Remove it again+```++### Workflow++1. Edit skill sources in `products/*/skills/`+2. Run `hogli lint:skills`, then `hogli sync:skill` to try it in a real agent session+3. Push to master — CI builds the ZIP and creates a GitHub release (`agent-skills-latest` + versioned)++The pipeline itself lives in [`products/posthog_ai/scripts/build_skills.py`](../scripts/build_skills.py).