:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(posthog-ai): support pi task sessions on the web (#108899)
Shy Alterdcef94078121
diff --git a/common/storybook/.storybook/main.ts b/common/storybook/.storybook/main.tsindex b501c9c2715a..877812f3273d 100644--- a/common/storybook/.storybook/main.ts+++ b/common/storybook/.storybook/main.ts@@ -111,6 +111,14 @@ const config: StorybookConfig = {'@posthog/shared-onboarding': path.resolve(REPO_ROOT, 'docs', 'onboarding'),'@posthog/quill': path.resolve(REPO_ROOT, 'packages', 'quill', 'packages', 'quill', 'src'),'@posthog/quill-charts': path.resolve(REPO_ROOT, 'packages', 'quill', 'packages', 'charts', 'src'),+ '@posthog/agent-contracts': path.resolve(+ REPO_ROOT,+ 'packages',+ 'agent',+ 'packages',+ 'agent-contracts',+ 'src'+ ),},},define: {diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex 9f455ff1623d..1961190e67ac 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -154,6 +154,7 @@ const config: Config = {'^@posthog/replay-shared/(.*)$': '<rootDir>/../common/replay-shared/src/$1','^@posthog/llm-normalizer$': '<rootDir>/../packages/llm-normalizer/src/index.ts','^@posthog/llm-normalizer/(.*)$': '<rootDir>/../packages/llm-normalizer/src/$1',+ '^@posthog/agent-contracts/(.*)$': '<rootDir>/../packages/agent/packages/agent-contracts/src/$1','^@posthog/quill$': '<rootDir>/../packages/quill/packages/quill/src/index.ts','^@posthog/quill-blocks$': '<rootDir>/../packages/quill/packages/blocks/src/index.ts','^@posthog/quill-charts$': '<rootDir>/../packages/quill/packages/charts/src/index.ts',diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3066d4e6a6ac..f464f8c5e735 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14426,6 +14426,10 @@ snapshots:hash: v1.k794b7964.b96b8b86fa0f5b0d6fcc7731a83830b2fb51f9d2534c772a155c55d90f13c730.AGvlm25vYELkMI_GF-_Bng6fHKPvZXZEi3c4XkoWzfgscenes-app-tasks--new-task-with-repository--light:hash: v1.k794b7964.9d642604e30074883b4ed69e9c5965fd12780d9d481a97363f15a46af0d54b38.e_DQSN2xqXAPcmJeyrASvlyjQp5FcLAVFXha99Fe6Qo+ scenes-app-tasks--pi-task-selected--dark:+ hash: v1.k794b7964.af9b88ddbc10b17dc0ccda95758fbf1ae9d103bcd0e511ec0352f76a1d0c2b80.kCLLV2HlqIkS_cCK8f1QsGpT7aNOgRJ6i7SRLgSzRv8+ scenes-app-tasks--pi-task-selected--light:+ hash: v1.k794b7964.dc94140b8460e76c6e8b81adb9c46997c89a5634f20fac20ddada1f1ffd12223.4KOsU0tDj1zB26GFLV3daFR9ypOtXtETf08ZsGEMZt4scenes-app-tasks--task-detail-loading--dark:hash: v1.k794b7964.8c04d529d803b961fcd596d0f748a22e0254ab185dc85bd42d3be47ff68e1902.3-VexQvKrWZFj_n7bOgXF3_lGw9S9zB4QYHA00Rpfh0scenes-app-tasks--task-detail-loading--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 50501b211150..49e44842d3c0 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -481,6 +481,7 @@ export const FEATURE_FLAGS = {PHAI_SANDBOX_MODE: 'phai-sandbox-mode', // owner: #team-posthog-aiPHAI_SCENE_AUTO_OPEN: 'phai-scene-auto-open', // owner: #team-posthog-aiPHAI_TASKS: 'phai-tasks', // owner: #team-array+ PI_ACP: 'pi-acp', // owner: #team-agent-infrastructure, Pi runs write ACP and show on the web run surfacePIPELINE_STATUS_PAGE: 'pipeline-status-page', // owner: @clr182 #team-supportPLATFORM_ALERTS: 'platform-alerts', // owner: #team-apm, gates the shared alerts platform read API and UIPOSTHOG_AI_BILLING_DISPLAY: 'posthog-ai-billing-display', // owner: #team-posthog-aidiff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 759eec353777..18e4611c9f64 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -322,12 +322,14 @@ export interface maxThreadLogicActions {retainedMessage?: stringrunId: stringtaskId: string+ taskRuntime?: string | nulltraceId?: string}) => {justCreatedRun?: boolean | undefinedretainedMessage?: string | undefinedrunId: stringtaskId: string+ taskRuntime?: string | null | undefinedtraceId?: string | undefined} // runStreamLogiccancelSandboxRun: (diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 5c6308735ec6..bdceba8560e1 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -83,6 +83,7 @@ export default defineConfig(({ mode }) => {'node_modules/@posthog/llm-normalizer/src/types.ts'),'@posthog/llm-normalizer': resolve(__dirname, 'node_modules/@posthog/llm-normalizer/src/index.ts'),+ '@posthog/agent-contracts': resolve(__dirname, '../packages/agent/packages/agent-contracts/src'),// These @tiptap packages live only in frontend/node_modules, which products/*/frontend// files can't reach by walking up from their own directory. Alias each package// individually: a blanket '@tiptap' prefix would also rewrite the imports *inside*diff --git a/packages/agent/packages/agent-contracts/src/acp-conversation.test.ts b/packages/agent/packages/agent-contracts/src/acp-conversation.test.tsnew file mode 100644index 000000000000..fa411846728d--- /dev/null+++ b/packages/agent/packages/agent-contracts/src/acp-conversation.test.ts@@ -0,0 +1,409 @@+import { describe, expect, it } from "vitest";+import {+ acpNotificationToAgentConversationEvent,+ agentConversationEventToAcpNotification,+} from "./acp-conversation";+import type { AgentConversationEvent } from "./agent-conversation";++describe("agentConversationEventToAcpNotification", () => {+ it.each<{+ caseName: string;+ event: AgentConversationEvent;+ expected: unknown;+ }>([+ {+ caseName: "a user message with an attachment",+ event: {+ type: "user_message",+ id: "u1",+ timestamp: 1,+ content: [+ { type: "text", text: "Check this" },+ {+ type: "resource_link",+ uri: "file:///w/.posthog/attachments/run/a/notes.md",+ name: "notes.md",+ },+ ],+ },+ expected: {+ method: "_posthog/user_message",+ params: {+ content: [+ { type: "text", text: "Check this" },+ {+ type: "resource_link",+ uri: "file:///w/.posthog/attachments/run/a/notes.md",+ name: "notes.md",+ },+ ],+ messageId: "u1",+ },+ },+ },+ {+ caseName: "a reasoning chunk",+ event: {+ type: "assistant_thought_chunk",+ timestamp: 1,+ content: { type: "text", text: "hm" },+ },+ expected: {+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "agent_thought_chunk",+ content: { type: "text", text: "hm" },+ },+ },+ },+ },+ {+ caseName: "a tool start, keeping its title and tool meta",+ event: {+ type: "tool_call_started",+ timestamp: 1,+ toolCall: {+ id: "t1",+ title: "read",+ kind: "read",+ status: "pending",+ rawInput: { path: "a.ts" },+ locations: [{ path: "a.ts" }],+ _meta: { posthog: { toolName: "Read" } },+ },+ },+ expected: {+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "tool_call",+ toolCallId: "t1",+ title: "read",+ kind: "read",+ status: "pending",+ rawInput: { path: "a.ts" },+ locations: [{ path: "a.ts" }],+ _meta: { posthog: { toolName: "Read" } },+ },+ },+ },+ },+ {+ caseName:+ "a subagent tool update, adding its parent without losing the tool meta",+ event: {+ type: "tool_call_updated",+ timestamp: 1,+ toolCall: {+ id: "t2",+ parentId: "t1",+ status: "completed",+ _meta: { posthog: { toolName: "Read" } },+ },+ },+ expected: {+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "tool_call_update",+ toolCallId: "t2",+ status: "completed",+ _meta: {+ posthog: { toolName: "Read" },+ claudeCode: { parentToolCallId: "t1" },+ },+ },+ },+ },+ },+ {+ caseName: "a tool update without an id",+ event: {+ type: "tool_call_updated",+ timestamp: 1,+ toolCall: { id: "" },+ },+ expected: null,+ },+ {+ caseName: "a turn end from a log that still says aborted",+ event: { type: "turn_completed", timestamp: 1, stopReason: "aborted" },+ expected: {+ method: "_posthog/turn_complete",+ params: { stopReason: "cancelled" },+ },+ },+ {+ caseName: "a turn end with usage",+ event: {+ type: "turn_completed",+ timestamp: 1,+ stopReason: "end_turn",+ usage: {+ inputTokens: 5,+ outputTokens: 1,+ cachedReadTokens: 0,+ cachedWriteTokens: 0,+ totalTokens: 6,+ },+ },+ expected: {+ method: "_posthog/turn_complete",+ params: {+ stopReason: "end_turn",+ usage: {+ inputTokens: 5,+ outputTokens: 1,+ cachedReadTokens: 0,+ cachedWriteTokens: 0,+ totalTokens: 6,+ },+ },+ },+ },+ {+ caseName: "a runtime error",+ event: {+ type: "runtime_error",+ timestamp: 1,+ errorType: "pi_runtime",+ message: "boom",+ },+ expected: {+ method: "_posthog/error",+ params: { message: "boom", errorType: "pi_runtime" },+ },+ },+ {+ caseName: "a retry status",+ event: { type: "runtime_status", timestamp: 1, status: "retrying" },+ expected: {+ method: "_posthog/status",+ params: { status: "retrying", isComplete: false },+ },+ },+ ])("maps $caseName", ({ event, expected }) => {+ expect(agentConversationEventToAcpNotification(event)).toEqual(expected);+ });+});++describe("acpNotificationToAgentConversationEvent", () => {+ it.each<{ caseName: string; event: AgentConversationEvent }>([+ {+ caseName: "a user message",+ event: {+ type: "user_message",+ id: "u1",+ timestamp: 1000,+ content: [{ type: "text", text: "hi" }],+ },+ },+ {+ caseName: "a message chunk",+ event: {+ type: "assistant_message_chunk",+ timestamp: 1000,+ content: { type: "text", text: "yo" },+ },+ },+ {+ caseName: "a reasoning chunk",+ event: {+ type: "assistant_thought_chunk",+ timestamp: 1000,+ content: { type: "text", text: "hm" },+ },+ },+ {+ caseName: "a user shell command",+ event: {+ type: "tool_call_started",+ timestamp: 1000,+ toolCall: {+ id: "pi-bash-1",+ title: "ls",+ kind: "execute",+ rawInput: { command: "ls" },+ origin: "user_shell",+ },+ },+ },+ {+ caseName: "a tool start with tool meta",+ event: {+ type: "tool_call_started",+ timestamp: 1000,+ toolCall: {+ id: "t1",+ title: "read",+ kind: "read",+ status: "pending",+ locations: [{ path: "a.ts" }],+ _meta: { posthog: { toolName: "Read" } },+ },+ },+ },+ {+ caseName: "a subagent tool update with tool meta",+ event: {+ type: "tool_call_updated",+ timestamp: 1000,+ toolCall: {+ id: "t2",+ parentId: "t1",+ status: "completed",+ _meta: { posthog: { toolName: "Read" } },+ },+ },+ },+ {+ caseName: "a subagent tool update without tool meta",+ event: {+ type: "tool_call_updated",+ timestamp: 1000,+ toolCall: { id: "t3", parentId: "t1", status: "failed" },+ },+ },+ {+ caseName: "a progress step",+ event: {+ type: "progress",+ timestamp: 1000,+ step: "clone",+ status: "completed",+ label: "Cloning",+ group: "setup",+ detail: "posthog/posthog",+ },+ },+ {+ caseName: "a retry status",+ event: {+ type: "runtime_status",+ timestamp: 1000,+ status: "retrying",+ isComplete: false,+ message: "Rate limited",+ attempt: 2,+ maxAttempts: 5,+ delayMs: 4000,+ },+ },+ {+ caseName: "a runtime error",+ event: {+ type: "runtime_error",+ timestamp: 1000,+ errorType: "pi_runtime",+ message: "boom",+ },+ },+ {+ caseName: "a turn end with usage",+ event: {+ type: "turn_completed",+ timestamp: 1000,+ stopReason: "end_turn",+ totalTokens: 6,+ usage: {+ inputTokens: 5,+ outputTokens: 1,+ cachedReadTokens: 0,+ cachedWriteTokens: 0,+ totalTokens: 6,+ contextTokens: 6,+ contextWindow: 200000,+ },+ },+ },+ {+ caseName: "a queue update",+ event: {+ type: "queue_update",+ timestamp: 1000,+ steering: ["stop"],+ followUp: [],+ },+ },+ ])("restores $caseName from its ACP form", ({ event }) => {+ const notification = agentConversationEventToAcpNotification(event);+ expect(notification).not.toBeNull();+ expect(+ acpNotificationToAgentConversationEvent(+ notification as NonNullable<typeof notification>,+ event.timestamp,+ ),+ ).toEqual(event);+ });++ it("reads a whole agent message as one message chunk", () => {+ expect(+ acpNotificationToAgentConversationEvent(+ {+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "agent_message",+ content: { type: "text", text: "pong" },+ },+ },+ },+ 1000,+ ),+ ).toEqual({+ type: "assistant_message_chunk",+ timestamp: 1000,+ content: { type: "text", text: "pong" },+ });+ });++ it("restores a tool title the sender dropped because it repeated the tool name", () => {+ expect(+ acpNotificationToAgentConversationEvent(+ {+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "tool_call",+ toolCallId: "t1",+ name: "read",+ kind: "read",+ },+ },+ },+ 1000,+ ),+ ).toEqual({+ type: "tool_call_started",+ timestamp: 1000,+ toolCall: { id: "t1", name: "read", title: "read", kind: "read" },+ });+ });++ it.each([+ {+ caseName: "a notification a Pi extension message produced",+ notification: {+ method: "_posthog/status",+ params: {+ status: "extension_notice",+ isComplete: true,+ message: "lint.ts failed: boom",+ _meta: { piExtension: { type: "extension_error", error: "boom" } },+ },+ },+ },+ {+ caseName: "a usage update",+ notification: {+ method: "_posthog/usage_update",+ params: { used: { inputTokens: 5 } },+ },+ },+ ])("maps $caseName to no conversation event", ({ notification }) => {+ expect(acpNotificationToAgentConversationEvent(notification, 1000)).toBe(+ null,+ );+ });+});diff --git a/packages/agent/packages/agent-contracts/src/acp-conversation.ts b/packages/agent/packages/agent-contracts/src/acp-conversation.tsnew file mode 100644index 000000000000..ee090f30c93b--- /dev/null+++ b/packages/agent/packages/agent-contracts/src/acp-conversation.ts@@ -0,0 +1,284 @@+import type {+ AgentContent,+ AgentConversationEvent,+ AgentToolCall,+} from "./agent-conversation";++export const PI_EXTENSION_META_KEY = "piExtension";++export type AcpToolCallSessionUpdate = {+ sessionUpdate: "tool_call" | "tool_call_update";+ toolCallId: string;+} & Record<string, unknown>;++export type AcpConversationSessionUpdate =+ | {+ sessionUpdate: "agent_message_chunk" | "agent_thought_chunk";+ content: unknown;+ }+ | AcpToolCallSessionUpdate;++export interface AcpConversationNotification {+ method: string;+ params: Record<string, unknown>;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function definedFields(+ fields: Record<string, unknown>,+): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(fields).filter(+ ([, value]) => value !== undefined && value !== null,+ ),+ );+}++function toolCallSessionUpdate(+ sessionUpdate: AcpToolCallSessionUpdate["sessionUpdate"],+ toolCall: Partial<AgentToolCall>,+): AcpToolCallSessionUpdate | null {+ const { id, parentId, ...fields } = toolCall;+ if (typeof id !== "string" || !id) {+ return null;+ }+ const update: AcpToolCallSessionUpdate = {+ sessionUpdate,+ toolCallId: id,+ ...definedFields(fields),+ };+ if (parentId) {+ const meta = fields._meta ?? {};+ const claudeCode = isRecord(meta.claudeCode) ? meta.claudeCode : {};+ update._meta = {+ ...meta,+ claudeCode: { ...claudeCode, parentToolCallId: parentId },+ };+ }+ return update;+}++function toolCallFromSessionUpdate(+ update: Record<string, unknown>,+): Record<string, unknown> | null {+ const { sessionUpdate: _sessionUpdate, toolCallId, ...fields } = update;+ if (typeof toolCallId !== "string" || !toolCallId) {+ return null;+ }+ const toolCall: Record<string, unknown> = { ...fields, id: toolCallId };+ if (toolCall.title === undefined && typeof fields.name === "string") {+ toolCall.title = fields.name;+ }+ const meta = isRecord(fields._meta) ? fields._meta : null;+ const claudeCode = meta && isRecord(meta.claudeCode) ? meta.claudeCode : null;+ if (meta && claudeCode && typeof claudeCode.parentToolCallId === "string") {+ toolCall.parentId = claudeCode.parentToolCallId;+ const { parentToolCallId: _parentToolCallId, ...otherClaudeCode } =+ claudeCode;+ const { claudeCode: _claudeCode, ...otherMeta } = meta;+ const restoredMeta =+ Object.keys(otherClaudeCode).length > 0+ ? { ...otherMeta, claudeCode: otherClaudeCode }+ : otherMeta;+ if (Object.keys(restoredMeta).length > 0) {+ toolCall._meta = restoredMeta;+ } else {+ delete toolCall._meta;+ }+ }+ return toolCall;+}++export function agentConversationEventToSessionUpdate(+ event: AgentConversationEvent,+): AcpConversationSessionUpdate | null {+ switch (event.type) {+ case "assistant_message_chunk":+ return { sessionUpdate: "agent_message_chunk", content: event.content };+ case "assistant_thought_chunk":+ return { sessionUpdate: "agent_thought_chunk", content: event.content };+ case "tool_call_started":+ return toolCallSessionUpdate("tool_call", event.toolCall);+ case "tool_call_updated":+ return toolCallSessionUpdate("tool_call_update", event.toolCall);+ default:+ return null;+ }+}++export function agentConversationEventToAcpNotification(+ event: AgentConversationEvent,+): AcpConversationNotification | null {+ const update = agentConversationEventToSessionUpdate(event);+ if (update) {+ return { method: "session/update", params: { update } };+ }+ switch (event.type) {+ case "user_message":+ return {+ method: "_posthog/user_message",+ params: { content: event.content, messageId: event.id },+ };+ case "progress":+ return {+ method: "_posthog/progress",+ params: definedFields({+ step: event.step,+ status: event.status,+ label: event.label,+ group: event.group,+ detail: event.detail,+ }),+ };+ case "runtime_status":+ return {+ method: "_posthog/status",+ params: {+ ...definedFields({+ status: event.status,+ error: event.error,+ message: event.message,+ attempt: event.attempt,+ maxAttempts: event.maxAttempts,+ delayMs: event.delayMs,+ }),+ isComplete: event.isComplete === true,+ },+ };+ case "runtime_error":+ return {+ method: "_posthog/error",+ params: { message: event.message, errorType: event.errorType },+ };+ case "turn_completed":+ return {+ method: "_posthog/turn_complete",+ params: definedFields({+ stopReason:+ event.stopReason === "aborted" ? "cancelled" : event.stopReason,+ usage: event.usage,+ totalTokens: event.totalTokens,+ }),+ };+ case "queue_update":+ return {+ method: "_posthog/pi_queue_update",+ params: { steering: event.steering, followUp: event.followUp },+ };+ default:+ return null;+ }+}++export function readPiExtensionMessage(+ params: unknown,+): Record<string, unknown> | null {+ const meta = isRecord(params) ? params._meta : undefined;+ const message = isRecord(meta) ? meta[PI_EXTENSION_META_KEY] : undefined;+ return isRecord(message) ? message : null;+}++export function acpNotificationToAgentConversationEvent(+ notification: AcpConversationNotification,+ timestamp: number,+): AgentConversationEvent | null {+ const { method, params } = notification;+ if (readPiExtensionMessage(params)) {+ return null;+ }+ switch (method) {+ case "session/update": {+ const update = params.update;+ if (!isRecord(update)) {+ return null;+ }+ switch (update.sessionUpdate) {+ case "agent_message":+ case "agent_message_chunk":+ return {+ type: "assistant_message_chunk",+ timestamp,+ content: update.content as AgentContent,+ };+ case "agent_thought_chunk":+ return {+ type: "assistant_thought_chunk",+ timestamp,+ content: update.content as AgentContent,+ };+ case "tool_call": {+ const toolCall = toolCallFromSessionUpdate(update);+ return toolCall+ ? {+ type: "tool_call_started",+ timestamp,+ toolCall: toolCall as unknown as AgentToolCall,+ }+ : null;+ }+ case "tool_call_update": {+ const toolCall = toolCallFromSessionUpdate(update);+ return toolCall+ ? {+ type: "tool_call_updated",+ timestamp,+ toolCall: toolCall as unknown as AgentToolCall,+ }+ : null;+ }+ default:+ return null;+ }+ }+ case "_posthog/user_message":+ return {+ type: "user_message",+ id: typeof params.messageId === "string" ? params.messageId : "",+ timestamp,+ content: Array.isArray(params.content)+ ? (params.content as AgentContent[])+ : [],+ };+ case "_posthog/progress":+ return {+ ...params,+ type: "progress",+ timestamp,+ } as AgentConversationEvent;+ case "_posthog/status":+ return {+ ...params,+ type: "runtime_status",+ timestamp,+ } as AgentConversationEvent;+ case "_posthog/error":+ return {+ type: "runtime_error",+ timestamp,+ errorType: String(params.errorType ?? ""),+ message: String(params.message ?? ""),+ };+ case "_posthog/turn_complete":+ return {+ ...params,+ type: "turn_completed",+ timestamp,+ } as AgentConversationEvent;+ case "_posthog/pi_queue_update":+ return {+ type: "queue_update",+ timestamp,+ steering: Array.isArray(params.steering)+ ? (params.steering as string[])+ : [],+ followUp: Array.isArray(params.followUp)+ ? (params.followUp as string[])+ : [],+ };+ default:+ return null;+ }+}diff --git a/packages/agent/packages/agent-contracts/src/agent-conversation.ts b/packages/agent/packages/agent-contracts/src/agent-conversation.tsindex defecacb1397..fc873940884b 100644--- a/packages/agent/packages/agent-contracts/src/agent-conversation.ts+++ b/packages/agent/packages/agent-contracts/src/agent-conversation.ts@@ -122,6 +122,7 @@ export interface AgentToolCall {details?: unknown;parentId?: string;origin?: "agent" | "user_shell";+ _meta?: Record<string, unknown> | null;}interface AgentConversationEventIdentity {diff --git a/packages/agent/packages/agent-contracts/src/index.ts b/packages/agent/packages/agent-contracts/src/index.tsindex 0004d7eff39d..13766e65ee55 100644--- a/packages/agent/packages/agent-contracts/src/index.ts+++ b/packages/agent/packages/agent-contracts/src/index.ts@@ -1,3 +1,11 @@+export {+ type AcpConversationNotification,+ acpNotificationToAgentConversationEvent,+ agentConversationEventToAcpNotification,+ agentConversationEventToSessionUpdate,+ PI_EXTENSION_META_KEY,+ readPiExtensionMessage,+} from "./acp-conversation";export * from "./adapter";export {buildActionUrl,diff --git a/packages/agent/packages/agent-contracts/src/pi-tool-call.test.ts b/packages/agent/packages/agent-contracts/src/pi-tool-call.test.tsindex 4b4e40f51922..ab4b41ca3548 100644--- a/packages/agent/packages/agent-contracts/src/pi-tool-call.test.ts+++ b/packages/agent/packages/agent-contracts/src/pi-tool-call.test.ts@@ -1,5 +1,52 @@import { describe, expect, it } from "vitest";-import { parsePiMcpCallDetails } from "./pi-tool-call";+import { createPiToolCallRecord, parsePiMcpCallDetails } from "./pi-tool-call";++describe("createPiToolCallRecord", () => {+ it.each([+ ["read", "Read"],+ ["bash", "Bash"],+ ["edit", "Edit"],+ ["write", "Write"],+ ["grep", "Grep"],+ ["find", "Glob"],+ ["ls", "LS"],+ ])("names the %s built-in %s on _meta.posthog", (name, toolName) => {+ expect(+ createPiToolCallRecord({ id: "t", name, arguments: {} }, "pending")._meta,+ ).toEqual({ posthog: { toolName } });+ });++ it("carries the proxied MCP call on _meta.posthog", () => {+ expect(+ createPiToolCallRecord(+ {+ id: "t",+ name: "mcp",+ arguments: { tool: "linear_create_issue", args: '{"title":"x"}' },+ },+ "pending",+ )._meta,+ ).toEqual({+ posthog: {+ toolName: "mcp",+ mcpProxy: {+ kind: "tool",+ name: "linear_create_issue",+ args: '{"title":"x"}',+ },+ },+ });+ });++ it("keeps an unknown tool's own name", () => {+ expect(+ createPiToolCallRecord(+ { id: "t", name: "set_current_work", arguments: {} },+ "pending",+ )._meta,+ ).toEqual({ posthog: { toolName: "set_current_work" } });+ });+});describe("parsePiMcpCallDetails", () => {it.each(["mcp_posthog_exec", "mcp__posthog__exec"])(diff --git a/packages/agent/packages/agent-contracts/src/pi-tool-call.ts b/packages/agent/packages/agent-contracts/src/pi-tool-call.tsindex 09b81006e544..0a9d19e0430a 100644--- a/packages/agent/packages/agent-contracts/src/pi-tool-call.ts+++ b/packages/agent/packages/agent-contracts/src/pi-tool-call.ts@@ -4,6 +4,7 @@ import type {AgentToolCallStatus,AgentToolKind,} from "./agent-conversation";+import type { PosthogToolMeta } from "./tool-meta";export const PI_TOOL_KIND_BY_NAME = {read: "read",@@ -17,6 +18,20 @@ export const PI_TOOL_KIND_BY_NAME = {export type PiToolName = keyof typeof PI_TOOL_KIND_BY_NAME;+/**+ * The harness-neutral name of each Pi built-in, as carried on `_meta.posthog.toolName`. The Claude+ * adapter emits the same names for the same operations, so one renderer entry serves both harnesses.+ */+const PI_AGENT_TOOL_NAME_BY_NAME = {+ read: "Read",+ edit: "Edit",+ write: "Write",+ bash: "Bash",+ grep: "Grep",+ find: "Glob",+ ls: "LS",+} as const satisfies Record<PiToolName, string>;+export interface PiToolCallInput {id: string;name: string;@@ -206,9 +221,29 @@ export const piToolCallRecordSchema = z.object({}),).optional(),+ _meta: z+ .object({+ posthog: z.object({+ toolName: z.string().min(1),+ mcpProxy: piMcpCallDetailsSchema.optional(),+ }),+ })+ .optional(),});export type PiToolCallRecord = z.infer<typeof piToolCallRecordSchema>;+function piToolMeta(+ name: string,+ details: PiMcpCallDetails | undefined,+): { posthog: PosthogToolMeta } {+ return {+ posthog: {+ toolName: isPiToolName(name) ? PI_AGENT_TOOL_NAME_BY_NAME[name] : name,+ ...(details ? { mcpProxy: details } : {}),+ },+ };+}+export function isPiToolName(name: string): name is PiToolName {return name in PI_TOOL_KIND_BY_NAME;}@@ -246,5 +281,6 @@ export function createPiToolCallRecord(rawInput: input.arguments,...(details ? { details } : {}),...(locations ? { locations } : {}),+ _meta: piToolMeta(input.name, details),};}diff --git a/packages/agent/packages/agent/src/pi/acp-wire.test.ts b/packages/agent/packages/agent/src/pi/acp-wire.test.tsnew file mode 100644index 000000000000..531c65ed7183--- /dev/null+++ b/packages/agent/packages/agent/src/pi/acp-wire.test.ts@@ -0,0 +1,281 @@+import { describe, expect, it } from "vitest";+import {+ type PiExtensionDialog,+ piAcpLogEntries,+ piAcpWireEntry,+ piExtensionDialogResponse,+} from "./acp-wire";++function notificationOf(entry: Record<string, unknown>) {+ return (+ piAcpWireEntry(entry) as {+ notification?: { method?: string; params?: Record<string, unknown> };+ } | null+ )?.notification;+}++describe("piAcpWireEntry", () => {+ it.each([+ {+ caseName: "a tool start whose title only repeats the tool name",+ toolCall: {+ id: "t1",+ name: "read",+ title: "read",+ kind: "read",+ _meta: { posthog: { toolName: "Read" } },+ },+ expected: {+ sessionUpdate: "tool_call",+ toolCallId: "t1",+ name: "read",+ kind: "read",+ _meta: { posthog: { toolName: "Read" } },+ },+ },+ {+ caseName: "a user shell command, which keeps its command as the title",+ toolCall: { id: "pi-bash-1", title: "ls", kind: "execute" },+ expected: {+ sessionUpdate: "tool_call",+ toolCallId: "pi-bash-1",+ title: "ls",+ kind: "execute",+ },+ },+ ])("writes $caseName as a session update", ({ toolCall, expected }) => {+ expect(+ piAcpWireEntry({+ type: "pi_event",+ id: "entry-1",+ timestamp: "2026-01-01T00:00:00Z",+ event_id: "boot-3",+ covered_event_ids: ["boot-1"],+ event: { type: "tool_call_started", timestamp: 1, toolCall },+ }),+ ).toEqual({+ type: "notification",+ id: "entry-1",+ timestamp: "2026-01-01T00:00:00Z",+ event_id: "boot-3",+ covered_event_ids: ["boot-1"],+ notification: {+ jsonrpc: "2.0",+ method: "session/update",+ params: { update: expected },+ },+ });+ });++ it.each([+ {+ caseName: "run start marker",+ entry: { type: "pi_run_started", runId: "run-1", taskId: "task-1" },+ method: "_posthog/run_started",+ },+ {+ caseName: "persisted extension request",+ entry: {+ type: "pi_extension_event",+ notification: {+ method: "_posthog/pi_extension_event",+ params: {+ type: "extension_ui_request",+ id: "e1",+ method: "select",+ title: "Pick",+ options: ["A", "B"],+ },+ },+ },+ method: "_posthog/permission_request",+ },+ {+ caseName: "live extension response",+ entry: { type: "extension_ui_response", id: "e1", value: "A" },+ method: "_posthog/permission_resolved",+ },+ {+ caseName: "fire-and-forget notify",+ entry: {+ type: "extension_ui_request",+ id: "e2",+ method: "notify",+ message: "Saved",+ },+ method: "_posthog/console",+ },+ {+ caseName: "widget update",+ entry: {+ type: "extension_ui_request",+ id: "e3",+ method: "setStatus",+ statusKey: "lint",+ statusText: "ok",+ },+ method: "_posthog/pi_extension_event",+ },+ ])("translates a $caseName into $method", ({ entry, method }) => {+ expect(notificationOf(entry)?.method).toBe(method);+ });++ it.each([+ {+ caseName: "a warning notification",+ entry: {+ type: "extension_ui_request",+ id: "e3",+ method: "notify",+ message: "Lint warnings",+ notifyType: "warning",+ },+ message: "Lint warnings",+ },+ {+ caseName: "an extension failure",+ entry: {+ type: "extension_error",+ extensionPath: "/ext/lint.ts",+ event: "tool_call",+ error: "crashed",+ },+ message: "lint.ts failed during tool_call: crashed",+ },+ ])(+ "shows $caseName as a notice that carries the Pi message",+ ({ entry, message }) => {+ expect(notificationOf(entry)).toEqual({+ jsonrpc: "2.0",+ method: "_posthog/status",+ params: {+ status: "extension_notice",+ isComplete: true,+ message,+ _meta: { piExtension: entry },+ },+ });+ },+ );++ it.each([+ {+ method: "input",+ fields: { placeholder: "Branch name" },+ expected: { placeholder: "Branch name" },+ },+ {+ method: "editor",+ fields: { prefill: "Line one\nLine two" },+ expected: { defaultAnswer: "Line one\nLine two", multiline: true },+ },+ ])(+ "carries the $method prompt defaults onto its question",+ ({ method, fields, expected }) => {+ expect(+ notificationOf({+ type: "extension_ui_request",+ id: "e1",+ method,+ title: "Branch?",+ ...fields,+ })?.params,+ ).toMatchObject({+ toolCall: {+ _meta: {+ questions: [{ question: "Branch?", options: [], ...expected }],+ },+ },+ });+ },+ );++ it("passes an entry that is already ACP through unchanged", () => {+ const entry = {+ type: "notification",+ notification: { method: "_posthog/usage_update", params: {} },+ };+ expect(piAcpWireEntry(entry)).toBe(entry);+ });+});++describe("piExtensionDialogResponse", () => {+ const confirm: PiExtensionDialog = {+ id: "e1",+ method: "confirm",+ options: [],+ };+ const input: PiExtensionDialog = { id: "e1", method: "input", options: [] };+ const select: PiExtensionDialog = {+ id: "e1",+ method: "select",+ options: ["A", "B"],+ };++ it.each([+ {+ caseName: "a confirmed prompt",+ dialog: confirm,+ answer: { optionId: "confirm" },+ expected: { type: "extension_ui_response", id: "e1", confirmed: true },+ },+ {+ caseName: "a cancelled prompt",+ dialog: confirm,+ answer: { optionId: "cancel" },+ expected: { type: "extension_ui_response", id: "e1", cancelled: true },+ },+ {+ caseName: "an answered question",+ dialog: input,+ answer: { optionId: "option_0", answers: { "Branch?": "feat/x" } },+ expected: { type: "extension_ui_response", id: "e1", value: "feat/x" },+ },+ {+ caseName: "a picked option",+ dialog: select,+ answer: { optionId: "option_1" },+ expected: { type: "extension_ui_response", id: "e1", value: "B" },+ },+ ])("answers $caseName", ({ dialog, answer, expected }) => {+ expect(piExtensionDialogResponse(dialog, answer)).toEqual(expected);+ });+});++describe("piAcpLogEntries", () => {+ const chunk = (text: string, eventId: string) => ({+ type: "pi_event",+ id: `entry-${eventId}`,+ event_id: eventId,+ timestamp: "2026-01-01T00:00:00Z",+ event: {+ type: "assistant_message_chunk",+ timestamp: 1,+ content: { type: "text", text },+ },+ });++ it.each([+ { final: false, written: [], carried: 2 },+ { final: true, written: ["pong"], carried: 0 },+ ])(+ "holds back a message still streaming unless the flush is final ($final)",+ ({ final, written, carried }) => {+ const { wire, carry } = piAcpLogEntries(+ [chunk("po", "boot-1"), chunk("ng", "boot-2")],+ { final },+ );+ expect(+ wire.map(+ (entry) =>+ (+ entry.notification?.params as {+ update: { content: { text: string } };+ }+ ).update.content.text,+ ),+ ).toEqual(written);+ expect(carry).toHaveLength(carried);+ },+ );+});diff --git a/packages/agent/packages/agent/src/pi/acp-wire.ts b/packages/agent/packages/agent/src/pi/acp-wire.tsnew file mode 100644index 000000000000..0840cde54c62--- /dev/null+++ b/packages/agent/packages/agent/src/pi/acp-wire.ts@@ -0,0 +1,406 @@+import {+ type AcpConversationNotification,+ type AgentConversationEvent,+ agentConversationEventToAcpNotification,+ MCP_TOOL_PERMISSION_OPTIONS,+ PI_EXTENSION_META_KEY,+ type StoredLogEntry,+} from "@posthog/agent-contracts";+import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";+import type { RpcExtensionUIResponse } from "./types";++const CONFIRM_OPTION_ID = "confirm";+const CANCEL_OPTION_ID = "cancel";+const PI_EXTENSION_EVENT_METHOD = "_posthog/pi_extension_event";++export const PI_ACP_MCP_PERMISSION_OPTIONS = [+ { kind: "allow_once", name: "Allow", optionId: "allow" },+ ...MCP_TOOL_PERMISSION_OPTIONS.map((option) =>+ option.kind === "reject_once"+ ? {+ ...option,+ _meta: { hint: "Blocks this tool call. The agent keeps working." },+ }+ : option,+ ),+];++export type PiExtensionDialogMethod = "select" | "confirm" | "input" | "editor";++export interface PiExtensionDialog {+ id: string;+ method: PiExtensionDialogMethod;+ options: string[];+ timeout?: number;+}++export interface PermissionAnswer {+ optionId: string;+ customInput?: string;+ answers?: Record<string, string>;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function optionalString(value: unknown): string | undefined {+ return typeof value === "string" && value ? value : undefined;+}++function isDialogMethod(method: unknown): method is PiExtensionDialogMethod {+ return (+ method === "select" ||+ method === "confirm" ||+ method === "input" ||+ method === "editor"+ );+}++export function readPiExtensionDialog(+ message: Record<string, unknown>,+): PiExtensionDialog | null {+ const id = optionalString(message.id);+ if (+ message.type !== "extension_ui_request" ||+ !id ||+ !isDialogMethod(message.method)+ ) {+ return null;+ }+ return {+ id,+ method: message.method,+ options:+ message.method === "select" && Array.isArray(message.options)+ ? message.options.filter(+ (option): option is string =>+ typeof option === "string" && option !== "",+ )+ : [],+ ...(typeof message.timeout === "number" && message.timeout > 0+ ? { timeout: message.timeout }+ : {}),+ };+}++function withPiExtension(+ params: Record<string, unknown>,+ message: Record<string, unknown>,+): Record<string, unknown> {+ return { ...params, _meta: { [PI_EXTENSION_META_KEY]: message } };+}++function dialogRequest(+ message: Record<string, unknown>,+ dialog: PiExtensionDialog,+): AcpConversationNotification {+ if (dialog.method === "confirm") {+ const title =+ optionalString(message.title) ?? "The agent needs your confirmation";+ const detail = optionalString(message.message);+ return {+ method: POSTHOG_NOTIFICATIONS.PERMISSION_REQUEST,+ params: withPiExtension(+ {+ requestId: dialog.id,+ toolCall: {+ toolCallId: `pi-extension-${dialog.id}`,+ kind: "other",+ description: detail ? `${title}\n\n${detail}` : title,+ },+ options: [+ {+ optionId: CONFIRM_OPTION_ID,+ name: "Confirm",+ kind: "allow_once",+ },+ {+ optionId: CANCEL_OPTION_ID,+ name: "Cancel",+ kind: "reject_once",+ _meta: {+ hint: "Declines this request. The agent keeps working.",+ },+ },+ ],+ },+ message,+ ),+ };+ }+ const title = optionalString(message.title) ?? "The agent needs your input";+ return {+ method: POSTHOG_NOTIFICATIONS.PERMISSION_REQUEST,+ params: withPiExtension(+ {+ requestId: dialog.id,+ toolCall: {+ toolCallId: `pi-extension-${dialog.id}`,+ title,+ kind: "question",+ _meta: {+ codeToolKind: "question",+ questions: [+ {+ question: title,+ multiSelect: false,+ options: dialog.options.map((label) => ({ label })),+ ...(optionalString(message.placeholder)+ ? { placeholder: message.placeholder }+ : {}),+ ...(typeof message.prefill === "string"+ ? { defaultAnswer: message.prefill }+ : {}),+ ...(dialog.method === "editor" ? { multiline: true } : {}),+ },+ ],+ },+ },+ options:+ dialog.options.length > 0+ ? dialog.options.map((label, index) => ({+ optionId: `option_${index}`,+ name: label,+ kind: "allow_once",+ }))+ : [{ optionId: "option_0", name: "Submit", kind: "allow_once" }],+ },+ message,+ ),+ };+}++function extensionNotice(+ text: string,+ message: Record<string, unknown>,+): AcpConversationNotification {+ return {+ method: POSTHOG_NOTIFICATIONS.STATUS,+ params: withPiExtension(+ { status: "extension_notice", isComplete: true, message: text },+ message,+ ),+ };+}++export function piExtensionAcpNotification(+ message: Record<string, unknown>,+): AcpConversationNotification | null {+ if (message.type === "extension_ui_response") {+ const id = optionalString(message.id);+ return id+ ? {+ method: POSTHOG_NOTIFICATIONS.PERMISSION_RESOLVED,+ params: withPiExtension({ requestId: id }, message),+ }+ : null;+ }+ if (message.type === "extension_error") {+ const error = optionalString(message.error);+ if (!error) {+ return null;+ }+ const extension = optionalString(message.extensionPath)+ ?.split(/[\\/]/)+ .pop();+ const during = optionalString(message.event);+ return extensionNotice(+ extension+ ? `${extension} failed${during ? ` during ${during}` : ""}: ${error}`+ : error,+ message,+ );+ }+ if (message.type !== "extension_ui_request") {+ return null;+ }+ const dialog = readPiExtensionDialog(message);+ if (dialog) {+ return dialogRequest(message, dialog);+ }+ if (message.method === "notify") {+ const text = optionalString(message.message);+ if (!text) {+ return null;+ }+ const level = optionalString(message.notifyType) ?? "info";+ return level === "warning" || level === "error"+ ? extensionNotice(text, message)+ : {+ method: POSTHOG_NOTIFICATIONS.CONSOLE,+ params: withPiExtension({ message: text, level }, message),+ };+ }+ return {+ method: PI_EXTENSION_EVENT_METHOD,+ params: withPiExtension({}, message),+ };+}++export function piExtensionDialogResponse(+ dialog: PiExtensionDialog,+ answer: PermissionAnswer,+): RpcExtensionUIResponse {+ if (answer.optionId === CANCEL_OPTION_ID) {+ return { type: "extension_ui_response", id: dialog.id, cancelled: true };+ }+ if (dialog.method === "confirm") {+ return {+ type: "extension_ui_response",+ id: dialog.id,+ confirmed: answer.optionId === CONFIRM_OPTION_ID,+ };+ }+ const index = Number(answer.optionId.replace(/^option_/, ""));+ const chosen = Number.isInteger(index) ? dialog.options[index] : undefined;+ return {+ type: "extension_ui_response",+ id: dialog.id,+ value:+ Object.values(answer.answers ?? {})[0] ??+ answer.customInput ??+ chosen ??+ "",+ };+}++function conversationNotification(+ event: unknown,+): AcpConversationNotification | null {+ if (!isRecord(event)) {+ return null;+ }+ const notification = agentConversationEventToAcpNotification(+ event as unknown as AgentConversationEvent,+ );+ const update = notification?.params.update;+ if (isRecord(update) && update.title === update.name) {+ delete update.title;+ }+ return notification;+}++function entryNotification(+ entry: Record<string, unknown>,+): AcpConversationNotification | null | undefined {+ switch (entry.type) {+ case "pi_event":+ return conversationNotification(entry.event);+ case "pi_run_started":+ return {+ method: POSTHOG_NOTIFICATIONS.RUN_STARTED,+ params: {+ ...(typeof entry.runId === "string" ? { runId: entry.runId } : {}),+ ...(typeof entry.taskId === "string" ? { taskId: entry.taskId } : {}),+ },+ };+ case "pi_extension_event":+ return isRecord(entry.notification) && isRecord(entry.notification.params)+ ? piExtensionAcpNotification(entry.notification.params)+ : null;+ case "extension_ui_request":+ case "extension_ui_response":+ case "extension_error":+ return piExtensionAcpNotification(entry);+ default:+ return undefined;+ }+}++export function piAcpWireEntry(source: object): StoredLogEntry | null {+ const entry = source as Record<string, unknown>;+ const notification = entryNotification(entry);+ if (notification === undefined) {+ return source as StoredLogEntry;+ }+ if (!notification) {+ return null;+ }+ return {+ type: "notification",+ timestamp:+ typeof entry.timestamp === "string"+ ? entry.timestamp+ : new Date().toISOString(),+ ...(typeof entry.id === "string" ? { id: entry.id } : {}),+ ...(typeof entry.event_id === "string" ? { event_id: entry.event_id } : {}),+ ...(Array.isArray(entry.covered_event_ids)+ ? { covered_event_ids: entry.covered_event_ids as string[] }+ : {}),+ notification: { jsonrpc: "2.0", ...notification },+ } as StoredLogEntry;+}++function assistantChunkText(entry: Record<string, unknown>): string | null {+ if (+ entry.type !== "pi_event" ||+ !isRecord(entry.event) ||+ entry.event.type !== "assistant_message_chunk"+ ) {+ return null;+ }+ const content = entry.event.content;+ return isRecord(content) &&+ content.type === "text" &&+ typeof content.text === "string"+ ? content.text+ : null;+}++function agentMessageEntry(chunks: Record<string, unknown>[]): StoredLogEntry {+ const first = chunks[0];+ const last = chunks[chunks.length - 1];+ return {+ type: "notification",+ timestamp:+ typeof first.timestamp === "string"+ ? first.timestamp+ : new Date().toISOString(),+ ...(typeof first.id === "string" ? { id: first.id } : {}),+ ...(typeof last.event_id === "string" ? { event_id: last.event_id } : {}),+ ...(typeof first.event_id === "string"+ ? { first_event_id: first.event_id }+ : {}),+ notification: {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "agent_message",+ content: {+ type: "text",+ text: chunks.map((chunk) => assistantChunkText(chunk)).join(""),+ },+ },+ },+ },+ } as StoredLogEntry;+}++export function piAcpLogEntries<T extends object>(+ entries: T[],+ { final }: { final: boolean },+): { wire: StoredLogEntry[]; carry: T[] } {+ const wire: StoredLogEntry[] = [];+ let chunks: T[] = [];+ for (const entry of entries) {+ if (assistantChunkText(entry as Record<string, unknown>) !== null) {+ chunks.push(entry);+ continue;+ }+ if (chunks.length > 0) {+ wire.push(agentMessageEntry(chunks as Record<string, unknown>[]));+ chunks = [];+ }+ const converted = piAcpWireEntry(entry);+ if (converted) {+ wire.push(converted);+ }+ }+ if (final && chunks.length > 0) {+ wire.push(agentMessageEntry(chunks as Record<string, unknown>[]));+ chunks = [];+ }+ return { wire, carry: chunks };+}diff --git a/packages/agent/packages/agent/src/pi/conversation/translatePiConversation.test.ts b/packages/agent/packages/agent/src/pi/conversation/translatePiConversation.test.tsindex fe4fb66da214..069fc5ae5d4f 100644--- a/packages/agent/packages/agent/src/pi/conversation/translatePiConversation.test.ts+++ b/packages/agent/packages/agent/src/pi/conversation/translatePiConversation.test.ts@@ -911,6 +911,7 @@ describe("createPiConversationTranslator", () => {kind: "execute",status: "pending",rawInput: { command: "pwd" },+ _meta: { posthog: { toolName: "Bash" } },},},],diff --git a/packages/agent/packages/agent/src/pi/runtime.test.ts b/packages/agent/packages/agent/src/pi/runtime.test.tsindex 75ee50e2d0ba..05f95bd26277 100644--- a/packages/agent/packages/agent/src/pi/runtime.test.ts+++ b/packages/agent/packages/agent/src/pi/runtime.test.ts@@ -245,6 +245,43 @@ describe("PiRuntime", () => {);});+ it("shows the conversation content a user message was sent with, not the prompt", async () => {+ const { client, emit, send } = createClient();+ const runtime = new PiRuntime(client);+ const conversationListener = vi.fn();+ runtime.onConversationEvent(conversationListener);+ const prompt =+ "Read this\n\nAttached files:\n- /work/.posthog/attachments/run/a/notes.txt";+ const conversationContent = [+ { type: "text" as const, text: "Read this" },+ {+ type: "resource_link" as const,+ uri: "file:///work/.posthog/attachments/run/a/notes.txt",+ name: "notes.txt",+ },+ ];+ send.mockImplementation(async () => {+ emit({+ type: "message_end",+ message: { role: "user", content: prompt, timestamp: 1 },+ });+ return { type: "response", command: "prompt", success: true };+ });++ await runtime.sendCommand(+ { id: "message-1", type: "prompt", message: prompt },+ { conversationContent },+ );++ expect(conversationListener).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "user_message",+ id: "message-1",+ content: conversationContent,+ }),+ );+ });+it("does not apply an extension command id to a later user message", async () => {const { client, emit, send } = createClient();const runtime = new PiRuntime(client);diff --git a/packages/agent/packages/agent/src/pi/runtime.ts b/packages/agent/packages/agent/src/pi/runtime.tsindex 6f422dda28f3..92d1a6e99506 100644--- a/packages/agent/packages/agent/src/pi/runtime.ts+++ b/packages/agent/packages/agent/src/pi/runtime.ts@@ -3,7 +3,10 @@ import type {RpcCommand,RpcResponse,} from "@earendil-works/pi-coding-agent";-import type { AgentConversationEvent } from "@posthog/agent-contracts";+import type {+ AgentContent,+ AgentConversationEvent,+} from "@posthog/agent-contracts";import {createPiConversationTranslator,type PiConversationTranslator,@@ -30,6 +33,7 @@ export class PiRuntime {id: string;message: string;type: "prompt" | "steer" | "follow_up";+ conversationContent?: AgentContent[];}> = [];private directBashActive = false;@@ -67,7 +71,15 @@ export class PiRuntime {return () => this.extensionListeners.delete(listener);}- async sendCommand(command: RpcCommand): Promise<RpcResponse> {+ /**+ * `conversationContent` is what the conversation shows for a user message instead of the prompt+ * Pi echoes back: the user's own text plus a `resource_link` per attachment, where the prompt+ * carries the attachment paths as text for the model.+ */+ async sendCommand(+ command: RpcCommand,+ options?: { conversationContent?: AgentContent[] },+ ): Promise<RpcResponse> {const isUserMessage =command.type === "prompt" ||command.type === "steer" ||@@ -77,6 +89,7 @@ export class PiRuntime {id: command.id,message: command.message,type: command.type,+ conversationContent: options?.conversationContent,});}if (command.type !== "bash") {@@ -168,6 +181,9 @@ export class PiRuntime {if (pendingIndex >= 0) {const [pending] = this.pendingUserMessages.splice(pendingIndex, 1);conversationEvent.id = pending.id;+ if (pending.conversationContent) {+ conversationEvent.content = pending.conversationContent;+ }}}}diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.tsindex 5b0a56120796..1c08c351b116 100644--- a/packages/agent/packages/agent/src/server/agent-server.ts+++ b/packages/agent/packages/agent/src/server/agent-server.ts@@ -1,6 +1,6 @@import { createHash } from "node:crypto";import { access, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";-import { basename, dirname, isAbsolute, join, relative } from "node:path";+import { dirname, isAbsolute, join, relative } from "node:path";import { pathToFileURL } from "node:url";import type {ContentBlock,@@ -130,6 +130,7 @@ import type {TaskRunStateField,} from "../types";import { resourceLink } from "../utils/acp-content";+import { attachmentFilePath, safeArtifactFileName } from "../utils/attachments";import { withTimeout } from "../utils/common";import { createEventIdSource } from "../utils/event-id";import { Logger } from "../utils/logger";@@ -4113,7 +4114,7 @@ export class AgentServer {throw new Error(`Skill bundle ${skillName} failed checksum validation`);}- const safeSkillName = this.getSafeArtifactName(skillName);+ const safeSkillName = safeArtifactFileName(skillName);const skillRoot = join(this.config.repositoryPath ?? "/tmp/workspace",".posthog",@@ -4245,17 +4246,12 @@ export class AgentServer {throw new Error(`Failed to download artifact ${artifact.name}`);}- const safeName = this.getSafeArtifactName(artifact.name);- const artifactDir = join(- this.config.repositoryPath ?? "/tmp/workspace",- ".posthog",- "attachments",+ const artifactPath = attachmentFilePath(+ this.config.repositoryPath,runId,- artifact.id ?? safeName,+ artifact,);- await mkdir(artifactDir, { recursive: true });-- const artifactPath = join(artifactDir, safeName);+ await mkdir(dirname(artifactPath), { recursive: true });await writeFile(artifactPath, Buffer.from(data));return resourceLink(pathToFileURL(artifactPath).toString(), artifact.name, {@@ -4264,15 +4260,6 @@ export class AgentServer {});}- private getSafeArtifactName(name: string): string {- const baseName = basename(name).trim();- const normalizedName = baseName.replace(/[^\w.-]/g, "_");- if (normalizedName.length === 0 || /^\.+$/.test(normalizedName)) {- return "attachment";- }- return normalizedName;- }-/*** Put the user's skills-store skills on disk as pointer stubs before the* harness session starts, so it lists them like any local skill. The taskdiff --git a/packages/agent/packages/agent/src/server/bin.ts b/packages/agent/packages/agent/src/server/bin.tsindex 54b7a182b542..f515366fa8bc 100644--- a/packages/agent/packages/agent/src/server/bin.ts+++ b/packages/agent/packages/agent/src/server/bin.ts@@ -78,6 +78,7 @@ const envSchema = z.object({.enum(["true", "false"]).transform((value) => value === "true").optional(),+ POSTHOG_PI_CONVERSATION_FORMAT: z.enum(["acp", "pi"]).optional(),// OTLP pair for shipping run metadata to PostHog Logs; telemetry stays off// unless both are set. The traces URL additionally enables APM spans.POSTHOG_AGENT_OTEL_LOGS_URL: z.url().optional(),@@ -312,6 +313,7 @@ programenv.POSTHOG_TASK_RUN_EVENT_INGEST_STREAM_WINDOW_MS,eventIngestKeepStreamOpen:env.POSTHOG_TASK_RUN_EVENT_INGEST_KEEP_STREAM_OPEN,+ piConversationFormat: env.POSTHOG_PI_CONVERSATION_FORMAT,otelLogsUrl: env.POSTHOG_AGENT_OTEL_LOGS_URL,otelLogsToken: env.POSTHOG_AGENT_OTEL_LOGS_TOKEN,otelTracesUrl: env.POSTHOG_AGENT_OTEL_TRACES_URL,diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.test.ts b/packages/agent/packages/agent/src/server/pi-agent-server.test.tsindex f5bf796c6a3b..3d7a79b7717f 100644--- a/packages/agent/packages/agent/src/server/pi-agent-server.test.ts+++ b/packages/agent/packages/agent/src/server/pi-agent-server.test.ts@@ -1,6 +1,7 @@import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";+import { pathToFileURL } from "node:url";import type { AgentConversationEvent } from "@posthog/agent-contracts";import { describe, expect, it, vi } from "vitest";import { PiAgentServer } from "./pi-agent-server";@@ -338,6 +339,295 @@ describe("PiAgentServer", () => {);});+ it("writes ACP notifications to the log when the run uses the ACP format", async () => {+ const appendTaskRunLog = vi.fn(+ async (_taskId: string, _runId: string, _entries: unknown[]) => ({}),+ );+ const server = new PiAgentServer(+ config({ piConversationFormat: "acp" }),+ ) as unknown as {+ posthogAPI: { appendTaskRunLog: typeof appendTaskRunLog };+ handleConversationEvent(event: Record<string, unknown>): void;+ logFlushQueue: Promise<void>;+ };+ server.posthogAPI.appendTaskRunLog = appendTaskRunLog;++ server.handleConversationEvent({+ type: "user_message",+ id: "message-1",+ timestamp: 1,+ content: [{ type: "text", text: "hello" }],+ });+ for (const text of ["po", "ng"]) {+ server.handleConversationEvent({+ type: "assistant_message_chunk",+ timestamp: 2,+ content: { type: "text", text },+ });+ }+ server.handleConversationEvent({+ type: "turn_completed",+ timestamp: 2,+ stopReason: "end_turn",+ usage: {+ inputTokens: 5,+ outputTokens: 1,+ cachedReadTokens: 0,+ cachedWriteTokens: 0,+ totalTokens: 6,+ contextTokens: 6,+ contextWindow: 200_000,+ },+ });+ await server.logFlushQueue;++ const entries = appendTaskRunLog.mock.calls.flatMap(+ ([, , entries]) => entries,+ );+ expect(entries[1]).toMatchObject({+ first_event_id: expect.any(String),+ event_id: expect.any(String),+ });+ const notifications = entries.map((entry) => {+ expect(entry).toMatchObject({ type: "notification" });+ return (entry as { notification: unknown }).notification;+ });+ expect(notifications).toEqual([+ {+ jsonrpc: "2.0",+ method: "_posthog/user_message",+ params: {+ content: [{ type: "text", text: "hello" }],+ messageId: "message-1",+ },+ },+ {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ update: {+ sessionUpdate: "agent_message",+ content: { type: "text", text: "pong" },+ },+ },+ },+ expect.objectContaining({+ method: "_posthog/turn_complete",+ params: expect.objectContaining({ stopReason: "end_turn" }),+ }),+ {+ jsonrpc: "2.0",+ method: "_posthog/usage_update",+ params: {+ used: {+ inputTokens: 5,+ outputTokens: 1,+ cachedReadTokens: 0,+ cachedWriteTokens: 0,+ },+ },+ },+ {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ update: { sessionUpdate: "usage_update", used: 6, size: 200_000 },+ },+ },+ ]);+ });++ it("answers an ACP-format MCP approval through permission_response", async () => {+ const appendTaskRunLog = vi.fn(+ async (_taskId: string, _runId: string, _entries: unknown[]) => ({}),+ );+ const approveMcpTool = vi.fn(async () => {});+ const respondMcpToolPermission = vi.fn();+ const server = new PiAgentServer(+ config({ piConversationFormat: "acp" }),+ ) as unknown as {+ posthogAPI: {+ appendTaskRunLog: typeof appendTaskRunLog;+ approveMcpTool: typeof approveMcpTool;+ };+ session: unknown;+ pendingEvents: Record<string, unknown>[];+ handleMcpToolPermissionRequest(request: Record<string, unknown>): void;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ flushConversationLog(): Promise<void>;+ };+ server.posthogAPI.appendTaskRunLog = appendTaskRunLog;+ server.posthogAPI.approveMcpTool = approveMcpTool;+ server.session = { runtime: { client: { respondMcpToolPermission } } };++ server.handleMcpToolPermissionRequest({+ requestId: "request-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: { query: "workers" },+ });+ await server.executeCommand("permission_response", {+ requestId: "request-1",+ optionId: "allow_always",+ });+ await server.flushConversationLog();++ expect(server.pendingEvents[0]).toMatchObject({+ type: "permission_request",+ options: [+ { optionId: "allow", kind: "allow_once" },+ { optionId: "allow_always" },+ { optionId: "reject", _meta: { hint: expect.any(String) } },+ ],+ });+ expect(approveMcpTool).toHaveBeenCalledWith("installation-1", "search");+ expect(respondMcpToolPermission).toHaveBeenCalledWith(+ "request-1",+ "allow_always",+ );+ expect(+ appendTaskRunLog.mock.calls+ .flatMap(([, , entries]) => entries)+ .map(+ (entry) =>+ (entry as { notification: { method: string } }).notification.method,+ ),+ ).toEqual(["_posthog/permission_request", "_posthog/permission_resolved"]);+ });++ it("answers a Pi dialog through permission_response and closes it when it times out", async () => {+ vi.useFakeTimers();+ try {+ const appendTaskRunLog = vi.fn(+ async (_taskId: string, _runId: string, _entries: unknown[]) => ({}),+ );+ const respondToExtensionUI = vi.fn(async () => {});+ const server = new PiAgentServer(+ config({ piConversationFormat: "acp" }),+ ) as unknown as {+ posthogAPI: { appendTaskRunLog: typeof appendTaskRunLog };+ session: unknown;+ handleExtensionEvent(event: Record<string, unknown>): void;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ logFlushQueue: Promise<void>;+ };+ server.posthogAPI.appendTaskRunLog = appendTaskRunLog;+ server.session = { runtime: { client: { respondToExtensionUI } } };+ const select = {+ type: "extension_ui_request",+ id: "select-1",+ method: "select",+ title: "Pick one",+ options: ["A", "B"],+ };++ server.handleExtensionEvent(select);+ await server.executeCommand("permission_response", {+ requestId: "select-1",+ optionId: "option_1",+ });+ server.handleExtensionEvent({+ type: "extension_ui_request",+ id: "confirm-1",+ method: "confirm",+ title: "Push?",+ message: "To main",+ timeout: 1_000,+ });+ await vi.advanceTimersByTimeAsync(1_000);+ await server.logFlushQueue;++ expect(respondToExtensionUI).toHaveBeenCalledWith({+ type: "extension_ui_response",+ id: "select-1",+ value: "B",+ });+ await expect(+ server.executeCommand("permission_response", {+ requestId: "confirm-1",+ optionId: "confirm",+ }),+ ).rejects.toThrow("No pending permission request");+ const notifications = appendTaskRunLog.mock.calls+ .flatMap(([, , entries]) => entries)+ .map(+ (entry) =>+ (entry as { notification: { method: string; params: unknown } })+ .notification,+ );+ expect(notifications).toEqual([+ expect.objectContaining({+ method: "_posthog/permission_request",+ params: expect.objectContaining({+ requestId: "select-1",+ options: [+ expect.objectContaining({ optionId: "option_0", name: "A" }),+ expect.objectContaining({ optionId: "option_1", name: "B" }),+ ],+ _meta: { piExtension: expect.objectContaining(select) },+ }),+ }),+ expect.objectContaining({+ method: "_posthog/permission_resolved",+ params: expect.objectContaining({ requestId: "select-1" }),+ }),+ expect.objectContaining({+ method: "_posthog/permission_request",+ params: expect.objectContaining({ requestId: "confirm-1" }),+ }),+ expect.objectContaining({+ method: "_posthog/permission_resolved",+ params: expect.objectContaining({ requestId: "confirm-1" }),+ }),+ ]);+ } finally {+ vi.useRealTimers();+ }+ });++ it.each([+ {+ configId: "model",+ value: "claude-opus-5-5",+ command: {+ type: "set_model",+ provider: "posthog",+ modelId: "claude-opus-5-5",+ },+ },+ {+ configId: "effort",+ value: "high",+ command: { type: "set_thinking_level", level: "high" },+ },+ ])(+ "applies a $configId change from set_config_option to the Pi session",+ async ({ configId, value, command }) => {+ const sendCommand = vi.fn(async () => ({ success: true }));+ const server = new PiAgentServer(config()) as unknown as {+ session: unknown;+ executeCommand(+ method: string,+ params: Record<string, unknown>,+ ): Promise<unknown>;+ };+ server.session = {+ runtime: { sendCommand, client: { getState: vi.fn(async () => ({})) } },+ };++ await server.executeCommand("set_config_option", { configId, value });++ expect(sendCommand).toHaveBeenCalledWith(command);+ },+ );+it("bounds events retained while no SSE client is connected", () => {const server = new PiAgentServer(config()) as unknown as {broadcast(event: Record<string, unknown>): void;@@ -507,12 +797,10 @@ describe("PiAgentServer", () => {messageId: "message-1",});- expect(sendCommand).toHaveBeenCalledWith({- id: "message-1",- type: "prompt",- message: "hello",- images: [],- });+ expect(sendCommand).toHaveBeenCalledWith(+ { id: "message-1", type: "prompt", message: "hello", images: [] },+ { conversationContent: [{ type: "text", text: "hello" }] },+ );});it("preserves the native Pi user prompt when auto-publish is enabled", async () => {@@ -543,7 +831,10 @@ describe("PiAgentServer", () => {it("hydrates cloud artifacts into native Pi prompt inputs", async () => {const repositoryPath = await mkdtemp(join(tmpdir(), "pi-attachments-"));const sendCommand = vi.fn(- async (_command: Record<string, unknown>) => ({}),+ async (+ _command: Record<string, unknown>,+ _options?: Record<string, unknown>,+ ) => ({}),);const downloadArtifact = vi.fn()@@ -587,15 +878,20 @@ describe("PiAgentServer", () => {],});- const command = sendCommand.mock.calls[0][0];- const filePath = join(+ const [command, options] = sendCommand.mock.calls[0];+ const attachmentsDir = join(repositoryPath,".posthog","attachments",- "file-1-notes.txt",+ "run-1",+ );+ const notesPath = join(attachmentsDir, "file-1", "notes.txt");+ const imagePath = join(attachmentsDir, "image-1", "image.png");+ expect(command.message).toBe(+ `Read these\n\nAttached files:\n- ${notesPath}`,);- expect(command.message).toContain(filePath);- await expect(readFile(filePath, "utf8")).resolves.toBe("notes");+ await expect(readFile(notesPath, "utf8")).resolves.toBe("notes");+ await expect(readFile(imagePath, "utf8")).resolves.toBe("image");expect(command.images).toEqual([{type: "image",@@ -604,14 +900,34 @@ describe("PiAgentServer", () => {fileName: "image.png",},]);+ expect(options).toEqual({+ conversationContent: [+ { type: "text", text: "Read these" },+ {+ type: "resource_link",+ uri: pathToFileURL(notesPath).toString(),+ name: "notes.txt",+ mimeType: "text/plain",+ },+ {+ type: "resource_link",+ uri: pathToFileURL(imagePath).toString(),+ name: "image.png",+ mimeType: "image/png",+ },+ ],+ });await rm(repositoryPath, { recursive: true });});it("steers the streaming run in place instead of aborting it", async () => {- const sendCommand = vi.fn(async (_command: Record<string, unknown>) => ({- success: true,- }));+ const sendCommand = vi.fn(+ async (+ _command: Record<string, unknown>,+ _options?: Record<string, unknown>,+ ) => ({ success: true }),+ );const order: string[] = [];const abort = vi.fn(async () => {order.push("abort");@@ -629,10 +945,15 @@ describe("PiAgentServer", () => {getState: vi.fn(async () => ({ isStreaming: true })),abort,},- sendCommand: vi.fn(async (command: Record<string, unknown>) => {- order.push("sendCommand");- return sendCommand(command);- }),+ sendCommand: vi.fn(+ async (+ command: Record<string, unknown>,+ options: Record<string, unknown>,+ ) => {+ order.push("sendCommand");+ return sendCommand(command, options);+ },+ ),},};@@ -646,12 +967,17 @@ describe("PiAgentServer", () => {expect(order).toEqual(["sendCommand"]);expect(abort).not.toHaveBeenCalled();expect(sendCommand).toHaveBeenCalledTimes(1);- expect(sendCommand).toHaveBeenCalledWith({- id: "message-1",- type: "steer",- message: "stop, do this instead",- images: [],- });+ expect(sendCommand).toHaveBeenCalledWith(+ {+ id: "message-1",+ type: "steer",+ message: "stop, do this instead",+ images: [],+ },+ {+ conversationContent: [{ type: "text", text: "stop, do this instead" }],+ },+ );});it("queues a steer that pi refuses while the run is still streaming", async () => {@@ -684,12 +1010,17 @@ describe("PiAgentServer", () => {steer: true,});- expect(sendCommand).toHaveBeenLastCalledWith({- id: "message-3",- type: "follow_up",- message: "stop, do this instead",- images: [],- });+ expect(sendCommand).toHaveBeenLastCalledWith(+ {+ id: "message-3",+ type: "follow_up",+ message: "stop, do this instead",+ images: [],+ },+ {+ conversationContent: [{ type: "text", text: "stop, do this instead" }],+ },+ );expect(result).toMatchObject({ success: true });expect(result).not.toHaveProperty("steered");});@@ -732,12 +1063,17 @@ describe("PiAgentServer", () => {});expect(sendCommand).toHaveBeenCalledTimes(1);- expect(sendCommand).toHaveBeenCalledWith({- id: "message-4",- type: "steer",- message: "stop, do this instead",- images: [],- });+ expect(sendCommand).toHaveBeenCalledWith(+ {+ id: "message-4",+ type: "steer",+ message: "stop, do this instead",+ images: [],+ },+ {+ conversationContent: [{ type: "text", text: "stop, do this instead" }],+ },+ );expect(result).toMatchObject({success: false,steered: false,@@ -774,12 +1110,17 @@ describe("PiAgentServer", () => {});expect(abort).not.toHaveBeenCalled();- expect(sendCommand).toHaveBeenCalledWith({- id: "message-5",- type: "prompt",- message: "stop, do this instead",- images: [],- });+ expect(sendCommand).toHaveBeenCalledWith(+ {+ id: "message-5",+ type: "prompt",+ message: "stop, do this instead",+ images: [],+ },+ {+ conversationContent: [{ type: "text", text: "stop, do this instead" }],+ },+ );expect(result).not.toHaveProperty("steered");});@@ -812,12 +1153,19 @@ describe("PiAgentServer", () => {expect(result).not.toHaveProperty("steered");expect(abort).not.toHaveBeenCalled();- expect(sendCommand).toHaveBeenCalledWith({- id: "message-2",- type: "follow_up",- message: "when you are done, also update the docs",- images: [],- });+ expect(sendCommand).toHaveBeenCalledWith(+ {+ id: "message-2",+ type: "follow_up",+ message: "when you are done, also update the docs",+ images: [],+ },+ {+ conversationContent: [+ { type: "text", text: "when you are done, also update the docs" },+ ],+ },+ );});it("allows a failed user-message delivery to be retried", async () => {diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.tsindex c1a9f97db0d1..80a928871ff4 100644--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts@@ -1,10 +1,12 @@import { randomUUID } from "node:crypto";import { access, mkdir, readFile, writeFile } from "node:fs/promises";-import { basename, dirname, join } from "node:path";+import { dirname, join } from "node:path";+import { pathToFileURL } from "node:url";import type { RpcSessionState } from "@earendil-works/pi-coding-agent";import type { ServerType } from "@hono/node-server";import { serve } from "@hono/node-server";import {+ type AgentContent,type AgentConversationEvent,type AgentTurnUsage,MCP_TOOL_PERMISSION_OPTIONS,@@ -30,6 +32,15 @@ import packageJson from "../../package.json" with { type: "json" };import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";import { buildLocalToolsServer } from "../adapters/codex-app-server/local-tools-mcp";import { OtelRunTelemetry } from "../otel-telemetry";+import {+ type PermissionAnswer,+ PI_ACP_MCP_PERMISSION_OPTIONS,+ type PiExtensionDialog,+ piAcpLogEntries,+ piAcpWireEntry,+ piExtensionDialogResponse,+ readPiExtensionDialog,+} from "../pi/acp-wire";import {createPiRpcClient,createRuntimeMcpServers,@@ -41,10 +52,12 @@ import { piRpcCommandSchema, type RpcCommand } from "../pi/rpc-transport";import { PiRuntime } from "../pi/runtime";import {type PiExtensionEvent,+ type PiThinkingLevel,piExtensionUIResponseSchema,type RpcExtensionUIResponse,} from "../pi/types";import { PostHogAPIClient } from "../posthog-api";+import { attachmentFilePath } from "../utils/attachments";import { createEventIdSource } from "../utils/event-id";import { resolveLlmGatewayUrl } from "../utils/gateway";import { Logger } from "../utils/logger";@@ -60,6 +73,14 @@ const MODEL_CHANGING_RPC_COMMANDS: ReadonlySet<string> = new Set(["cycle_model",]);+interface PiPreparedUserMessage {+ /** The text Pi receives, with attachment paths appended for the model. */+ prompt: string;+ images: Parameters<PiRpcClient["prompt"]>[1];+ /** What the conversation shows: the user's text and one `resource_link` per attachment. */+ content: AgentContent[];+}+interface SseController {send(data: unknown): void;close(): void;@@ -97,11 +118,25 @@ const mcpPermissionResponseCommandSchema = z.object({decision: z.enum(["allow", "allow_always", "reject"]),});+const permissionResponseCommandSchema = z.object({+ requestId: z.string().min(1),+ optionId: z.string().min(1),+ customInput: z.string().optional(),+ answers: z.record(z.string(), z.string()).optional(),+});++const setConfigOptionCommandSchema = z.object({+ configId: z.enum(["model", "effort"]),+ value: z.string().min(1),+});+const commandSchemas = {user_message: userMessageCommandSchema,cancel: emptySchema,queue_get: emptySchema,queue_clear: emptySchema,+ permission_response: permissionResponseCommandSchema,+ set_config_option: setConfigOptionCommandSchema,"pi/rpc": z.object({ command: piRpcCommandSchema }),} as const;@@ -154,11 +189,16 @@ export class PiAgentServer {private logFlushQueue: Promise<void> = Promise.resolve();private logFlushActive = false;private logFlushRequested = false;+ private logFlushFinalRequested = false;private readonly canceledSseControllers = new WeakSet<SseController>();private readonly pendingMcpPermissions = new Map<string,McpToolPermissionRequest>();+ private readonly pendingExtensionDialogs = new Map<+ string,+ { dialog: PiExtensionDialog; timer?: ReturnType<typeof setTimeout> }+ >();private rtkSavingsAttempted = false;private runUsage = new RunUsageAccumulator();private modelContextWindow: number | null = null;@@ -190,6 +230,14 @@ export class PiAgentServer {return this.config.version ?? packageJson.version;}+ private get acpConversation(): boolean {+ return this.config.piConversationFormat === "acp";+ }++ private toWire(entry: object): object | null {+ return this.acpConversation ? piAcpWireEntry(entry) : entry;+ }+private createRunTelemetry(payload: JwtPayload,): OtelRunTelemetry | undefined {@@ -275,7 +323,11 @@ export class PiAgentServer {this.session = null;this.runUsage = new RunUsageAccumulator();this.pendingMcpPermissions.clear();- await this.flushConversationLog().catch((error) =>+ for (const { timer } of this.pendingExtensionDialogs.values()) {+ clearTimeout(timer);+ }+ this.pendingExtensionDialogs.clear();+ await this.flushConversationLog({ final: true }).catch((error) =>this.logger.error("Failed to persist Pi events during shutdown", error),);await this.emitRtkSavings();@@ -305,7 +357,7 @@ export class PiAgentServer {await this.syncTaskSession().catch((syncError) =>this.logger.error("Failed to sync crashed Pi session", syncError),);- await this.flushConversationLog().catch((syncError) =>+ await this.flushConversationLog({ final: true }).catch((syncError) =>this.logger.error("Failed to persist crashed Pi events", syncError),);await this.posthogAPI@@ -767,6 +819,62 @@ export class PiAgentServer {this.recordTurnUsage(event.usage);}this.handleEvent(event);+ if (+ this.acpConversation &&+ event.type === "turn_completed" &&+ event.usage+ ) {+ this.broadcastUsage(event.usage);+ }+ }++ private broadcastUsage(usage: AgentTurnUsage): void {+ const totals = this.runUsage.snapshot();+ this.broadcastNotification(POSTHOG_NOTIFICATIONS.USAGE_UPDATE, {+ used: {+ inputTokens: totals.input_tokens,+ outputTokens: totals.output_tokens,+ cachedReadTokens: totals.cache_read_tokens,+ cachedWriteTokens: totals.cache_write_tokens,+ },+ });+ if (typeof usage.contextTokens === "number") {+ this.broadcastNotification("session/update", {+ update: {+ sessionUpdate: "usage_update",+ used: usage.contextTokens,+ ...(typeof usage.contextWindow === "number"+ ? { size: usage.contextWindow }+ : {}),+ },+ });+ }+ }++ private broadcastNotification(+ method: string,+ params: Record<string, unknown>,+ ): void {+ this.broadcast({+ type: "notification",+ timestamp: new Date().toISOString(),+ notification: { jsonrpc: "2.0", method, params },+ });+ }++ private persistNotification(+ method: string,+ params: Record<string, unknown>,+ ): void {+ this.pendingLogEntries.push({+ type: "notification",+ timestamp: new Date().toISOString(),+ event_id: this.nextEventId(),+ notification: { method, params },+ });+ void this.flushConversationLog().catch((error) =>+ this.logger.error("Failed to persist Pi notification", error),+ );}private recordTurnUsage(usage: AgentTurnUsage): void {@@ -796,9 +904,35 @@ export class PiAgentServer {}private handleExtensionEvent(event: PiExtensionEvent): void {+ const dialog = this.acpConversation+ ? readPiExtensionDialog(event as unknown as Record<string, unknown>)+ : null;+ if (dialog) {+ this.pendingExtensionDialogs.set(dialog.id, {+ dialog,+ timer: dialog.timeout+ ? setTimeout(+ () => this.expireExtensionDialog(dialog.id),+ dialog.timeout,+ )+ : undefined,+ });+ }this.broadcast({ ...event });}+ private expireExtensionDialog(id: string): void {+ if (!this.pendingExtensionDialogs.delete(id)) {+ return;+ }+ this.broadcast({+ type: "extension_ui_response",+ id,+ cancelled: true,+ timestamp: new Date().toISOString(),+ });+ }+private async respondExtensionUI(response: RpcExtensionUIResponse,): Promise<{ resolved: true }> {@@ -806,6 +940,8 @@ export class PiAgentServer {if (!runtime) {throw new Error("No active Pi runtime");}+ clearTimeout(this.pendingExtensionDialogs.get(response.id)?.timer);+ this.pendingExtensionDialogs.delete(response.id);await runtime.client.respondToExtensionUI(response);this.broadcast({ ...response });return { resolved: true };@@ -838,8 +974,27 @@ export class PiAgentServer {mcpInstallationId: request.installationId,}),},- options: MCP_TOOL_PERMISSION_OPTIONS,+ options: this.acpConversation+ ? PI_ACP_MCP_PERMISSION_OPTIONS+ : MCP_TOOL_PERMISSION_OPTIONS,});+ if (this.acpConversation) {+ this.persistNotification(POSTHOG_NOTIFICATIONS.PERMISSION_REQUEST, {+ requestId: request.requestId,+ toolCall: {+ toolCallId: request.requestId,+ title: `The agent wants to call ${request.toolName} (${request.serverName})`,+ kind: "other",+ rawInput: request.arguments,+ _meta: posthogToolMeta({+ toolName: mcpToolKey(mcp),+ mcp,+ mcpInstallationId: request.installationId,+ }),+ },+ options: PI_ACP_MCP_PERMISSION_OPTIONS,+ });+ }}private async respondMcpToolPermission(@@ -858,6 +1013,13 @@ export class PiAgentServer {}this.pendingMcpPermissions.delete(requestId);this.session?.runtime.client.respondMcpToolPermission(requestId, decision);+ if (this.acpConversation) {+ this.broadcastNotification(POSTHOG_NOTIFICATIONS.PERMISSION_RESOLVED, {+ requestId,+ toolCallId: requestId,+ optionId: decision,+ });+ }return { resolved: true };}@@ -882,6 +1044,15 @@ export class PiAgentServer {runtime.clearPendingQueuedUserMessages();return queue;}+ case "permission_response":+ return this.respondPermission(+ params as unknown as PermissionAnswer & { requestId: string },+ );+ case "set_config_option":+ return this.setConfigOption(+ params.configId as "model" | "effort",+ params.value as string,+ );case "pi/rpc": {const command = params.command as RpcCommand;if (@@ -906,6 +1077,54 @@ export class PiAgentServer {}}+ private async respondPermission(+ answer: PermissionAnswer & { requestId: string },+ ): Promise<{ resolved: true }> {+ if (this.pendingMcpPermissions.has(answer.requestId)) {+ const decision =+ mcpPermissionResponseCommandSchema.shape.decision.safeParse(+ answer.optionId,+ );+ if (!decision.success) {+ throw new Error(+ `Option "${answer.optionId}" was not offered for permission request ${answer.requestId}`,+ );+ }+ return this.respondMcpToolPermission(answer.requestId, decision.data);+ }+ const pending = this.pendingExtensionDialogs.get(answer.requestId);+ if (!pending) {+ throw new Error(+ `No pending permission request found for id: ${answer.requestId}`,+ );+ }+ return this.respondExtensionUI(+ piExtensionDialogResponse(pending.dialog, answer),+ );+ }++ private async setConfigOption(+ configId: "model" | "effort",+ value: string,+ ): Promise<Record<string, never>> {+ const runtime = this.session?.runtime;+ if (!runtime) {+ throw new Error("No active Pi runtime");+ }+ const response = await runtime.sendCommand(+ configId === "model"+ ? { type: "set_model", provider: "posthog", modelId: value }+ : { type: "set_thinking_level", level: value as PiThinkingLevel },+ );+ if (!response.success) {+ throw new Error(response.error || `Pi rejected the ${configId} change`);+ }+ if (configId === "model") {+ await this.refreshModelContextWindow(runtime.client);+ }+ return {};+ }+private applyModelContextWindow(state: RpcSessionState): void {this.modelContextWindow =typeof state.model?.contextWindow === "number"@@ -934,28 +1153,25 @@ export class PiAgentServer {);const result = await this.dispatchUserMessage(runtime,- message.content,- message.images,+ message,typeof params.messageId === "string" ? params.messageId : randomUUID(),params.steer === true,);return result;}+ /**+ * Every attachment is written to the shared `.posthog/attachments` layout and shows in the+ * conversation as a `resource_link`. The model gets the files as paths in the prompt text, and+ * images inline as well, since Pi reads images natively.+ */private async prepareUserMessage(content: string,artifacts: TaskRunArtifact[],- ): Promise<{- content: string;- images: Parameters<PiRpcClient["prompt"]>[1];- }> {+ ): Promise<PiPreparedUserMessage> {const images: NonNullable<Parameters<PiRpcClient["prompt"]>[1]> = [];const filePaths: string[] = [];- const attachmentDirectory = join(- this.config.repositoryPath ?? "/tmp/workspace",- ".posthog",- "attachments",- );+ const attachments: AgentContent[] = [];for (const artifact of artifacts) {if (!artifact.storage_path) {@@ -970,6 +1186,21 @@ export class PiAgentServer {throw new Error(`Failed to download attachment: ${artifact.name}`);}+ const filePath = attachmentFilePath(+ this.config.repositoryPath,+ this.config.runId,+ artifact,+ );+ await mkdir(dirname(filePath), { recursive: true });+ await writeFile(filePath, Buffer.from(data));+ attachments.push({+ type: "resource_link",+ uri: pathToFileURL(filePath).toString(),+ name: artifact.name,+ ...(artifact.content_type ? { mimeType: artifact.content_type } : {}),+ ...(typeof artifact.size === "number" ? { size: artifact.size } : {}),+ });+const mimeType = artifact.content_type ?? "application/octet-stream";if (mimeType.startsWith("image/")) {images.push({@@ -978,34 +1209,35 @@ export class PiAgentServer {mimeType,fileName: artifact.name,} as (typeof images)[number]);- continue;+ } else {+ filePaths.push(filePath);}-- await mkdir(attachmentDirectory, { recursive: true });- const fileName = `${artifact.id}-${basename(artifact.name)}`;- const filePath = join(attachmentDirectory, fileName);- await writeFile(filePath, Buffer.from(data));- filePaths.push(filePath);}const attachmentText = filePaths.length? `Attached files:\n${filePaths.map((filePath) => `- ${filePath}`).join("\n")}`: "";return {- content: [content, attachmentText].filter(Boolean).join("\n\n"),+ prompt: [content, attachmentText].filter(Boolean).join("\n\n"),images,+ content: [+ ...(content ? [{ type: "text" as const, text: content }] : []),+ ...attachments,+ ],};}private async dispatchUserMessage(runtime: PiRuntime,- content: string,- images: Parameters<PiRpcClient["prompt"]>[1],+ message: PiPreparedUserMessage,id: string,steer: boolean,): Promise<unknown> {const send = (type: "prompt" | "follow_up" | "steer") =>- runtime.sendCommand({ id, type, message: content, images });+ runtime.sendCommand(+ { id, type, message: message.prompt, images: message.images },+ { conversationContent: message.content },+ );const state = await runtime.client.getState();if (!state.isStreaming) {return send("prompt");@@ -1043,7 +1275,10 @@ export class PiAgentServer {}private async persistSettledTurn(): Promise<void> {- await Promise.all([this.syncTaskSession(), this.flushConversationLog()]);+ await Promise.all([+ this.syncTaskSession(),+ this.flushConversationLog({ final: true }),+ ]);}private syncTaskSession(): Promise<void> {@@ -1095,32 +1330,37 @@ export class PiAgentServer {const isExtensionMessage =event.type === "extension_ui_request" ||event.type === "extension_ui_response";- if (isConversationEvent || isExtensionMessage) {- const logEntry: StoredLogEntry = isExtensionMessage- ? {- id: typeof event.id === "string" ? event.id : undefined,- type: "pi_extension_event",- timestamp:- typeof event.timestamp === "string"- ? event.timestamp- : new Date().toISOString(),- notification: {- method: "_posthog/pi_extension_event",- params: event,- },- event_id: eventId,- }- : {- id: typeof event.id === "string" ? event.id : undefined,- type: String(event.type),- timestamp:- typeof event.timestamp === "string" ? event.timestamp : undefined,- event:- event.type === "pi_event"- ? (event.event as AgentConversationEvent)- : undefined,- event_id: eventId,- };+ const isNotification = event.type === "notification";+ if (isConversationEvent || isExtensionMessage || isNotification) {+ const logEntry: StoredLogEntry = isNotification+ ? (event as unknown as StoredLogEntry)+ : isExtensionMessage+ ? {+ id: typeof event.id === "string" ? event.id : undefined,+ type: "pi_extension_event",+ timestamp:+ typeof event.timestamp === "string"+ ? event.timestamp+ : new Date().toISOString(),+ notification: {+ method: "_posthog/pi_extension_event",+ params: event,+ },+ event_id: eventId,+ }+ : {+ id: typeof event.id === "string" ? event.id : undefined,+ type: String(event.type),+ timestamp:+ typeof event.timestamp === "string"+ ? event.timestamp+ : undefined,+ event:+ event.type === "pi_event"+ ? (event.event as AgentConversationEvent)+ : undefined,+ event_id: eventId,+ };const toolCallId = updatedToolCallId(logEntry.event);const pendingLogIndex = toolCallId? this.pendingLogEntries.findLastIndex(@@ -1155,6 +1395,7 @@ export class PiAgentServer {if (event.type === "pi_run_started" ||isExtensionMessage ||+ isNotification ||this.pendingLogEntries.length >= LOG_FLUSH_ENTRY_COUNT ||(event.event as { type?: string } | undefined)?.type ==="turn_completed"@@ -1165,9 +1406,14 @@ export class PiAgentServer {}}- this.eventStreamSender?.enqueue(event);+ const streamEvent = this.toWire(event);+ if (streamEvent) {+ this.eventStreamSender?.enqueue(streamEvent as Record<string, unknown>);+ }if (this.session?.sseController) {- this.session.sseController.send(event);+ if (streamEvent) {+ this.session.sseController.send(streamEvent);+ }} else {const toolCallId = updatedToolCallId(event.type === "pi_event"@@ -1215,7 +1461,14 @@ export class PiAgentServer {}}- private flushConversationLog(): Promise<void> {+ private flushConversationLog({+ final = false,+ }: {+ final?: boolean;+ } = {}): Promise<void> {+ if (final) {+ this.logFlushFinalRequested = true;+ }if (this.logFlushActive) {this.logFlushRequested = true;return this.logFlushQueue;@@ -1228,23 +1481,34 @@ export class PiAgentServer {const flush = (async () => {do {this.logFlushRequested = false;+ const final = this.logFlushFinalRequested;+ this.logFlushFinalRequested = false;const entries = this.pendingLogEntries;this.pendingLogEntries = [];if (entries.length === 0) {return;}- try {- await this.posthogAPI.appendTaskRunLog(- this.config.taskId,- this.config.runId,- entries,- );- } catch (error) {- this.pendingLogEntries = [- ...entries,- ...this.pendingLogEntries,- ].slice(-MAX_PENDING_LOG_ENTRIES);- throw error;+ const { wire, carry } = this.acpConversation+ ? piAcpLogEntries(entries, { final })+ : { wire: entries, carry: [] };+ if (wire.length > 0) {+ try {+ await this.posthogAPI.appendTaskRunLog(+ this.config.taskId,+ this.config.runId,+ wire,+ );+ } catch (error) {+ this.pendingLogEntries = [+ ...entries,+ ...this.pendingLogEntries,+ ].slice(-MAX_PENDING_LOG_ENTRIES);+ throw error;+ }+ }+ this.pendingLogEntries = [...carry, ...this.pendingLogEntries];+ if (wire.length === 0) {+ return;}} while (this.logFlushRequested ||@@ -1266,7 +1530,10 @@ export class PiAgentServer {const events = this.pendingEvents;this.pendingEvents = [];for (const event of events) {- controller.send(event);+ const streamEvent = this.toWire(event);+ if (streamEvent) {+ controller.send(streamEvent);+ }}}diff --git a/packages/agent/packages/agent/src/server/types.ts b/packages/agent/packages/agent/src/server/types.tsindex a34685f9a694..38ba874f9285 100644--- a/packages/agent/packages/agent/src/server/types.ts+++ b/packages/agent/packages/agent/src/server/types.ts@@ -28,6 +28,7 @@ export interface AgentServerConfig {eventIngestBaseUrl?: string;eventIngestStreamWindowMs?: number;eventIngestKeepStreamOpen?: boolean;+ piConversationFormat?: "acp" | "pi";/** Full OTLP logs URL for run telemetry, e.g. https://us.i.posthog.com/i/v1/logs */otelLogsUrl?: string;/** Project API key for the OTLP logs/traces endpoints */diff --git a/packages/agent/packages/agent/src/utils/attachments.ts b/packages/agent/packages/agent/src/utils/attachments.tsnew file mode 100644index 000000000000..0f9e53ad8a94--- /dev/null+++ b/packages/agent/packages/agent/src/utils/attachments.ts@@ -0,0 +1,32 @@+import { basename, join } from "node:path";++/** A file name safe to write under the repository, or `attachment` when nothing usable is left. */+export function safeArtifactFileName(name: string): string {+ const normalizedName = basename(name)+ .trim()+ .replace(/[^\w.-]/g, "_");+ if (normalizedName.length === 0 || /^\.+$/.test(normalizedName)) {+ return "attachment";+ }+ return normalizedName;+}++/**+ * Where a run's attachment lives on disk: `.posthog/attachments/<runId>/<artifactId>/<name>`.+ * Every harness writes this layout, and the clients read the run and artifact ids back out of it.+ */+export function attachmentFilePath(+ repositoryPath: string | undefined,+ runId: string,+ artifact: { id?: string; name: string },+): string {+ const safeName = safeArtifactFileName(artifact.name);+ return join(+ repositoryPath ?? "/tmp/workspace",+ ".posthog",+ "attachments",+ runId,+ artifact.id ?? safeName,+ safeName,+ );+}diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.tsindex f5c63125d41c..d724ca4e744b 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts@@ -2,8 +2,10 @@ import type { TaskService } from "@posthog/core/task-detail/taskService";import type { RootLogger } from "@posthog/di/logger";import {type AgentConversationEvent,+ agentConversationEventToAcpNotification,mcpToolKey,posthogToolMeta,+ type StoredLogEntry,} from "@posthog/shared";import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";import { describe, expect, it, vi } from "vitest";@@ -102,6 +104,34 @@ const snapshotEvent: AgentConversationEvent = {content: { type: "text", text: "durable response" },};+function acpEntry(event: AgentConversationEvent): StoredLogEntry {+ return {+ type: "notification",+ timestamp: new Date(event.timestamp).toISOString(),+ notification: agentConversationEventToAcpNotification(event) ?? undefined,+ };+}++function piExtensionEntry(message: Record<string, unknown>): StoredLogEntry {+ return {+ type: "pi_extension_event",+ notification: { method: "_posthog/pi_extension_event", params: message },+ };+}++function acpExtensionEntry(message: Record<string, unknown>): StoredLogEntry {+ return {+ type: "notification",+ notification: {+ method:+ message.type === "extension_ui_response"+ ? "_posthog/permission_resolved"+ : "_posthog/permission_request",+ params: { requestId: message.id, _meta: { piExtension: message } },+ },+ };+}+describe("CloudPiSessionClient", () => {it("relays Pi extension UI requests and responses through a cloud run", async () => {const cloud = createCloudTaskClient();@@ -173,70 +203,58 @@ describe("CloudPiSessionClient", () => {});});- it("restores only unresolved extension requests from a cloud snapshot", () => {- const cloud = createCloudTaskClient();- const session = new CloudPiSessionClient(- cloud.client,- context("in_progress"),- );- const onEvent = vi.fn();- session.onExtensionEvent(onEvent, vi.fn());-- const pendingRequest = {- type: "extension_ui_request",- id: "pending",- method: "confirm",- title: "Continue?",- message: "Proceed?",- };- const resolvedRequest = {- ...pendingRequest,- id: "resolved",- };- cloud.sendUpdate({- taskId: "task-1",- runId: "run-1",- kind: "snapshot",- status: "in_progress",- newEntries: [- {- type: "pi_extension_event",- notification: {- method: "_posthog/pi_extension_event",- params: pendingRequest,- },- },- {- type: "pi_extension_event",- notification: {- method: "_posthog/pi_extension_event",- params: resolvedRequest,- },- },- {- type: "pi_extension_event",- notification: {- method: "_posthog/pi_extension_event",- params: {- type: "extension_ui_response",- id: "resolved",- confirmed: true,- },- },- },- ],- totalEntryCount: 3,- });+ it.each([+ { format: "Pi", entry: piExtensionEntry },+ { format: "ACP", entry: acpExtensionEntry },+ ])(+ "restores only unresolved extension requests from a $format-format cloud snapshot",+ ({ entry }) => {+ const cloud = createCloudTaskClient();+ const session = new CloudPiSessionClient(+ cloud.client,+ context("in_progress"),+ );+ const onEvent = vi.fn();+ session.onExtensionEvent(onEvent, vi.fn());++ const pendingRequest = {+ type: "extension_ui_request",+ id: "pending",+ method: "confirm",+ title: "Continue?",+ message: "Proceed?",+ };+ const resolvedRequest = {+ ...pendingRequest,+ id: "resolved",+ };+ cloud.sendUpdate({+ taskId: "task-1",+ runId: "run-1",+ kind: "snapshot",+ status: "in_progress",+ newEntries: [+ entry(pendingRequest),+ entry(resolvedRequest),+ entry({+ type: "extension_ui_response",+ id: "resolved",+ confirmed: true,+ }),+ ],+ totalEntryCount: 3,+ });- expect(onEvent).toHaveBeenCalledTimes(2);- expect(onEvent).toHaveBeenCalledWith(pendingRequest);- expect(onEvent).toHaveBeenCalledWith({- type: "extension_ui_response",- id: "resolved",- confirmed: true,- });- expect(onEvent).not.toHaveBeenCalledWith(resolvedRequest);- });+ expect(onEvent).toHaveBeenCalledTimes(2);+ expect(onEvent).toHaveBeenCalledWith(pendingRequest);+ expect(onEvent).toHaveBeenCalledWith({+ type: "extension_ui_response",+ id: "resolved",+ confirmed: true,+ });+ expect(onEvent).not.toHaveBeenCalledWith(resolvedRequest);+ },+ );it("relays MCP permission requests and responses through the cloud task", async () => {const cloud = createCloudTaskClient();@@ -306,37 +324,49 @@ describe("CloudPiSessionClient", () => {);});- it("waits for the native Pi readiness event before startup RPC commands", async () => {- const cloud = createCloudTaskClient();- vi.mocked(cloud.client.sendCommand).mockResolvedValue({- success: true,- result: {- type: "response",- command: "get_state",- success: true,- data: { isStreaming: true },+ it.each([+ { format: "Pi", readiness: { type: "pi_run_started" } },+ {+ format: "ACP",+ readiness: {+ type: "notification",+ notification: { method: "_posthog/run_started", params: {} },},- });- const session = new CloudPiSessionClient(- cloud.client,- context("in_progress"),- );- session.onConversationEvent(vi.fn(), vi.fn());+ },+ ])(+ "waits for the $format-format readiness event before startup RPC commands",+ async ({ readiness }) => {+ const cloud = createCloudTaskClient();+ vi.mocked(cloud.client.sendCommand).mockResolvedValue({+ success: true,+ result: {+ type: "response",+ command: "get_state",+ success: true,+ data: { isStreaming: true },+ },+ });+ const session = new CloudPiSessionClient(+ cloud.client,+ context("in_progress"),+ );+ session.onConversationEvent(vi.fn(), vi.fn());- const state = session.client.getState();- expect(cloud.client.sendCommand).not.toHaveBeenCalled();+ const state = session.client.getState();+ expect(cloud.client.sendCommand).not.toHaveBeenCalled();- cloud.sendUpdate({- taskId: "task-1",- runId: "run-1",- kind: "logs",- newEntries: [{ type: "pi_run_started" }],- totalEntryCount: 1,- });+ cloud.sendUpdate({+ taskId: "task-1",+ runId: "run-1",+ kind: "logs",+ newEntries: [readiness],+ totalEntryCount: 1,+ });- await expect(state).resolves.toMatchObject({ isStreaming: true });- expect(cloud.client.sendCommand).toHaveBeenCalledOnce();- });+ await expect(state).resolves.toMatchObject({ isStreaming: true });+ expect(cloud.client.sendCommand).toHaveBeenCalledOnce();+ },+ );it("uses the readiness snapshot when opening an already-running session", async () => {const cloud = createCloudTaskClient();@@ -725,49 +755,55 @@ describe("CloudPiSessionClient", () => {});});- it("loads terminal history from the cloud snapshot without sandbox RPC", async () => {- const cloud = createCloudTaskClient();- const session = new CloudPiSessionClient(- cloud.client,- context("completed"),- );- const events: AgentConversationEvent[] = [];- const eventContexts: Array<{ isLive: boolean } | undefined> = [];- session.onConversationEvent((event, context) => {- events.push(event);- eventContexts.push(context);- }, vi.fn());-- const conversation = session.getConversation();- cloud.sendUpdate({- taskId: "task-1",- runId: "run-1",- kind: "snapshot",- status: "completed",- newEntries: [{ type: "pi_event", event: snapshotEvent }],- totalEntryCount: 1,- });+ it.each([+ { format: "Pi", entry: { type: "pi_event", event: snapshotEvent } },+ { format: "ACP", entry: acpEntry(snapshotEvent) },+ ])(+ "loads $format-format terminal history from the cloud snapshot without sandbox RPC",+ async ({ entry }) => {+ const cloud = createCloudTaskClient();+ const session = new CloudPiSessionClient(+ cloud.client,+ context("completed"),+ );+ const events: AgentConversationEvent[] = [];+ const eventContexts: Array<{ isLive: boolean } | undefined> = [];+ session.onConversationEvent((event, context) => {+ events.push(event);+ eventContexts.push(context);+ }, vi.fn());++ const conversation = session.getConversation();+ cloud.sendUpdate({+ taskId: "task-1",+ runId: "run-1",+ kind: "snapshot",+ status: "completed",+ newEntries: [entry],+ totalEntryCount: 1,+ });- await expect(conversation).resolves.toEqual([- expect.objectContaining(snapshotEvent),- ]);- expect(session.resumeRequired).toBe(true);- await expect(session.health()).resolves.toEqual({ state: "cold" });- await expect(session.client.getState()).resolves.toMatchObject({- isStreaming: false,- });- await expect(session.client.getAvailableModels()).resolves.toEqual([]);- await expect(session.client.getCommands()).resolves.toEqual([]);- expect(events).toEqual([- expect.objectContaining(snapshotEvent),- expect.objectContaining({- type: "turn_completed",- stopReason: "end_turn",- }),- ]);- expect(eventContexts).toEqual([{ isLive: false }, { isLive: false }]);- expect(cloud.client.sendCommand).not.toHaveBeenCalled();- });+ await expect(conversation).resolves.toEqual([+ expect.objectContaining(snapshotEvent),+ ]);+ expect(session.resumeRequired).toBe(true);+ await expect(session.health()).resolves.toEqual({ state: "cold" });+ await expect(session.client.getState()).resolves.toMatchObject({+ isStreaming: false,+ });+ await expect(session.client.getAvailableModels()).resolves.toEqual([]);+ await expect(session.client.getCommands()).resolves.toEqual([]);+ expect(events).toEqual([+ expect.objectContaining(snapshotEvent),+ expect.objectContaining({+ type: "turn_completed",+ stopReason: "end_turn",+ }),+ ]);+ expect(eventContexts).toEqual([{ isLive: false }, { isLive: false }]);+ expect(cloud.client.sendCommand).not.toHaveBeenCalled();+ },+ );it("does not install streaming state after a terminal snapshot arrives during controller load", async () => {const cloud = createCloudTaskClient();diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.tsindex 9a8b086b47f7..986f4e514127 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts@@ -17,11 +17,13 @@ import {} from "@posthog/agent/pi/types";import {type AgentConversationEvent,+ acpNotificationToAgentConversationEvent,type McpToolPermissionDecision,type McpToolPermissionRequest,type PiRuntimeHealth,readMcpInstallationId,readMcpToolDescriptor,+ readPiExtensionMessage,type StoredLogEntry,type TaskRunStatus,} from "@posthog/shared";@@ -83,9 +85,20 @@ function extensionMessageFromLogEntry(entry: StoredLogEntry): unknown {) {return entry.notification.params;}+ if (entry.type === "notification") {+ return readPiExtensionMessage(entry.notification?.params);+ }return entry;}+function isRunStartedEntry(entry: StoredLogEntry): boolean {+ return (+ entry.type === "pi_run_started" ||+ (entry.type === "notification" &&+ entry.notification?.method === "_posthog/run_started")+ );+}+function permissionDescription(content: unknown[] | undefined,): string | undefined {@@ -519,7 +532,7 @@ export class CloudPiSessionClient implements PiSession {update.sandboxAlive !== false;const hasRuntimeStartedEvent =(update.kind === "logs" || update.kind === "snapshot") &&- update.newEntries.some((entry) => entry.type === "pi_run_started");+ update.newEntries.some(isRunStartedEntry);const hasLiveRuntimeStarted =update.kind === "logs" && hasRuntimeStartedEvent;if (hasLiveRuntimeStarted) {@@ -667,11 +680,37 @@ export class CloudPiSessionClient implements PiSession {const progress = this.getProgressEvent(entry);if (progress) {events.push({ ...progress, sourceId });+ continue;+ }++ const event = this.getAcpConversationEvent(entry);+ if (event) {+ events.push({ ...event, sourceId });}}return events;}+ private getAcpConversationEvent(+ entry: StoredLogEntry,+ ): AgentConversationEvent | null {+ const method = entry.notification?.method;+ const params = entry.notification?.params;+ if (+ entry.type !== "notification" ||+ !method ||+ typeof params !== "object" ||+ params === null+ ) {+ return null;+ }+ const timestamp = Date.parse(entry.timestamp ?? "");+ return acpNotificationToAgentConversationEvent(+ { method, params: params as Record<string, unknown> },+ Number.isNaN(timestamp) ? Date.now() : timestamp,+ );+ }+private normalizeLegacyEvent(event: AgentConversationEvent,): AgentConversationEvent {diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.tsindex cd9204321f00..b26c5457334e 100644--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts@@ -13,6 +13,7 @@ import { isSessionStartupPhase } from "@posthog/core/sessions/sessionStartup";import {type AcpMessage,type AgentConversationEvent,+ agentConversationEventToSessionUpdate,isJsonRpcNotification,isJsonRpcRequest,isJsonRpcResponse,@@ -452,52 +453,16 @@ export function processAgentConversationEvent(return;}- if (event.type === "assistant_message_chunk") {+ const sessionUpdate = agentConversationEventToSessionUpdate(event);+ if (sessionUpdate) {processSessionUpdate(b,- { sessionUpdate: "agent_message_chunk", content: event.content },+ sessionUpdate as ConversationSessionUpdate,event.timestamp,);return;}- if (event.type === "assistant_thought_chunk") {- processSessionUpdate(- b,- { sessionUpdate: "agent_thought_chunk", content: event.content },- event.timestamp,- );- return;- }-- if (event.type === "tool_call_started") {- const { id, parentId, ...toolCall } = event.toolCall;- const update: ConversationSessionUpdate = {- sessionUpdate: "tool_call",- toolCallId: id,- ...toolCall,- ...(parentId- ? { _meta: { claudeCode: { parentToolCallId: parentId } } }- : {}),- };- processSessionUpdate(b, update, event.timestamp);- return;- }-- if (event.type === "tool_call_updated") {- const { id, parentId, ...toolCall } = event.toolCall;- const update: ConversationSessionUpdate = {- sessionUpdate: "tool_call_update",- toolCallId: id,- ...toolCall,- ...(parentId- ? { _meta: { claudeCode: { parentToolCallId: parentId } } }- : {}),- };- processSessionUpdate(b, update, event.timestamp);- return;- }-if (event.type === "progress") {handleProgress(b, event, event.timestamp, {waitForRunStarted: false,diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.tsindex 64c22db49a1d..f1554ce8f72d 100644--- a/products/logs/frontend/generated/api.ts+++ b/products/logs/frontend/generated/api.ts@@ -1256,7 +1256,7 @@ export const getTasksRunsLogsRetrieveUrl = (projectId: string, taskId: string, i}/**- * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history.+ * Fetch the logs for a task run as JSONL. If the run resumes from another (state.resume_from_run_id), each ancestor's log is concatenated first (oldest ancestor → ... → this run) so resume consumers see a single continuous history. A resumed Pi run includes the earlier runs of its task session the same way, each preceded by a pi_run_started entry that names its run.* @summary Get task run logs*/export const tasksRunsLogsRetrieve = async (diff --git a/products/posthog_ai/frontend/components/OptionSelector.tsx b/products/posthog_ai/frontend/components/OptionSelector.tsxindex fdbeaa67677b..fa670e6d607c 100644--- a/products/posthog_ai/frontend/components/OptionSelector.tsx+++ b/products/posthog_ai/frontend/components/OptionSelector.tsx@@ -1,6 +1,6 @@import { useEffect, useRef, useState } from 'react'-import { LemonButton, LemonInput, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonTextArea, Spinner } from '@posthog/lemon-ui'import { CollapsiblePrimitive, CollapsiblePrimitiveContent } from 'lib/ui/Collapsible/lib/CollapsiblePrimitive'import { cn } from 'lib/utils/css-classes'@@ -29,6 +29,7 @@ interface OptionSelectorProps {submitLabel?: string/** Called when the user clicks "Skip question" */onSkip?: () => void+ multiline?: boolean}export function OptionSelector({@@ -44,10 +45,12 @@ export function OptionSelector({selectedValue,submitLabel = 'Next',onSkip,+ multiline = false,}: OptionSelectorProps): JSX.Element {+ const freeTextOnly = allowCustom && options.length === 0const isCustomValue = selectedValue !== undefined && !options.some((o) => o.value === selectedValue)const [userWantsCustomMode, setUserWantsCustomMode] = useState(isCustomValue)- const showCustomInput = userWantsCustomMode || isCustomValue+ const showCustomInput = freeTextOnly || userWantsCustomMode || isCustomValueconst [customInput, setCustomInput] = useState(initialCustomValue ?? '')const selectedValueRef = useRef(selectedValue)selectedValueRef.current = selectedValue@@ -58,7 +61,7 @@ export function OptionSelector({}function handleKeyDown(event: KeyboardEvent): void {- if (showCustomInput && event.key === 'Escape') {+ if (showCustomInput && !freeTextOnly && event.key === 'Escape') {event.preventDefault()setUserWantsCustomMode(false)setCustomInput('')@@ -93,7 +96,7 @@ export function OptionSelector({return () => {window.removeEventListener('keydown', handleKeyDown)}- }, [options, onSelect, allowCustom, disabled, loading, showCustomInput])+ }, [options, onSelect, allowCustom, disabled, loading, showCustomInput, freeTextOnly])const noDescriptions = options.every((o) => !o.description)const footerOpen = !!onSkip || showCustomInput@@ -109,6 +112,10 @@ export function OptionSelector({return}+ if (freeTextOnly) {+ onCustomSubmit?.(multiline ? customInput : customInput.trim())+ return+ }setUserWantsCustomMode(false)onCustomSubmit?.(customInput.trim())}@@ -165,7 +172,29 @@ export function OptionSelector({))}</div>- {allowCustom && (+ {freeTextOnly &&+ (multiline ? (+ <LemonTextArea+ placeholder={customPlaceholder}+ value={customInput}+ onChange={setCustomInput}+ onPressCmdEnter={handleCustomSubmit}+ minRows={3}+ maxRows={12}+ autoFocus+ />+ ) : (+ <LemonInput+ placeholder={customPlaceholder}+ fullWidth+ size="small"+ value={customInput}+ onChange={setCustomInput}+ onPressEnter={handleCustomSubmit}+ autoFocus+ />+ ))}+ {allowCustom && !freeTextOnly && (<label className="grid items-center gap-x-2 grid-cols-[min-content_auto] text-sm font-medium cursor-pointer"><inputtype="radio"diff --git a/products/posthog_ai/frontend/components/QuestionField.tsx b/products/posthog_ai/frontend/components/QuestionField.tsxindex c4bf37345ef3..192825b0a399 100644--- a/products/posthog_ai/frontend/components/QuestionField.tsx+++ b/products/posthog_ai/frontend/components/QuestionField.tsx@@ -20,6 +20,9 @@ interface QuestionFieldProps {onSkip?: () => voidsubmitLabel?: stringdisabled?: boolean+ customPlaceholder?: string+ initialCustomValue?: string+ multiline?: boolean}export function QuestionField({@@ -31,6 +34,9 @@ export function QuestionField({onSkip,submitLabel = 'Next',disabled = false,+ customPlaceholder,+ initialCustomValue,+ multiline,}: QuestionFieldProps): JSX.Element {const fieldType = question.type ?? 'select'@@ -56,6 +62,9 @@ export function QuestionField({onAnswer={onAnswer}onSkip={onSkip}submitLabel={submitLabel}+ customPlaceholder={customPlaceholder}+ initialCustomValue={initialCustomValue}+ multiline={multiline}/>)}@@ -68,6 +77,9 @@ function SelectField({onAnswer,onSkip,submitLabel,+ customPlaceholder,+ initialCustomValue,+ multiline,}: {disabled: booleanquestion: MultiQuestionFormQuestion@@ -75,6 +87,9 @@ function SelectField({onAnswer: (value: string | null) => voidonSkip?: () => voidsubmitLabel: string+ customPlaceholder?: string+ initialCustomValue?: string+ multiline?: boolean}): JSX.Element {const options: Option[] = (question.options ?? []).map((option) => ({label: option.value,@@ -90,7 +105,9 @@ function SelectField({options={options}onSelect={onAnswer}allowCustom={allowCustomAnswer}- customPlaceholder="Type your answer..."+ customPlaceholder={customPlaceholder ?? 'Type your answer...'}+ initialCustomValue={initialCustomValue}+ multiline={multiline}onCustomSubmit={onAnswer}selectedValue={value}submitLabel={submitLabel}diff --git a/products/posthog_ai/frontend/components/QuestionInput.test.tsx b/products/posthog_ai/frontend/components/QuestionInput.test.tsxindex 54d741f583af..cdfd06dec9e6 100644--- a/products/posthog_ai/frontend/components/QuestionInput.test.tsx+++ b/products/posthog_ai/frontend/components/QuestionInput.test.tsx@@ -164,6 +164,40 @@ describe('QuestionInput', () => {})})+ it.each([+ {+ caseName: 'an input prompt',+ extra: { placeholder: 'Button label' },+ findField: () => screen.getByPlaceholderText('Button label'),+ typed: 'Download CSV',+ sent: 'Download CSV',+ },+ {+ caseName: 'an editor prompt',+ extra: { defaultAnswer: 'Line one\nLine two', multiline: true },+ findField: () => screen.getByDisplayValue(/Line one/),+ typed: undefined,+ sent: 'Line one\nLine two',+ },+ ])('answers $caseName through a field that is open from the start', ({ extra, findField, typed, sent }) => {+ const question: AgentQuestion = { question: 'What should it say?', multiSelect: false, options: [], ...extra }+ render(<QuestionInput streamKey="conv-1" request={makeRequest([question])} />)++ expect(screen.queryByText("Explain what you'd like instead.")).not.toBeInTheDocument()+ if (typed !== undefined) {+ fireEvent.change(findField(), { target: { value: typed } })+ }+ expect(findField()).toHaveValue(sent)+ fireEvent.click(screen.getByText('Submit'))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'option_0',+ answers: { 'What should it say?': sent },+ customInput: sent,+ })+ })+it('preserves custom answers and disables hidden shortcuts during delivery', () => {const request = makeRequest([goalQuestion])const { rerender } = render(<QuestionInput streamKey="conv-1" request={request} />)diff --git a/products/posthog_ai/frontend/components/QuestionInput.tsx b/products/posthog_ai/frontend/components/QuestionInput.tsxindex 0fb7f33440e4..cae181b3333f 100644--- a/products/posthog_ai/frontend/components/QuestionInput.tsx+++ b/products/posthog_ai/frontend/components/QuestionInput.tsx@@ -164,6 +164,9 @@ export function QuestionInput({ streamKey, request, disabled = false }: QuestiononChange={handleMultiSelectChange}onSubmit={handleMultiSelectSubmit}submitLabel={isLast ? 'Submit' : 'Next'}+ customPlaceholder={question.placeholder}+ initialCustomValue={question.defaultAnswer}+ multiline={question.multiline}/></div>)diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsxindex d1df99c6b14d..78980b1bc7b7 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx@@ -4,6 +4,8 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'import { useActions, useValues } from 'kea'import { useState } from 'react'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import type { RunStatus } from '../logics/runStreamLogic'@@ -24,6 +26,8 @@ jest.mock('../logics/runStreamLogic', () => ({status != null && ['completed', 'failed', 'cancelled'].includes(status),}))+jest.mock('lib/hooks/useFeatureFlag', () => ({ useFeatureFlag: jest.fn() }))+jest.mock('../logics/taskLogic', () => ({ taskLogic: jest.fn(() => ({ __mock: 'taskLogic' })) }))jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))@@ -41,12 +45,15 @@ function setValues(runOpening: booleanthreadItems: unknown[]task: { origin_product: string; runtime?: TaskRuntimeEnumApi } | null+ piAcpEnabled: boolean}>): void {+ const { piAcpEnabled = true, ...values } = overrides+ ;(useFeatureFlag as jest.Mock).mockReturnValue(piAcpEnabled);(useValues as jest.Mock).mockReturnValue({bootstrapLoading: false,threadItems: [],- hasThreadItems: !!overrides.threadItems?.length,+ hasThreadItems: !!values.threadItems?.length,pendingPermissionRequest: null,respondingToPermission: false,currentRunStatus: 'in_progress',@@ -54,7 +61,7 @@ function setValues(taskLoading: false,taskError: null,taskNotFound: false,- ...overrides,+ ...values,})}@@ -106,8 +113,14 @@ describe('RunSurface', () => {cleanup()})- it('does not mount the ACP run surface for a Pi task', () => {- setValues({ task: { origin_product: 'user_created', runtime: TaskRuntimeEnumApi.Pi } })+ it.each([+ { caseName: 'a Pi task', runtime: TaskRuntimeEnumApi.Pi },+ { caseName: 'an ACP task', runtime: TaskRuntimeEnumApi.Acp },+ { caseName: 'an older API response without runtime', runtime: undefined },+ ])('mounts the run surface and bootstraps with the runtime for $caseName', ({ runtime }) => {+ const bootstrapRun = jest.fn()+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun, reset: jest.fn(), loadTask: jest.fn() })+ setValues({ task: { origin_product: 'user_created', runtime } })render(<RunSurface.Root taskId="task-1" runId="run-1" interaction="live">@@ -118,13 +131,18 @@ describe('RunSurface', () => {</RunSurface.Root>)- expect(screen.getByText("Pi session logs aren't available in PostHog yet.")).toBeInTheDocument()- expect(screen.queryByTestId('thread')).not.toBeInTheDocument()- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ expect(screen.getByTestId('thread')).toBeInTheDocument()+ expect(screen.getByTestId('composer-child')).toBeInTheDocument()+ expect(bootstrapRun).toHaveBeenCalledWith({ taskId: 'task-1', runId: 'run-1', taskRuntime: runtime })})- it('keeps the ACP run surface available when an older API response omits runtime', () => {- setValues({ task: { origin_product: 'user_created' } })+ it('keeps a Pi task behind the unavailable banner until Pi web sessions are on', () => {+ const bootstrapRun = jest.fn()+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun, reset: jest.fn(), loadTask: jest.fn() })+ setValues({+ task: { origin_product: 'user_created', runtime: TaskRuntimeEnumApi.Pi },+ piAcpEnabled: false,+ })render(<RunSurface.Root taskId="task-1" runId="run-1" interaction="live">@@ -132,8 +150,9 @@ describe('RunSurface', () => {</RunSurface.Root>)- expect(screen.getByTestId('thread')).toBeInTheDocument()- expect(screen.queryByText("Pi session logs aren't available in PostHog yet.")).not.toBeInTheDocument()+ expect(screen.getByText("Pi session logs aren't available in PostHog yet.")).toBeInTheDocument()+ expect(screen.queryByTestId('thread')).not.toBeInTheDocument()+ expect(bootstrapRun).not.toHaveBeenCalled()})describe('Composer slot', () => {diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxindex 939a844383fb..4172e168b20a 100644--- a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -3,6 +3,8 @@ import { createContext, type ReactNode, useCallback, useContext, useEffect, useMimport { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { useThreadSkin } from '../hooks/useThreadSkin'import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'import { taskLogic } from '../logics/taskLogic'@@ -60,6 +62,7 @@ interface RunSurfaceContextValue {isScout: booleanfloatingInputsHeight: numbersetFloatingInputsHeight: (height: number) => void+ taskRuntime?: string | null}const FLOATING_INPUTS_GAP = 16@@ -103,6 +106,7 @@ function RunSurfaceRoot({// The runtime and scout flag live on the task (not the run), so the surface owns loading it once and// exposing it to the slots. The runner already has the task loaded; an embed fetches it here.const { task, taskLoading, taskError, taskNotFound } = useValues(taskLogic({ taskId }))+ const piAcpEnabled = useFeatureFlag('PI_ACP')const { loadTask } = useActions(taskLogic({ taskId }))useEffect(() => {// A pending surface (optimistic create) has no task yet, so don't fetch an empty id.@@ -127,7 +131,7 @@ function RunSurfaceRoot({}}- if (task && isPiTaskRuntime(task.runtime)) {+ if (task && isPiTaskRuntime(task.runtime) && !piAcpEnabled) {return <LemonBanner type="info">Pi session logs aren't available in PostHog yet.</LemonBanner>}@@ -145,6 +149,7 @@ function RunSurfaceRoot({isScout,floatingInputsHeight,setFloatingInputsHeight,+ taskRuntime: task?.runtime,}}><RunSurfaceBootstrap taskId={taskId} />@@ -156,7 +161,7 @@ function RunSurfaceRoot({/** Drives the run bootstrap as a side effect; renders nothing. Kept separate so slots stay presentational. */function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {- const { runId, interaction } = useRunSurfaceContext()+ const { runId, interaction, taskRuntime } = useRunSurfaceContext()const { bootstrapRun, reset } = useActions(runStreamLogic)// The bootstrap decision reads logic-resident state (not a per-component ref) so it survives the// optimistic create-thread → detail-page component swap onto the same `streamKey` instance.@@ -181,7 +186,7 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {if (awaitingOptimisticAttach) {// Attaching a freshly-created run to a seeded optimistic instance: skip the reset so the seed// survives, and take the fresh-run fast path. The live SSE echo dedups the seeded message.- bootstrapRun({ taskId, runId, justCreatedRun: true })+ bootstrapRun({ taskId, runId, justCreatedRun: true, taskRuntime })return}// Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run@@ -189,8 +194,18 @@ function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {// `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right// mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.reset()- bootstrapRun({ taskId, runId })- }, [taskId, runId, interaction, bootstrappedRunId, awaitingOptimisticAttach, currentProjectId, bootstrapRun, reset])+ bootstrapRun({ taskId, runId, taskRuntime })+ }, [+ taskId,+ runId,+ interaction,+ taskRuntime,+ bootstrappedRunId,+ awaitingOptimisticAttach,+ currentProjectId,+ bootstrapRun,+ reset,+ ])return null}diff --git a/products/posthog_ai/frontend/components/ThreadItems.tsx b/products/posthog_ai/frontend/components/ThreadItems.tsxindex da0901e0cad6..ea2c3abf5824 100644--- a/products/posthog_ai/frontend/components/ThreadItems.tsx+++ b/products/posthog_ai/frontend/components/ThreadItems.tsx@@ -11,6 +11,7 @@ import type { ActivityStatus } from './activityTypes'const IN_PROGRESS_STATUS_LABELS: Record<string, string> = {compacting: 'Compacting conversation history…',clearing: 'Clearing conversation…',+ retrying: 'Retrying the model request…',}function StatusLine({ icon, children }: { icon?: JSX.Element; children: React.ReactNode }): JSX.Element {@@ -35,6 +36,15 @@ export function StatusItem({ item }: { item: ThreadItem }): JSX.Element {: "Couldn't clear the conversation"return <StatusLine icon={<IconX className="size-3" />}>{reason}. Start a new run to keep going.</StatusLine>}+ if (item.status === 'compacting_failed') {+ const reason = item.errorMessage+ ? `Couldn't compact the conversation: ${item.errorMessage}`+ : "Couldn't compact the conversation"+ return <StatusLine icon={<IconWarning className="size-3" />}>{reason}</StatusLine>+ }+ if (item.status === 'extension_notice' && item.message) {+ return <StatusLine icon={<IconWarning className="size-3" />}>{item.message}</StatusLine>+ }return <StatusLine>Status: {item.status}</StatusLine>}diff --git a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.test.tsxindex ada0cd7f6edb..de8b6623394e 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.test.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.test.tsx@@ -7,6 +7,7 @@ import {ModelChoiceApi,ReasoningEffortEnumApi,RuntimeAdapterEnumApi,+ TaskRuntimeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'import { ComposerModelEffortPickers } from './ComposerModelEffortPickers'@@ -137,6 +138,26 @@ describe('ComposerModelEffortPickers', () => {})})+ it('lists every model with no harness choice for a Pi task', async () => {+ renderPickers({+ taskRuntime: TaskRuntimeEnumApi.Pi,+ models: [+ ...CATALOGUE,+ {+ runtime_adapter: RuntimeAdapterEnumApi.Codex,+ model: 'gpt-6-sol',+ display_name: 'GPT-6 Sol',+ supported_efforts: [ReasoningEffortEnumApi.High],+ },+ ],+ })++ expect(screen.queryByText('Harness')).not.toBeInTheDocument()+ fireEvent.click(screen.getByText('Model'))+ expect(await screen.findByText('GPT-6 Sol')).toBeInTheDocument()+ expect(screen.getByText('Claude Sonnet 5.5')).toBeInTheDocument()+ })+it('offers no way to change the default on a surface that has none to change', () => {renderPickers()diff --git a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsxindex 9158b6409a13..b9acda5dd5f0 100644--- a/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx+++ b/products/posthog_ai/frontend/components/composer/ComposerModelEffortPickers.tsx@@ -32,6 +32,7 @@ import {ModelChoiceApi,ReasoningEffortEnumApi,RuntimeAdapterEnumApi,+ TaskRuntimeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'import { useThreadSkin } from '../../hooks/useThreadSkin'@@ -88,6 +89,7 @@ export interface ComposerModelEffortPickersProps {/** Who pays for a run on the Codex harness. Shown only while Codex is selected; omit to hide the row. */codexBilling?: ComposerCodexBillingphoneSheet?: boolean+ taskRuntime?: TaskRuntimeEnumApi}interface PickerSectionProps {@@ -151,6 +153,7 @@ export function ComposerModelEffortPickers({onOpenDefaultSettings,codexBilling,phoneSheet = false,+ taskRuntime,}: ComposerModelEffortPickersProps): JSX.Element {const chrome = PICKER_CHROME[useThreadSkin()]const [open, setOpen] = useState(false)@@ -165,18 +168,18 @@ export function ComposerModelEffortPickers({const { selectedAdapter, modelLabel, effortOptions, adapters, adapterModels, ladder, showsAnyCost } =useMemo(() => {const adapter = getRuntimeAdapterForModel(models, selectedModel)- const offered = modelsForRuntimeAdapter(models, adapter)+ const offered = modelsForRuntimeAdapter(models, adapter, taskRuntime)return {selectedAdapter: adapter,modelLabel: getModelLabel(models, selectedModel),effortOptions: getEffortsForModel(models, selectedModel),- adapters: listRuntimeAdapters(models),+ adapters: listRuntimeAdapters(models, taskRuntime),adapterModels: offered,ladder: getCapabilityLadder(models, adapter),// The legend explains a symbol, so it only belongs where a row carries one.showsAnyCost: offered.some((option) => !!getModelCost(option.model)),}- }, [models, selectedModel])+ }, [models, selectedModel, taskRuntime])const selectAdapter = (adapter: string): void => {const runtimeAdapter = adapter as RuntimeAdapterEnumApidiff --git a/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.test.tsx b/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.test.tsxnew file mode 100644index 000000000000..154c3d078e7e--- /dev/null+++ b/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.test.tsx@@ -0,0 +1,26 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import type { ThreadItem } from '../../types/streamTypes'+import { QuillSeparatorRow } from './QuillSeparatorRow'++describe('QuillSeparatorRow', () => {+ afterEach(cleanup)++ it.each([+ {+ caseName: 'an extension notice shows its message',+ item: { id: 's1', type: 'status', status: 'extension_notice', isComplete: true, message: 'Picked: Blue' },+ label: 'Picked: Blue',+ },+ {+ caseName: 'an extension notice without a message falls back to the status name',+ item: { id: 's2', type: 'status', status: 'extension_notice', isComplete: true },+ label: 'Extension notice',+ },+ ])('$caseName', ({ item, label }) => {+ render(<QuillSeparatorRow item={item as ThreadItem} live={false} />)+ expect(screen.getByText(label)).toBeInTheDocument()+ })+})diff --git a/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsx b/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsxindex 529a1980fdba..6bd01459499d 100644--- a/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsx+++ b/products/posthog_ai/frontend/components/quill/QuillSeparatorRow.tsx@@ -26,6 +26,9 @@ function statusLabel(item: ThreadItem, live: boolean): { label: string; running:if (isRunningStatus(item)) {return { label: RUNNING_LABELS[status], running: true }}+ if (status === 'extension_notice' && item.message) {+ return { label: item.message, running: false }+ }// A failed clear leaves the agent session closed, so the way forward is a new run, not a retry.if (status === 'clearing_failed') {const reason = item.errorMessagediff --git a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsxindex 97ae9cc00e2a..10f5540fa056 100644--- a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx@@ -51,7 +51,9 @@ export function getMcpToolPresentation(? `Call ${toolLabel}`: isMcp? `Call ${serverName} – ${toolLabel} (MCP)`- : message.title || displayName || toolLabel || (message.kind && KIND_LABELS[message.kind]) || ''+ : message.proxiedToolName+ ? `Call ${message.proxiedToolName} (MCP)`+ : message.title || displayName || toolLabel || (message.kind && KIND_LABELS[message.kind]) || ''// The PostHog MCP asks the agent for a one-sentence `context` on every call. It is the only// harness-independent description of intent, so it reads better in the row than the command.const context = typeof message.rawInput.context === 'string' ? message.rawInput.context.trim() : ''diff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsxindex e1175ffe0c5d..8a1a75dd2aff 100644--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx@@ -417,17 +417,18 @@ const SkillToolRenderer = memo(function SkillToolRenderer(props: ToolRendererPro})/**- * ToolSearch — Claude's deferred-tool search, rendered like PostHog's MCP tool search: a "Search tools"- * header with the query on the second line and the matched tool schemas in the body. Falls back to the- * generic card when the input isn't the expected `{ query, max_results }` shape.+ * ToolSearch — a deferred-tool search (Claude's built-in, or a Pi MCP proxy search resolved onto this key),+ * rendered like PostHog's MCP tool search: a "Search tools" header with the query on the second line and+ * the matched tool schemas in the body. Falls back to the generic card when no query is present.*/const ToolSearchRenderer = memo(function ToolSearchRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = props- const query = asString(message.rawInput.query)- if (!query || typeof message.rawInput.max_results !== 'number') {+ const input = message.innerInput ?? message.rawInput+ const query = asString(input.query)+ if (!query) {return <GenericMcpToolRenderer {...props} />}- const formattedInput = formatInput(message.rawInput)+ const formattedInput = formatInput(input)const output = stripCodeFences(getContentText(message.content))const body =formattedInput || output ? (diff --git a/products/posthog_ai/frontend/logics/runCancellationLogic.test.ts b/products/posthog_ai/frontend/logics/runCancellationLogic.test.tsindex d44473d25756..2dfb5d2587e7 100644--- a/products/posthog_ai/frontend/logics/runCancellationLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runCancellationLogic.test.ts@@ -103,6 +103,24 @@ describe('runCancellationLogic', () => {expect(logic.values.cancellationState).toBeNull()})+ it('stops a run whose logged run start carries no run id', async () => {+ attach()+ logic.actions.requestCancellation()+ await expectLogic(logic, () => {+ stream.actions.ingestAcpFrame({+ type: 'notification',+ timestamp: '2026-01-01T00:00:00Z',+ notification: { method: '_posthog/run_started', params: {} },+ source_run_id: 'run-1',+ })+ stream.actions.ingestAcpFrame(prompt('run-1', 'agent_message_chunk'))+ }).toFinishAllListeners()+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'cancel',+ })+ })+it('ignores readiness from an earlier resumed run', async () => {attach()logic.actions.requestCancellation()diff --git a/products/posthog_ai/frontend/logics/runCancellationLogic.ts b/products/posthog_ai/frontend/logics/runCancellationLogic.tsindex 2635985fafab..974eedc970fd 100644--- a/products/posthog_ai/frontend/logics/runCancellationLogic.ts+++ b/products/posthog_ai/frontend/logics/runCancellationLogic.ts@@ -25,7 +25,8 @@ function confirmsAgentReady(entry: StoredLogEntry, runId: string): boolean {params?.group === `setup:${runId}` &¶ms.step === 'agent' &¶ms.status === 'completed') ||- (method === '_posthog/run_started' && params?.runId === runId)+ (method === '_posthog/run_started' &&+ (params?.runId === runId || (params?.runId === undefined && entry.source_run_id === runId))))}diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 342f44cf0703..feaef54d30e9 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -14,6 +14,7 @@ import {tasksRunsCommandCreate,tasksWarmResumeCreate,} from 'products/tasks/frontend/generated/api'+import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import type { PermissionRequestRecord } from '../types/streamTypes'import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'@@ -46,6 +47,7 @@ jest.mock('./runStreamLogic', () => {respondToPermission: (payload: unknown) => ({ payload }),cancelRun: (run?: unknown) => ({ run }),markTurnComplete: (isReplay: boolean = false) => ({ isReplay }),+ markRunStarted: true,setCurrentMode: (mode: string) => ({ mode }),handleTerminalStatus: (status: { status: string }) => status,setStubStatus: (status: string | null) => ({ status }),@@ -1071,6 +1073,80 @@ describe('runInteractionLogic', () => {expect(toolEvents.values.applyBackTargetClaims[RUN_ID]).toBeUndefined()})+ describe('Pi task', () => {+ let piLogic: ReturnType<typeof runInteractionLogic.build>++ beforeEach(() => {+ logic.unmount()+ piLogic = runInteractionLogic({+ taskId: TASK_ID,+ runId: RUN_ID,+ onRunStarted,+ taskRuntime: TaskRuntimeEnumApi.Pi,+ })+ piLogic.mount()+ })++ afterEach(() => {+ piLogic.unmount()+ logic.mount()+ })++ const configCommand = (configId: string, value: string): [string, string, string, Record<string, unknown>] => [+ '997',+ TASK_ID,+ RUN_ID,+ { jsonrpc: '2.0', method: 'set_config_option', params: { configId, value } },+ ]++ it.each([+ { caseName: 'no pick', pick: () => {}, commands: [] },+ {+ caseName: 'a picked model',+ pick: () => piLogic.actions.setModel('claude-opus-5-5'),+ commands: [configCommand('model', 'claude-opus-5-5')],+ },+ {+ caseName: 'a picked effort',+ pick: () => piLogic.actions.setEffort('low'),+ commands: [configCommand('effort', 'low')],+ },+ ])('syncs $caseName to the Pi session before a follow-up', async ({ pick, commands }) => {+ pick()+ piLogic.actions.setComposerFormValues({ draft: 'keep going' })+ await expectLogic(piLogic, () => piLogic.actions.submitComposerForm()).toFinishAllListeners()++ expect((tasksRunsCommandCreate as jest.Mock).mock.calls).toEqual([+ ...commands,+ userMessageCommand('keep going'),+ ])+ })++ it.each([+ { caseName: 'no pick', pick: () => {}, selection: {} },+ {+ caseName: 'a picked model and effort',+ pick: () => {+ piLogic.actions.setModel('claude-opus-5-5')+ piLogic.actions.setEffort('low')+ },+ selection: { model: 'claude-opus-5-5', reasoning_effort: 'low' },+ },+ ])('resumes a terminal run with $caseName', async ({ pick, selection }) => {+ setStatus('completed')+ pick()+ piLogic.actions.setComposerFormValues({ draft: 'continue from here' })+ await expectLogic(piLogic, () => piLogic.actions.submitComposerForm()).toFinishAllListeners()++ expect(tasksRunCreate).toHaveBeenCalledWith(+ '997',+ TASK_ID,+ { resume_from_run_id: RUN_ID, pending_user_message: 'continue from here', ...selection },+ expect.objectContaining({ signal: expect.any(AbortSignal) })+ )+ })+ })+it('starts a fresh run seeded with the message when the run is terminal', async () => {let resolveRun!: (value: unknown) => void;(tasksRunCreate as jest.Mock).mockReturnValueOnce(diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 0d8f2b7c4663..ece905f04713 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -22,7 +22,7 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import {buildRunCreateRequest,- DEFAULT_COMPOSER_MODEL,+ getDefaultModelForTaskRuntime,getRuntimeAdapterForModel,resolveEffortForModel,} from 'products/posthog_ai/frontend/utils/composerModels'@@ -42,11 +42,13 @@ import {type ReasoningEffortEnumApi,RuntimeAdapterEnumApi,type TaskRunDetailDTOApi,+ type TaskRuntimeEnumApi,type WarmTaskResumeRequestApi,} from 'products/tasks/frontend/generated/api.schemas'import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'import type { PermissionRequestRecord, StagedAttachment } from '../types/streamTypes'+import { isPiTaskRuntime } from '../types/taskTypes'import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'import { rememberAttachmentPreview } from '../utils/attachmentPreviews'import type { PendingAttachment } from '../utils/attachments'@@ -65,6 +67,12 @@ import { taskRunDefaultsLogic } from './taskRunDefaultsLogic'import { taskWarmLogic, type WarmSubmission } from './taskWarmLogic'import { toolStreamEventsLogic } from './toolStreamEventsLogic'+/** What the agent session runs with before the user picks anything in this composer. */+export interface SessionBaseline {+ model: string | null+ effort: string | null+}+export interface RunInteractionLogicProps {/** Empty until creation attaches a real task and run. */taskId: string@@ -92,6 +100,7 @@ export interface RunInteractionLogicProps {currentRuntimeAdapter?: string | null/** Who pays for the run's Codex model use, from the run state. A live run keeps it. */currentCodexModelAccess?: string | null+ taskRuntime?: TaskRuntimeEnumApi/** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can* re-point selection to it (the run lifecycle / selection is a tasks-scene concern, injected here). */onRunStarted?: (runId: string, handoff?: RunContinuationHandoff) => void@@ -236,6 +245,7 @@ export interface runInteractionLogicValues {sentEffort: string | nullsentMode: PermissionMode | nullsentModel: string | null+ sessionBaseline: SessionBaselineshowComposerFormErrors: booleanstartingRun: booleansteerPending: boolean@@ -547,18 +557,20 @@ export interface runInteractionLogicMeta {isTerminal: boolean) => booleanisTerminal: (currentRunStatus: RunStatus | null) => boolean+ sessionBaseline: (defaultModel: string | null, defaultEffort: string | null, arg: any) => SessionBaselineselectedModel: (modelOverride: string | null,arg: any,- defaultModel: string | null,+ sessionBaseline: SessionBaseline,catalogue: ModelChoiceApi[],arg2: any,- isTerminal: boolean+ isTerminal: boolean,+ arg3: any) => stringselectedEffort: (effortOverride: string | null,arg: any,- defaultEffort: string | null,+ sessionBaseline: SessionBaseline,selectedModel: string,catalogue: ModelChoiceApi[]) => ReasoningEffortEnumApi@@ -985,25 +997,38 @@ export const runInteractionLogic = kea<runInteractionLogicType>([(s) => [s.currentRunStatus],(status: null | import('./runStreamLogic').RunStatus): boolean => isTerminalRunStatus(status),],+ sessionBaseline: [+ (s) => [s.defaultModel, s.defaultEffort, (_, p) => p.taskRuntime],+ (+ defaultModel: string | null,+ defaultEffort: string | null,+ taskRuntime: TaskRuntimeEnumApi | undefined+ ): SessionBaseline =>+ isPiTaskRuntime(taskRuntime)+ ? { model: null, effort: null }+ : { model: defaultModel, effort: defaultEffort },+ ],// The model/effort to display in the picker and launch the next run with: the optimistic client-side- // override, else the run's stored value, else the server-resolved default (user preference over- // project default), else the built-in default. Effort is clamped to one the model supports.+ // override, else the run's stored value, else the session baseline, else the runtime's built-in+ // default. Effort is clamped to one the model supports.selectedModel: [(s) => [s.modelOverride,(_, p) => p.currentModel,- s.defaultModel,+ s.sessionBaseline,s.catalogue,(_, p) => p.currentRuntimeAdapter,s.isTerminal,+ (_, p) => p.taskRuntime,],(override: string | null,current: string | null | undefined,- serverDefault: string | null,+ baseline: SessionBaseline,catalogue: ModelChoiceApi[],runtimeAdapter: string | null | undefined,- terminal: boolean+ terminal: boolean,+ taskRuntime: TaskRuntimeEnumApi | undefined): string => {const compatibleOverride =override &&@@ -1012,18 +1037,19 @@ export const runInteractionLogic = kea<runInteractionLogicType>([getRuntimeAdapterForModel(catalogue, override) !== runtimeAdapter? null: override- return compatibleOverride ?? current ?? serverDefault ?? DEFAULT_COMPOSER_MODEL+ return compatibleOverride ?? current ?? baseline.model ?? getDefaultModelForTaskRuntime(taskRuntime)},],selectedEffort: [- (s) => [s.effortOverride, (_, p) => p.currentEffort, s.defaultEffort, s.selectedModel, s.catalogue],+ (s) => [s.effortOverride, (_, p) => p.currentEffort, s.sessionBaseline, s.selectedModel, s.catalogue],(override: string | null,current: string | null | undefined,- serverDefault: string | null,+ baseline: SessionBaseline,model: string,catalogue: ModelChoiceApi[]- ): ReasoningEffortEnumApi => resolveEffortForModel(catalogue, override ?? current ?? serverDefault, model),+ ): ReasoningEffortEnumApi =>+ resolveEffortForModel(catalogue, override ?? current ?? baseline.effort, model),],// The permission mode to display and launch with: the client-side override, else the session's live// mode (from the stream's `current_mode_update` frames), else the run's stored launch mode, else the@@ -1341,54 +1367,53 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// `set_config_option` command before the message rather than ride inside `user_message`. A// failure here aborts the send (the catch restores the content); `setSent*` runs only after a// successful sync so the next send retries an unsent change.+ const setConfigOption = (configId: string, value: string): Promise<unknown> =>+ tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {+ jsonrpc: '2.0',+ method: 'set_config_option',+ params: { configId, value },+ })const activeModel =- values.sentModel ?? props.currentModel ?? values.defaultModel ?? DEFAULT_COMPOSER_MODEL+ values.sentModel ??+ props.currentModel ??+ values.sessionBaseline.model ??+ getDefaultModelForTaskRuntime(props.taskRuntime)const activeEffort = resolveEffortForModel(values.catalogue,- values.sentEffort ?? props.currentEffort ?? values.defaultEffort,+ values.sentEffort ?? props.currentEffort ?? values.sessionBaseline.effort,activeModel)if (values.selectedModel !== activeModel) {- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {- jsonrpc: '2.0',- method: 'set_config_option',- params: { configId: MODEL_CONFIG_ID, value: values.selectedModel },- })+ await setConfigOption(MODEL_CONFIG_ID, values.selectedModel)if (!isCurrent()) {return}actions.setSentModel(values.selectedModel)}if (values.selectedEffort !== activeEffort) {- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {- jsonrpc: '2.0',- method: 'set_config_option',- params: { configId: EFFORT_CONFIG_ID, value: values.selectedEffort },- })+ await setConfigOption(EFFORT_CONFIG_ID, values.selectedEffort)if (!isCurrent()) {return}actions.setSentEffort(values.selectedEffort)}- const modeAdapter = props.currentRuntimeAdapter ?? RuntimeAdapterEnumApi.Claude- const lastKnownMode =- values.sentMode ??- getModeOption(values.currentMode)?.value ??- getModeOption(props.currentMode)?.value- const activeMode = lastKnownMode- ? resolveModeForRuntimeAdapter(modeAdapter, lastKnownMode)- : getDefaultModeForRuntimeAdapter(modeAdapter)- if (values.selectedMode !== activeMode) {- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {- jsonrpc: '2.0',- method: 'set_config_option',- params: { configId: MODE_CONFIG_ID, value: values.selectedMode },- })- if (!isCurrent()) {- return+ if (!isPiTaskRuntime(props.taskRuntime)) {+ const modeAdapter = props.currentRuntimeAdapter ?? RuntimeAdapterEnumApi.Claude+ const lastKnownMode =+ values.sentMode ??+ getModeOption(values.currentMode)?.value ??+ getModeOption(props.currentMode)?.value+ const activeMode = lastKnownMode+ ? resolveModeForRuntimeAdapter(modeAdapter, lastKnownMode)+ : getDefaultModeForRuntimeAdapter(modeAdapter)+ if (values.selectedMode !== activeMode) {+ await setConfigOption(MODE_CONFIG_ID, values.selectedMode)+ if (!isCurrent()) {+ return+ }}+ actions.setSentMode(values.selectedMode)}- actions.setSentMode(values.selectedMode)// A drain carries the files queued with its text, not whatever the composer holds now.const sending = source === 'queue' ? values.queuedAttachments : values.stagedAttachmentslet artifactIds: string[] = []@@ -1478,7 +1503,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// The new model may not support the current effort — clamp the override so it never holds an// unsupported value. No network here: the pick is synced to the agent at send time.setModel: ({ model }) => {- const currentEffort = values.effortOverride ?? props.currentEffort+ const currentEffort = values.effortOverride ?? props.currentEffort ?? values.sessionBaseline.effortconst resolvedEffort = resolveEffortForModel(values.catalogue, currentEffort, model)if (resolvedEffort !== currentEffort) {actions.setEffort(resolvedEffort)@@ -1541,20 +1566,29 @@ export const runInteractionLogic = kea<runInteractionLogicType>([// from the finished run so the new run continues the thread, and carrying the picked model /// reasoning effort (the resume schema can't, so we send the Claude create shape). The response// carries the new run as `run`; the consumer-provided `onRunStarted` re-points to it.+ const resumeRequest = {+ resume_from_run_id: props.runId,+ pending_user_message: wrapWithPosthogContext(content, pendingContext),+ }const codexModelAccess = pickedCodexModelAccess(getRuntimeAdapterForModel(values.catalogue, values.selectedModel))- const createRequest = buildRunCreateRequest(- values.catalogue,- values.selectedModel,- values.selectedEffort,- values.selectedMode,- {- resume_from_run_id: props.runId,- pending_user_message: wrapWithPosthogContext(content, pendingContext),- ...(codexModelAccess ? { codex_model_access: codexModelAccess } : {}),- }- )+ const createRequest = isPiTaskRuntime(props.taskRuntime)+ ? {+ ...resumeRequest,+ ...(values.modelOverride ? { model: values.selectedModel } : {}),+ ...(values.effortOverride ? { reasoning_effort: values.selectedEffort } : {}),+ }+ : buildRunCreateRequest(+ values.catalogue,+ values.selectedModel,+ values.selectedEffort,+ values.selectedMode,+ {+ ...resumeRequest,+ ...(codexModelAccess ? { codex_model_access: codexModelAccess } : {}),+ }+ )// The task already exists here, so staged artifacts hold the files whether this request// activates a warm run or cold-boots one.// The queue rides along into the run this send starts, so its files come too.diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 10b1691f5010..41fe317871d8 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -1364,6 +1364,127 @@ describe('runStreamLogic', () => {})})+ describe('Pi runtime', () => {+ const piEvent = (+ event: Record<string, unknown>,+ eventId: string,+ extra: Record<string, unknown> = {}+ ): object => ({+ type: 'pi_event',+ timestamp: '2026-01-01T00:00:00Z',+ event_id: eventId,+ event,+ ...extra,+ })++ it('replays a run log written before Pi runs used ACP', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ { type: 'pi_run_started', runId: 'run-1', taskId: 'task-1', timestamp: '2026-01-01T00:00:00Z' },+ piEvent(+ { type: 'user_message', id: 'u1', timestamp: 1, content: [{ type: 'text', text: 'fix it' }] },+ 'b-1'+ ),+ piEvent(+ { type: 'assistant_message_chunk', timestamp: 2, content: { type: 'text', text: 'On ' } },+ 'b-2'+ ),+ piEvent(+ { type: 'assistant_message_chunk', timestamp: 2, content: { type: 'text', text: 'it' } },+ 'b-3'+ ),+ piEvent(+ {+ type: 'tool_call_started',+ timestamp: 3,+ toolCall: {+ id: 't1',+ name: 'read',+ title: 'read',+ kind: 'read',+ status: 'pending',+ rawInput: { path: 'a.ts' },+ _meta: { posthog: { toolName: 'Read' } },+ },+ },+ 'b-4'+ ),+ piEvent(+ { type: 'tool_call_updated', timestamp: 4, toolCall: { id: 't1', status: 'completed' } },+ 'b-6',+ {+ covered_event_ids: ['b-5'],+ }+ ),+ piEvent({ type: 'turn_completed', timestamp: 5, stopReason: 'end_turn' }, 'b-7'),+ ] as any)+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems.map((item) => [item.type, item.text])).toEqual([+ ['human_message', 'fix it'],+ ['assistant_message', 'On it'],+ ['tool_invocation', undefined],+ ['turn_separator', undefined],+ ])+ const invocation = logic.values.toolInvocations.get('t1')+ expect(invocation?.status).toBe('completed')+ expect(resolveToolCall(invocation!).resolvedKey).toBe('Read')+ })++ it.each([+ { caseName: 'hides a replayed request that a later turn end already closed', eventId: 'b-2', shown: false },+ { caseName: 'shows a request raised after the last turn end', eventId: 'b-4', shown: true },+ ])('$caseName', async ({ eventId, shown }) => {+ let resolveLogs: (entries: unknown[]) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise<unknown[]>((resolve) => (resolveLogs = resolve)) as any+ )+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', taskRuntime: 'pi' })+ await flushPromises()+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(+ {+ type: 'permission_request',+ event_id: eventId,+ requestId: 'mcp-1',+ toolCall: { toolCallId: 'mcp-1', _meta: { posthog: { toolName: 'mcp__linear__create_issue' } } },+ options: [+ { optionId: 'allow_always', name: 'Always allow', kind: 'allow_always' },+ { optionId: 'reject', name: 'Reject', kind: 'reject_once' },+ ],+ },+ '1700-0'+ )++ resolveLogs([+ { ...notification('_posthog/run_started', { runId: 'run-1' }), event_id: 'b-1' },+ { ...notification('_posthog/turn_complete', { stopReason: 'end_turn' }), event_id: 'b-3' },+ ])+ await flushPromises()++ expect(logic.values.pendingPermissionRequest?.requestId ?? null).toBe(shown ? 'mcp-1' : null)+ })++ it('drops a live tool update that the persisted log already covers', () => {+ const persisted: StoredLogEntry = {+ ...sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' }),+ event_id: 'b-6',+ covered_event_ids: ['b-5'],+ }+ const liveEarlier: StoredLogEntry = {+ ...sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'in_progress' }),+ event_id: 'b-5',+ }++ const log = reconcileRunLog([persisted], [], [liveEarlier])++ expect(log.entries.map(({ entry }) => entry.event_id)).toEqual(['b-6'])+ })+ })+describe('turn trace ids', () => {const TRACE = '1d223305-d7ca-bfeb-3775-a4a15a6a31c6'@@ -1541,6 +1662,41 @@ describe('runStreamLogic', () => {])})+ it('reads the attachments of a Pi prompt from the links the Pi server writes', () => {+ const items = foldReplay([+ {+ ...notification('_posthog/user_message', {+ messageId: 'u1',+ content: [+ { type: 'text', text: 'Look here' },+ {+ type: 'resource_link',+ uri: 'file:///tmp/workspace/.posthog/attachments/run-7/art-1/report.csv',+ name: 'report.csv',+ },+ {+ type: 'resource_link',+ uri: 'file:///tmp/workspace/.posthog/attachments/run-7/art-2/shot.png',+ name: 'shot.png',+ mimeType: 'image/png',+ },+ ],+ }),+ source_run_id: 'run-7',+ },+ ])++ expect(items.filter((item) => item.type === 'human_message')).toEqual([+ expect.objectContaining({+ text: 'Look here',+ attachments: [+ { name: 'report.csv', taskId: 'task-3', runId: 'run-7', artifactId: 'art-1' },+ { name: 'shot.png', taskId: 'task-3', runId: 'run-7', artifactId: 'art-2' },+ ],+ }),+ ])+ })+it('leaves a path outside the attachments layout without ids', () => {const items = foldReplay([sessionUpdate({@@ -5119,6 +5275,26 @@ describe('runStreamLogic', () => {})})+ it('keeps the text of an extension notice on its status item', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/status', {+ status: 'extension_notice',+ isComplete: true,+ message: 'lint.ts failed during tool_call: crashed',+ })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([+ expect.objectContaining({+ type: 'status',+ status: 'extension_notice',+ message: 'lint.ts failed during tool_call: crashed',+ }),+ ])+ })+describe('/clear inline items', () => {it('replaces the in-progress clearing spinner with the conversation_cleared divider', async () => {await expectLogic(logic, () => {@@ -5363,14 +5539,18 @@ describe('runStreamLogic', () => {})describe('reset clears notification state', () => {- it('clears contextUsage and sdkSession on reset', async () => {+ it('clears contextUsage, sdkSession and the Pi runtime on reset', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.mocked(tasksRunsRetrieve).mockResolvedValue({ status: 'completed' } as any)await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', taskRuntime: 'pi' })logic.actions.ingestAcpFrame(notification('_posthog/usage_update', { used: { inputTokens: 1 } }))logic.actions.ingestAcpFrame(notification('_posthog/sdk_session', { adapter: 'codex' }))}).toFinishAllListeners()expect(logic.values.contextUsage).not.toBeNull()expect(logic.values.sdkSession).not.toBeNull()+ expect(logic.values.piRuntime).toBe(true)await expectLogic(logic, () => {logic.actions.reset()@@ -5378,6 +5558,7 @@ describe('runStreamLogic', () => {expect(logic.values.contextUsage).toBeNull()expect(logic.values.sdkSession).toBeNull()+ expect(logic.values.piRuntime).toBe(false)})})diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 508c69e9f5e7..e872fee45fed 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -2,6 +2,9 @@ import { type EventSourceMessage, createParser } from 'eventsource-parser'import { MakeLogicType, getContext, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import posthog from 'posthog-js'+import { agentConversationEventToAcpNotification } from '@posthog/agent-contracts/acp-conversation'+import type { AgentConversationEvent } from '@posthog/agent-contracts/agent-conversation'+import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast'@@ -15,9 +18,11 @@ import {tasksRunsRetrieve,tasksRunsStreamTokenRetrieve,} from 'products/tasks/frontend/generated/api'-import type {- TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,- TaskRunDetailDTOApi,+import {+ type TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi,+ type TaskRunCommandRequestApi,+ type TaskRunDetailDTOApi,+ TaskRuntimeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'import type { FeatureFlagsSet } from '../../../../frontend/src/lib/logic/featureFlagLogic'@@ -481,10 +486,53 @@ function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)}+const LEGACY_PI_ENTRY_TYPES = new Set([+ 'pi_event',+ 'pi_run_started',+ 'pi_extension_event',+ 'extension_ui_request',+ 'extension_ui_response',+ 'extension_error',+])++function isLegacyPiEntry(entry: unknown): entry is Record<string, unknown> {+ return isRecord(entry) && LEGACY_PI_ENTRY_TYPES.has(String(entry.type))+}++function readLegacyPiEntry(entry: Record<string, unknown>): StoredLogEntry | null {+ const notification =+ entry.type === 'pi_event' && isRecord(entry.event)+ ? agentConversationEventToAcpNotification(entry.event as unknown as AgentConversationEvent)+ : entry.type === 'pi_run_started'+ ? { method: '_posthog/run_started', params: { runId: entry.runId, taskId: entry.taskId } }+ : null+ if (!notification) {+ return null+ }+ const update = notification.params.update+ if (isRecord(update) && update.title === update.name) {+ delete update.title+ }+ const coveredEventIds = Array.isArray(entry.covered_event_ids)+ ? entry.covered_event_ids.filter((id): id is string => typeof id === 'string' && id !== '')+ : []+ return {+ type: 'notification',+ ...(typeof entry.timestamp === 'string' ? { timestamp: entry.timestamp } : {}),+ ...(typeof entry.event_id === 'string' && entry.event_id ? { event_id: entry.event_id } : {}),+ ...(typeof entry.source_run_id === 'string' ? { source_run_id: entry.source_run_id } : {}),+ ...(coveredEventIds.length > 0 ? { covered_event_ids: coveredEventIds } : {}),+ notification: notification as StoredLogEntry['notification'],+ }+}+function normalizeNotificationEntry(entry: unknown): StoredLogEntry | null {if (isNotificationFrame(entry)) {return entry}+ if (isLegacyPiEntry(entry)) {+ return readLegacyPiEntry(entry)+ }// Older append_log callers wrote `{ notification }` directly, without the stream envelope.if (!isRecord(entry) || !isRecord(entry.notification)) {@@ -801,13 +849,14 @@ function parsePermissionOption(raw: unknown): PermissionOption | null {return null}const meta = r._meta- const customInput =- typeof meta === 'object' && meta !== null && (meta as Record<string, unknown>).customInput === true+ const metaRecord = typeof meta === 'object' && meta !== null ? (meta as Record<string, unknown>) : {}+ const customInput = metaRecord.customInput === truereturn {optionId,name: String(r.name ?? ''),kind,customInput,+ ...(typeof metaRecord.hint === 'string' && metaRecord.hint ? { hint: metaRecord.hint } : {}),}}@@ -1095,6 +1144,9 @@ function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: Storecontinue}eventIds.set(JSON.stringify([entry.source_run_id, entry.event_id]), index)+ for (const coveredId of entry.covered_event_ids ?? []) {+ eventIds.set(JSON.stringify([entry.source_run_id, coveredId]), index)+ }if (!isAgentMessageEntry(entry) || typeof entry.first_event_id !== 'string' || !entry.first_event_id) {continue}@@ -1190,6 +1242,9 @@ class RunEventCoverage {return}this.ids.add(JSON.stringify([entry.source_run_id, entry.event_id]))+ for (const coveredId of entry.covered_event_ids ?? []) {+ this.ids.add(JSON.stringify([entry.source_run_id, coveredId]))+ }// Neutral notifications can occur inside a coalesced text range without being superseded.if (!isAgentMessageEntry(entry)) {return@@ -1259,6 +1314,20 @@ class RunEventCoverage {}}+function permissionEndedByLaterTurn(eventId: unknown, sourceRunId: string | undefined, log: RunLog): boolean {+ const position = typeof eventId === 'string' ? parseAgentEventId(eventId) : null+ if (!position) {+ return false+ }+ return log.entries.some(({ entry }) => {+ if (entry.notification.method !== '_posthog/turn_complete' || entry.source_run_id !== sourceRunId) {+ return false+ }+ const end = entry.event_id ? parseAgentEventId(entry.event_id) : null+ return !!end && end.boot === position.boot && end.sequence > position.sequence+ })+}+function compareEntryPosition(left: StoredLogEntry, right: StoredLogEntry): number {const a = eventPosition(left)const b = eventPosition(right)@@ -2080,12 +2149,14 @@ export function foldLogFromCheckpoint(if (method === '_posthog/status') {const status = String(params.status ?? '')const isComplete = params.isComplete === true- if (isComplete && (status === 'compacting' || status === 'clearing')) {+ if (isComplete && (status === 'compacting' || status === 'clearing' || status === 'retrying')) {items = items.filter((item) => !isPendingStatus(item, status))- } else if (status === 'clearing_failed') {+ } else if (status === 'clearing_failed' || status === 'compacting_failed') {// A failed clear emits no `conversation_cleared` marker, so retire the spinner// here and report the outcome in its place.- items = items.filter((item) => !isPendingStatus(item, 'clearing'))+ items = items.filter(+ (item) => !isPendingStatus(item, status === 'clearing_failed' ? 'clearing' : 'compacting')+ )items.push({id: `status-${statusSeq++}`,type: 'status',@@ -2093,6 +2164,14 @@ export function foldLogFromCheckpoint(isComplete: true,errorMessage: stringifyOptional(params.error),})+ } else if (status === 'extension_notice') {+ items.push({+ id: `status-${statusSeq++}`,+ type: 'status',+ status,+ isComplete: true,+ message: stringifyOptional(params.message),+ })} else {items.push({ id: `status-${statusSeq++}`, type: 'status', status, isComplete })}@@ -2316,6 +2395,7 @@ export interface runStreamLogicValues {pendingPermissionRequest: PermissionRequestRecord | nullpendingRunMessage: PendingRunMessage | nullpermissionResponseRequestIds: Set<string>+ piRuntime: booleanreconnectAttempt: numberrecoveryState: {attempt: number@@ -2395,12 +2475,14 @@ export interface runStreamLogicActions {retainedMessage?: stringrunId: stringtaskId: string+ taskRuntime?: string | nulltraceId?: string}) => {justCreatedRun?: boolean | undefinedretainedMessage?: string | undefinedrunId: stringtaskId: string+ taskRuntime?: string | null | undefinedtraceId?: string | undefined}cancelPermissionDelivery: () => {@@ -2784,6 +2866,7 @@ export const runStreamLogic = kea<runStreamLogicType>([justCreatedRun?: booleantraceId?: stringretainedMessage?: string+ taskRuntime?: string | null}) => payload,openSseForRun: (payload: { taskId: string; runId: string; startLatest?: boolean; traceId?: string }) => payload,/**@@ -3114,6 +3197,14 @@ export const runStreamLogic = kea<runStreamLogicType>([reset: () => null,},],+ piRuntime: [+ false,+ {+ bootstrapRun: (state, { taskRuntime }) =>+ taskRuntime === undefined ? state : taskRuntime === TaskRuntimeEnumApi.Pi,+ reset: () => false,+ },+ ],// The task id this instance last bootstrapped, so the `ingestAcpFrame` history-derived context// bookkeeping can attribute seen context blocks to the task. Null for an unattached optimistic// stream — those record nothing (their send path marks sent keys directly).@@ -3838,6 +3929,7 @@ export const runStreamLogic = kea<runStreamLogicType>([const bufferedIds = new Set(session.buffer.flatMap((entry) => (entry.event_id ? [entry.event_id] : [])))// Rebuild state without publishing a partial transcript or repeating live reactions.cache.rebuildingHistory = true+ cache.rebuildingLog = logcache.trackedToolInvocations = undefinedtry {let reachedSuccessor = false@@ -3864,6 +3956,7 @@ export const runStreamLogic = kea<runStreamLogicType>([}} finally {cache.rebuildingHistory = false+ cache.rebuildingLog = undefined}actions.replaceLog(log)cache.eventCoverage = new RunEventCoverage([@@ -4122,6 +4215,9 @@ export const runStreamLogic = kea<runStreamLogicType>([} catch {return}+ if (isLegacyPiEntry(parsed)) {+ parsed = readLegacyPiEntry(parsed)+ }if (isNotificationFrame(parsed)) {const marker =parsed.notification.method === '_posthog/run_started'@@ -4174,7 +4270,8 @@ export const runStreamLogic = kea<runStreamLogicType>([if (record &&!values.seenPermissionRequestIds.has(record.requestId) &&- !values.resolvedPermissionRequestIds.has(record.requestId)+ !values.resolvedPermissionRequestIds.has(record.requestId) &&+ !permissionEndedByLaterTurn(parsed.event_id, runId, values.log)) {actions.routePermissionRequest(record)}@@ -4203,14 +4300,21 @@ export const runStreamLogic = kea<runStreamLogicType>([try {let response: Responsefor (;;) {- const proxyTarget = values.streamViaProxyEnabled- ? await session.request(- STREAM_REQUEST_TIMEOUT_MS,- (signal) =>- resolveStreamTarget(String(session.projectId), taskId, runId, true, signal),- controller.signal- )- : null+ const proxyTarget =+ values.streamViaProxyEnabled || values.piRuntime+ ? await session.request(+ STREAM_REQUEST_TIMEOUT_MS,+ (signal) =>+ resolveStreamTarget(+ String(session.projectId),+ taskId,+ runId,+ true,+ signal+ ),+ controller.signal+ )+ : nullif (!ownsStream()) {return}@@ -4498,26 +4602,22 @@ export const runStreamLogic = kea<runStreamLogicType>([key,{ pauseOnPageHidden: false })- const params = {- requestId: record.requestId,- optionId,- customInput,- answers: answers ? { ...answers } : undefined,+ const body: TaskRunCommandRequestApi = {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: {+ requestId: record.requestId,+ optionId,+ customInput,+ answers: answers ? { ...answers } : undefined,+ },}try {await deliverPermissionResponse((signal) =>- tasksRunsCommandCreate(- String(projectId),- activeRun.taskId,- activeRun.runId,- {- jsonrpc: '2.0',- method: 'permission_response',- params,- },- { signal }- ),+ tasksRunsCommandCreate(String(projectId), activeRun.taskId, activeRun.runId, body, {+ signal,+ }),controller.signal)if (!controller.signal.aborted && !disposables.isDisposed) {@@ -4897,6 +4997,7 @@ export const runStreamLogic = kea<runStreamLogicType>([run_id: activeRun?.runId,task_id: activeRun?.taskId,execution_type: 'sandbox',+ task_runtime: values.piRuntime ? TaskRuntimeEnumApi.Pi : TaskRuntimeEnumApi.Acp,// The run-started frame carries no warmth signal and pre-warming isn't wired// yet, so every run is a cold start. A later pre-warm hook flips this.cold_start: true,@@ -4968,7 +5069,12 @@ export const runStreamLogic = kea<runStreamLogicType>([if (record &&!values.seenPermissionRequestIds.has(record.requestId) &&- !values.resolvedPermissionRequestIds.has(record.requestId)+ !values.resolvedPermissionRequestIds.has(record.requestId) &&+ !permissionEndedByLaterTurn(+ entry.event_id ?? notification.params?.event_id,+ entry.source_run_id,+ (cache.rebuildingLog as RunLog | undefined) ?? values.log+ )) {actions.routePermissionRequest(record, isReplay)}diff --git a/products/posthog_ai/frontend/policy/permissionOptionCopy.ts b/products/posthog_ai/frontend/policy/permissionOptionCopy.tsindex 430431f44915..3e6a34cac64c 100644--- a/products/posthog_ai/frontend/policy/permissionOptionCopy.ts+++ b/products/posthog_ai/frontend/policy/permissionOptionCopy.ts@@ -17,6 +17,9 @@ export function optionRowLabel(option: ApprovalCardOption): string {}export function optionSublabel(option: ApprovalCardOption): string | null {+ if (option.hint) {+ return option.hint+ }if (option.requiresFeedback) {return 'The agent adjusts and continues instead of stopping this turn.'}diff --git a/products/posthog_ai/frontend/policy/permissionUtils.test.ts b/products/posthog_ai/frontend/policy/permissionUtils.test.tsindex 2a29b075fd31..1393e1494d3a 100644--- a/products/posthog_ai/frontend/policy/permissionUtils.test.ts+++ b/products/posthog_ai/frontend/policy/permissionUtils.test.ts@@ -21,6 +21,14 @@ describe('permissionUtils', () => {expect(mapPermissionOption({ optionId: 'x', name: '', kind })).toMatchObject(expected)})+ it.each(['allow_once', 'reject_once'])('carries the option hint for %s onto the card model', (kind) => {+ expect(+ mapPermissionOption({ optionId: 'x', name: 'X', kind, hint: 'The agent keeps working.' })+ ).toMatchObject({+ hint: 'The agent keeps working.',+ })+ })+it('treats reject_once as a one-click decline that supports optional feedback via customInput', () => {expect(mapPermissionOption({ optionId: 'r', name: 'No', kind: 'reject_once', customInput: true })diff --git a/products/posthog_ai/frontend/policy/permissionUtils.ts b/products/posthog_ai/frontend/policy/permissionUtils.tsindex 6e47991bd54e..9a4e66e43c86 100644--- a/products/posthog_ai/frontend/policy/permissionUtils.ts+++ b/products/posthog_ai/frontend/policy/permissionUtils.ts@@ -39,6 +39,7 @@ export interface ApprovalCardOption {requiresFeedback: boolean/** `reject_once` carrying `_meta.customInput` — a one-click decline that ALSO offers an optional feedback input. */supportsFeedback: boolean+ hint?: string}/**@@ -59,6 +60,7 @@ export function mapPermissionOption(option: PermissionOption): ApprovalCardOptioremembered,requiresFeedback: false,supportsFeedback: false,+ ...(option.hint ? { hint: option.hint } : {}),}}@@ -74,6 +76,7 @@ export function mapPermissionOption(option: PermissionOption): ApprovalCardOptioremembered: false,requiresFeedback,supportsFeedback: !requiresFeedback && option.customInput === true,+ ...(option.hint ? { hint: option.hint } : {}),}}diff --git a/products/posthog_ai/frontend/policy/questionUtils.ts b/products/posthog_ai/frontend/policy/questionUtils.tsindex 768cbadcdfb3..7301651804b3 100644--- a/products/posthog_ai/frontend/policy/questionUtils.ts+++ b/products/posthog_ai/frontend/policy/questionUtils.ts@@ -26,6 +26,9 @@ export interface AgentQuestion {header?: stringmultiSelect: booleanoptions: AgentQuestionOption[]+ placeholder?: string+ defaultAnswer?: string+ multiline?: boolean}function asRecord(value: unknown): Record<string, unknown> | null {@@ -59,6 +62,9 @@ function parseQuestionItem(record: Record<string, unknown>): AgentQuestion | nulheader: typeof record.header === 'string' && record.header ? record.header : undefined,multiSelect: record.multiSelect === true,options: parseOptions(record.options),+ ...(typeof record.placeholder === 'string' && record.placeholder ? { placeholder: record.placeholder } : {}),+ ...(typeof record.defaultAnswer === 'string' ? { defaultAnswer: record.defaultAnswer } : {}),+ ...(record.multiline === true ? { multiline: true } : {}),}}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsxindex f8c02a76cd25..9d26e464aa58 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskTracker.stories.tsx@@ -123,6 +123,110 @@ const TASKS: Task[] = [},]+const PI_TASK_RUN = mockRun('task-4', TaskRunStatus.COMPLETED, '2024-01-15T10:05:00Z', '2024-01-15T10:12:00Z')++const PI_TASK: Task = {+ id: 'task-4',+ task_number: 4,+ slug: 'TASK-4',+ title: 'Rename the export button label',+ description: 'Change the export button label to sentence case.',+ origin_product: OriginProduct.USER_CREATED,+ runtime: TaskRuntimeEnumApi.Pi,+ repository: 'PostHog/posthog',+ github_integration: 1,+ signal_report: null,+ json_schema: null,+ internal: false,+ latest_run: PI_TASK_RUN,+ created_at: '2024-01-15T10:00:00Z',+ updated_at: '2024-01-15T10:12:00Z',+ created_by: CREATED_BY,+}++const piLogEntry = (eventId: string, event: Record<string, unknown>): Record<string, unknown> => ({+ type: 'pi_event',+ timestamp: '2024-01-15T10:06:00Z',+ event_id: `pi-boot-${eventId}`,+ event,+})++const PI_TASK_LOG = [+ { type: 'pi_run_started', timestamp: '2024-01-15T10:05:30Z', taskId: 'task-4', runId: 'run-task-4' },+ piLogEntry('1', {+ type: 'user_message',+ id: 'pi-user-1',+ timestamp: 1,+ content: [{ type: 'text', text: 'Change the export button label to sentence case.' }],+ }),+ piLogEntry('2', {+ type: 'assistant_thought_chunk',+ timestamp: 2,+ content: { type: 'text', text: 'Find the button label first.' },+ }),+ piLogEntry('3', {+ type: 'tool_call_started',+ timestamp: 3,+ toolCall: {+ id: 'pi-tool-read',+ name: 'read',+ title: 'read',+ kind: 'read',+ status: 'pending',+ rawInput: { path: 'frontend/src/scenes/insights/ExportButton.tsx' },+ locations: [{ path: 'frontend/src/scenes/insights/ExportButton.tsx' }],+ },+ }),+ piLogEntry('4', { type: 'tool_call_updated', timestamp: 4, toolCall: { id: 'pi-tool-read', status: 'completed' } }),+ piLogEntry('5', {+ type: 'tool_call_started',+ timestamp: 5,+ toolCall: {+ id: 'pi-tool-edit',+ name: 'edit',+ title: 'edit',+ kind: 'edit',+ status: 'pending',+ rawInput: { path: 'frontend/src/scenes/insights/ExportButton.tsx' },+ },+ }),+ piLogEntry('6', {+ type: 'tool_call_updated',+ timestamp: 6,+ toolCall: {+ id: 'pi-tool-edit',+ status: 'completed',+ content: [+ {+ type: 'diff',+ path: 'frontend/src/scenes/insights/ExportButton.tsx',+ oldText: '<LemonButton>Export As CSV</LemonButton>',+ newText: '<LemonButton>Export as CSV</LemonButton>',+ },+ ],+ },+ }),+ piLogEntry('7', {+ type: 'tool_call_started',+ timestamp: 7,+ toolCall: {+ id: 'pi-tool-bash',+ name: 'bash',+ title: 'bash',+ kind: 'execute',+ status: 'pending',+ rawInput: { command: 'pnpm --filter=@posthog/frontend format' },+ },+ }),+ piLogEntry('8', { type: 'tool_call_updated', timestamp: 8, toolCall: { id: 'pi-tool-bash', status: 'completed' } }),+ piLogEntry('9', {+ type: 'assistant_message_chunk',+ timestamp: 9,+ content: { type: 'text', text: 'The export button now reads "Export as CSV".' },+ }),+ piLogEntry('10', { type: 'turn_completed', timestamp: 10, stopReason: 'end_turn' }),+]+const listResponse = (results: Task[]): Record<string, unknown> => ({count: results.length,next: null,@@ -262,6 +366,28 @@ export const CloudTaskSelected: Story = {],}+export const PiTaskSelected: Story = {+ parameters: {+ pageUrl: taskDetailUrl('task-4'),+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/tasks/task-4/': PI_TASK,+ '/api/projects/:team_id/tasks/task-4/runs/': {+ count: 1,+ next: null,+ previous: null,+ results: [PI_TASK_RUN],+ },+ '/api/projects/:team_id/tasks/task-4/runs/run-task-4/': PI_TASK_RUN,+ '/api/projects/:team_id/tasks/task-4/runs/run-task-4/logs': () =>+ new HttpResponse(PI_TASK_LOG.map((entry) => JSON.stringify(entry)).join('\n')),+ },+ }),+ ],+}+export const NewTask: Story = {parameters: {pageUrl: taskNewUrl(),diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsxindex 0a2171c0b19e..3bd9d13a57ed 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx@@ -33,6 +33,7 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPagconst isActiveCreation = activeCreation?.taskId === taskIdconst artifactsTabEnabled = useFeatureFlag('TODAY_RAIL_NAV')const skin = useThreadSkin()+ const piAcpEnabled = useFeatureFlag('PI_ACP')if (taskNotFound && !task) {return <NotFound object="task" />@@ -53,7 +54,8 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPagupdateTask({ data: { title: nextTitle } })}}- const canRun = !!task && !isPiTaskRuntime(task.runtime) && !isLatestRunInProgress && !isLatestRunCompleted+ const canRun =+ !!task && (!isPiTaskRuntime(task.runtime) || piAcpEnabled) && !isLatestRunInProgress && !isLatestRunCompletedconst taskActions =isHeaderLoading || !task ? (isActiveCreation ? undefined : (diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex bd14f936a732..ac5e0c3d5d77 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -99,6 +99,7 @@ export function TaskRunChat({typeof runConfig?.state?.codex_model_access === 'string'? runConfig.state.codex_model_access: pendingInteraction?.props.currentCodexModelAccess,+ taskRuntime: task?.runtime ?? pendingInteraction?.props.taskRuntime,onRunStarted: (newRunId, handoff) => {if (handoff) {continueWithRun(handoff)diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsxindex b68526a35b96..d4c4d33ce975 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx@@ -16,7 +16,11 @@ import { QueuedMessageList, useThreadSkin } from 'products/posthog_ai/frontend/aimport { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'import { runSlashCommandsLogic } from 'products/posthog_ai/frontend/logics/runSlashCommandsLogic'import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'-import { getRuntimeAdapterForModel, pickerModels } from 'products/posthog_ai/frontend/utils/composerModels'+import {+ getRuntimeAdapterForModel,+ PI_DEFAULT_MODEL,+ pickerModels,+} from 'products/posthog_ai/frontend/utils/composerModels'import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/frontend/utils/composerModes'import { ModelAccessEnumApi } from 'products/tasks/frontend/generated/api.schemas'@@ -39,6 +43,7 @@ import { QuillAttachedContextPicker } from '../../../components/quill/QuillAttacimport { QuillComposerAttachButton } from '../../../components/quill/QuillComposerAttachButton'import { QuillComposerLayout } from '../../../components/quill/QuillComposerLayout'import { QuillComposerSendButton } from '../../../components/quill/QuillComposerSendButton'+import { isPiTaskRuntime } from '../../../types/taskTypes'export function TaskRunComposer({logicProps,@@ -73,13 +78,14 @@ export function TaskRunComposer({const { slashCommands, commandResult } = useValues(runSlashCommandsLogic(logicProps))const { submitComposer, dismissCommandResult } = useActions(runSlashCommandsLogic(logicProps))const { catalogue } = useValues(modelCatalogueLogic)+ const isPiTask = isPiTaskRuntime(logicProps.taskRuntime)const offeredModels = useMemo(() => pickerModels(catalogue, selectedModel), [catalogue, selectedModel])const { user } = useValues(userLogic)const { currentProjectId } = useValues(projectLogic)const { myConfigLoading } = useValues(taskRunDefaultsLogic)// A live run's harness is whatever it booted on; once terminal the next run follows the picked model.const composerAdapter = logicProps.currentRuntimeAdapter ?? getRuntimeAdapterForModel(catalogue, selectedModel)- const controlsReady = isTerminal || !!logicProps.currentRuntimeAdapter+ const controlsReady = isTerminal || isPiTask || !!logicProps.currentRuntimeAdapterconst {setComposerFormValues,enableTaskDraftPersistence,@@ -128,7 +134,7 @@ export function TaskRunComposer({: 'Send a follow-up message, or type / for commands…'// Selection lives in the bound runInteractionLogic and is applied when the message is sent — synced to the// running agent on a follow-up, or used to seed the next run once terminal.- const modePicker = (+ const modePicker = isPiTask ? null : (<ComposerModePickerselectedMode={selectedMode}onModeChange={setMode}@@ -138,28 +144,31 @@ export function TaskRunComposer({const modelPickerProps: ComposerModelEffortPickersProps = {models: offeredModels,selectedModel,- defaultModel,- isDefaultModelLoading: myConfigLoading,+ defaultModel: isPiTask ? PI_DEFAULT_MODEL : defaultModel,+ isDefaultModelLoading: !isPiTask && myConfigLoading,selectedEffort,onModelChange: setModel,onEffortChange: setEffort,+ taskRuntime: logicProps.taskRuntime,// While the run is live its harness is fixed to whatever the sandbox booted; once// terminal the next send starts a fresh run, which may pick any harness.lockedRuntimeAdapter: isTerminal ? null : logicProps.currentRuntimeAdapter,- onOpenDefaultSettings: () =>- router.actions.push(urls.settings('environment-task-agents', 'task-agent-my-preference')),+ onOpenDefaultSettings: isPiTask+ ? undefined+ : () => router.actions.push(urls.settings('environment-task-agents', 'task-agent-my-preference')),phoneSheet: todayRailEnabled && phoneLayout,}- const modelPicker = codexBillingEnabled ? (- <ComposerCodexBillingPickers- {...modelPickerProps}- lockedCodexModelAccess={- isTerminal ? null : (logicProps.currentCodexModelAccess ?? ModelAccessEnumApi.PosthogGateway)- }- />- ) : (- <ComposerModelEffortPickers {...modelPickerProps} />- )+ const modelPicker =+ codexBillingEnabled && !isPiTask ? (+ <ComposerCodexBillingPickers+ {...modelPickerProps}+ lockedCodexModelAccess={+ isTerminal ? null : (logicProps.currentCodexModelAccess ?? ModelAccessEnumApi.PosthogGateway)+ }+ />+ ) : (+ <ComposerModelEffortPickers {...modelPickerProps} />+ )const field = (<ComposerCommandMenu commands={slashCommands}><Composer.Field>@@ -168,7 +177,7 @@ export function TaskRunComposer({</Composer.Field></ComposerCommandMenu>)- const pickers = (first: JSX.Element, second: JSX.Element): JSX.Element => (+ const pickers = (first: JSX.Element | null, second: JSX.Element | null): JSX.Element => (<fieldset disabled={!controlsReady} className="flex flex-wrap items-center gap-1 border-0 p-0 m-0 min-w-0">{first}{second}@@ -199,7 +208,7 @@ export function TaskRunComposer({return (<div onFocusCapture={() => setComposerFocused(true)} onBlurCapture={() => setComposerFocused(false)}><ComposerModeShortcut- disabled={!composerActive || !controlsReady}+ disabled={isPiTask || !composerActive || !controlsReady}onCycle={() => setMode(cycleMode(composerAdapter, selectedMode))}/><Composer.Rootdiff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.tsindex 4439010445ad..67fad9c31b5c 100644--- a/products/posthog_ai/frontend/types/streamTypes.ts+++ b/products/posthog_ai/frontend/types/streamTypes.ts@@ -174,6 +174,8 @@ export interface ThreadItem {toolCallId?: string/** For `error` items, and for `status` items whose status is a `*_failed` phase. */errorMessage?: string+ /** For `status` items that carry a notice to show as-is, such as an extension's warning. */+ message?: string/*** For `error` items — distinguishes a friendlier agent-crash affordance (`crash`) from a* raw error line (`error`, the default). Drives the copy/styling branch in the renderer.diff --git a/products/posthog_ai/frontend/types/toolTypes.ts b/products/posthog_ai/frontend/types/toolTypes.tsindex 665a99ff708e..792f281f2374 100644--- a/products/posthog_ai/frontend/types/toolTypes.ts+++ b/products/posthog_ai/frontend/types/toolTypes.ts@@ -16,6 +16,8 @@ export interface ToolCallMessage {rawInput: Record<string, unknown>/** JSON-parsed inner args when `innerToolName` is set. */innerInput?: Record<string, unknown>+ /** The MCP tool a Pi proxy call names while the server has not yet reported which MCP server answered it. */+ proxiedToolName?: stringrawOutput?: unknown/** Accumulated ACP `content[]`. */content: unknown[]diff --git a/products/posthog_ai/frontend/types/wireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.tsindex 654b86c0aaab..7e3775b5dd7f 100644--- a/products/posthog_ai/frontend/types/wireTypes.ts+++ b/products/posthog_ai/frontend/types/wireTypes.ts@@ -30,6 +30,7 @@ export interface StoredLogEntry {type: 'notification'event_id?: stringfirst_event_id?: string+ covered_event_ids?: string[]/** Client-side ownership; the shared backend log payload stays unchanged. */source_run_id?: stringtimestamp?: string@@ -72,11 +73,14 @@ export interface PermissionOption {kind: string/** `_meta.customInput === true` — the option accepts optional free-text feedback. */customInput?: boolean+ hint?: string+ _meta?: { customInput?: boolean; hint?: string }}/** Top-level permission frame hoisted onto the stream by the relay. */export interface PermissionRequestFrame {type: 'permission_request'+ event_id?: stringrequestId?: stringtoolCallId?: stringoptions?: PermissionOption[]diff --git a/products/posthog_ai/frontend/utils/composerModels.test.ts b/products/posthog_ai/frontend/utils/composerModels.test.tsindex a06fbfbe31a5..e833a06db3ec 100644--- a/products/posthog_ai/frontend/utils/composerModels.test.ts+++ b/products/posthog_ai/frontend/utils/composerModels.test.ts@@ -5,6 +5,7 @@ import {ModelChoiceApi,ReasoningEffortEnumApi,RuntimeAdapterEnumApi,+ TaskRuntimeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'import { DEFAULT_MODEL_BY_RUNTIME_ADAPTER, MODELS } from 'products/tasks/frontend/modelCatalog.generated'@@ -240,11 +241,14 @@ describe('composerModels', () => {// The picker groups by harness and offers one row per runtime, so both have to come off the catalogue rather// than a hardcoded list — a runtime the gateway stops serving must stop being offered.- it("derives the harness list and each harness's models from the catalogue", () => {- expect(listRuntimeAdapters(CATALOGUE)).toEqual(['claude', 'codex'])- expect(modelsForRuntimeAdapter(CATALOGUE, RuntimeAdapterEnumApi.Codex).map((o) => o.model)).toEqual([- 'gpt-5.6-luna',- ])+ it.each([+ [TaskRuntimeEnumApi.Acp, ['claude', 'codex'], ['gpt-5.6-luna']],+ [TaskRuntimeEnumApi.Pi, [], ['claude-opus-4-8', 'gpt-5.6-luna']],+ ])("derives the harness list and each harness's models from the catalogue for %s", (runtime, adapters, models) => {+ expect(listRuntimeAdapters(CATALOGUE, runtime)).toEqual(adapters)+ expect(modelsForRuntimeAdapter(CATALOGUE, RuntimeAdapterEnumApi.Codex, runtime).map((o) => o.model)).toEqual(+ models+ )})describe('pickerModels', () => {diff --git a/products/posthog_ai/frontend/utils/composerModels.ts b/products/posthog_ai/frontend/utils/composerModels.tsindex aae55ec15810..08a5aff6d660 100644--- a/products/posthog_ai/frontend/utils/composerModels.ts+++ b/products/posthog_ai/frontend/utils/composerModels.ts@@ -7,6 +7,7 @@ import {ReasoningEffortEnumApi,RuntimeAdapterEnumApi,TaskRunCreateRequestSchemaApi,+ TaskRuntimeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'import { isOfferedModel, normalizeModelId } from 'products/tasks/frontend/modelCatalog'import {@@ -33,6 +34,12 @@ const FALLBACK_EFFORTS: ReasoningEffortEnumApi[] = []export const DEFAULT_COMPOSER_MODEL = DEFAULT_MODEL_BY_RUNTIME_ADAPTER.claude+export const PI_DEFAULT_MODEL = 'gpt-5.6-terra'++/** The model a task runs on when neither the run nor the session names one. */+export function getDefaultModelForTaskRuntime(taskRuntime: TaskRuntimeEnumApi = TaskRuntimeEnumApi.Acp): string {+ return taskRuntime === TaskRuntimeEnumApi.Pi ? PI_DEFAULT_MODEL : DEFAULT_COMPOSER_MODEL+}export const DEFAULT_COMPOSER_EFFORT: ReasoningEffortEnumApi = ReasoningEffortEnumApi.Highconst EFFORT_LABELS: Record<string, string> = REASONING_EFFORT_LABELS@@ -67,14 +74,24 @@ export function getRuntimeAdapterForModel(// The harnesses the catalogue actually offers, in the order the models arrive. Derived rather than enumerated, so a// runtime the gateway stops serving disappears from the picker on its own.-export function listRuntimeAdapters(catalogue: ModelChoiceApi[]): RuntimeAdapterEnumApi[] {+export function listRuntimeAdapters(+ catalogue: ModelChoiceApi[],+ taskRuntime: TaskRuntimeEnumApi = TaskRuntimeEnumApi.Acp+): RuntimeAdapterEnumApi[] {+ if (taskRuntime === TaskRuntimeEnumApi.Pi) {+ return []+ }return [...new Set(catalogue.map((option) => option.runtime_adapter))]}export function modelsForRuntimeAdapter(catalogue: ModelChoiceApi[],- runtimeAdapter: RuntimeAdapterEnumApi+ runtimeAdapter: RuntimeAdapterEnumApi,+ taskRuntime: TaskRuntimeEnumApi = TaskRuntimeEnumApi.Acp): ModelChoiceApi[] {+ if (taskRuntime === TaskRuntimeEnumApi.Pi) {+ return catalogue+ }return catalogue.filter((option) => option.runtime_adapter === runtimeAdapter)}diff --git a/products/posthog_ai/frontend/utils/toolCallMessage.ts b/products/posthog_ai/frontend/utils/toolCallMessage.tsindex df45d6a80d43..029039a22962 100644--- a/products/posthog_ai/frontend/utils/toolCallMessage.ts+++ b/products/posthog_ai/frontend/utils/toolCallMessage.ts@@ -17,6 +17,7 @@ export function toolInvocationToMessage(invocation: ToolInvocation | undefined):claudeToolName: resolved.claudeToolName,rawInput: invocation.input,innerInput: resolved.innerInput,+ proxiedToolName: resolved.proxiedToolName,rawOutput: invocation.output,content: invocation.contentBlocks,status: invocation.status,diff --git a/products/posthog_ai/frontend/utils/toolResolver.test.ts b/products/posthog_ai/frontend/utils/toolResolver.test.tsindex fbe0e70a84d8..51ef395f7e46 100644--- a/products/posthog_ai/frontend/utils/toolResolver.test.ts+++ b/products/posthog_ai/frontend/utils/toolResolver.test.ts@@ -118,6 +118,34 @@ describe('toolResolver', () => {})})+ it.each([+ {+ caseName: 'a Pi proxy search as a tool search with the query as its input',+ meta: { posthog: { toolName: 'mcp', mcpProxy: { kind: 'search', query: 'issue' } } },+ expected: { resolvedKey: 'ToolSearch', innerInput: { query: 'issue' } },+ },+ {+ caseName: 'a Pi proxy call by the tool it names until the server reports the MCP server',+ meta: { posthog: { toolName: 'mcp', mcpProxy: { kind: 'tool', name: 'linear_create_issue' } } },+ expected: { resolvedKey: 'mcp', proxiedToolName: 'linear_create_issue' },+ },+ {+ caseName: 'a Pi proxy call by its MCP descriptor once the server reports it',+ meta: {+ posthog: {+ toolName: 'mcp__linear__create_issue',+ mcp: { server: 'linear', tool: 'create_issue' },+ mcpProxy: { kind: 'tool', name: 'linear_create_issue' },+ },+ },+ expected: { resolvedKey: 'mcp__linear__create_issue' },+ },+ ])('resolves $caseName', ({ meta, expected }) => {+ expect(+ resolveToolCall({ rawServerName: 'posthog', rawToolName: '', input: { search: 'issue' }, meta })+ ).toEqual({ ...expected, claudeToolName: undefined })+ })+it.each([[{ posthog: { mcp: { server: 'other', tool: 'exec' } } }, 'exec', 'mcp__other__exec'],[{ posthog: { toolName: 'mcp__other__exec' } }, 'exec', 'mcp__other__exec'],diff --git a/products/posthog_ai/frontend/utils/toolResolver.ts b/products/posthog_ai/frontend/utils/toolResolver.tsindex 6691846667a0..8700b2009523 100644--- a/products/posthog_ai/frontend/utils/toolResolver.ts+++ b/products/posthog_ai/frontend/utils/toolResolver.ts@@ -5,8 +5,12 @@ export interface ResolvedToolKey {resolvedKey: stringinnerToolName?: stringinnerInput?: Record<string, unknown>+ /** The MCP tool a Pi proxy call names while the server has not yet reported which MCP server answered it. */+ proxiedToolName?: string}+type McpProxyCall = { kind: 'search'; query: string } | { kind: 'tool'; name: string }+export interface ResolvableToolCall {rawServerName: stringrawToolName: string@@ -50,6 +54,24 @@ export function extractAgentToolName(meta: unknown): string | undefined {return extractClaudeToolName(meta)}+/** The structured `_meta.posthog.mcpProxy` a Pi harness puts on a call made through its `mcp` proxy tool. */+function extractMcpProxyCall(meta: unknown): McpProxyCall | undefined {+ const posthog = typeof meta === 'object' && meta !== null ? (meta as { posthog?: unknown }).posthog : undefined+ const proxy =+ typeof posthog === 'object' && posthog !== null ? (posthog as { mcpProxy?: unknown }).mcpProxy : undefined+ if (typeof proxy !== 'object' || proxy === null) {+ return undefined+ }+ const { kind, query, name } = proxy as { kind?: unknown; query?: unknown; name?: unknown }+ if (kind === 'search' && typeof query === 'string' && query) {+ return { kind, query }+ }+ if (kind === 'tool' && typeof name === 'string' && name) {+ return { kind, name }+ }+ return undefined+}+/*** Resolves the registry key for a tool call. The single-exec `posthog` MCP server exposes one* outer `exec` tool; the inner tool name is parsed out of `rawInput.command`. Non-exec MCP tools@@ -105,6 +127,15 @@ export function resolveToolCall(toolCall: ResolvableToolCall): ResolvedToolCallconst claudeToolName = extractClaudeToolName(toolCall.meta)const agentToolName = extractAgentToolName(toolCall.meta)const mcp = agentToolName?.match(/^mcp__(.+?)__(.+)$/)+ // A Pi proxy call names the MCP tool before the server reports which server answered; the+ // descriptor arrives with the result and takes over above.+ const proxy = mcp ? undefined : extractMcpProxyCall(toolCall.meta)+ if (proxy?.kind === 'search') {+ return { resolvedKey: 'ToolSearch', innerInput: { query: proxy.query }, claudeToolName }+ }+ if (proxy) {+ return { resolvedKey: agentToolName ?? toolCall.rawToolName, proxiedToolName: proxy.name, claudeToolName }+ }return {...resolveToolKey(mcp?.[1] ?? toolCall.rawServerName,diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 45678cffca08..23e9c54c20be 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -43,6 +43,7 @@ REASONING_EFFORTS = model_catalog.REASONING_EFFORTS# runtime, so the effective audience is teams with both this flag and# PI_CLOUD_RUNTIME_FEATURE_FLAG enabled.AGENT_PEER_MESSAGING_FEATURE_FLAG = "tasks-agent-peer-messaging"+PI_ACP_FEATURE_FLAG = "pi-acp"TASK_ANALYSIS_FEATURE_FLAG = "posthog-code-task-analysis"ANALYSIS_TARGET_TASK_ID_STATE_KEY = "analysis_target_task_id"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 53ef93acd378..355e5efcad87 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -342,6 +342,7 @@ __all__ = ["get_task_run_log_urls","get_task_run_log_size","read_task_run_log_content",+ "read_task_run_conversation_logs","read_task_run_logs","record_comment_activity","record_run_failure_cause",@@ -4865,6 +4866,28 @@ def read_task_run_logs(run_id: str | UUID, task_id: str | UUID, team_id: int) ->return read_task_run_log_content(log_urls)+def read_task_run_conversation_logs(run_id: str | UUID, task_id: str | UUID, team_id: int) -> str | None:+ run = _get_visible_run(run_id, task_id, team_id)+ if run is None:+ return None+ chain = run.get_history_chain()+ if len(chain) < 2 or run.task.runtime != Task.Runtime.PI:+ return read_task_run_log_content([ancestor.log_url for ancestor in chain])++ contents = _TASK_LOG_READ_EXECUTOR.map(lambda ancestor: read_task_run_log_content([ancestor.log_url]), chain)+ parts: list[str] = []+ for ancestor, content in zip(chain, contents):+ marker = {+ "type": "pi_run_started",+ "timestamp": ancestor.created_at.isoformat(),+ "taskId": str(ancestor.task_id),+ "runId": str(ancestor.id),+ }+ parts.append(json.dumps(marker) + "\n")+ parts.append(content)+ return "".join(parts)++def get_task_run_log_urls(run_id: str | UUID, task_id: str | UUID, team_id: int) -> list[str] | None:"""Log URLs across the run's resume chain (oldest ancestor first). ``None`` if the run isn't found."""run = _get_visible_run(run_id, task_id, team_id)@@ -8082,7 +8105,14 @@ def readonly_github_integration_id(team_id: int) -> int | None:return integration.integration.id if integration is not None else None-def _with_ai_run_defaults(data: dict, *, team_id: int, acting_user_id: int | None, internal: bool = False) -> dict:+def _with_ai_run_defaults(+ data: dict,+ *,+ team_id: int,+ acting_user_id: int | None,+ internal: bool = False,+ runtime: str = Task.Runtime.ACP,+) -> dict:"""A copy of ``data`` with the team/user default AI run triple filled in when it pinsno runtime selection (see ``resolve_ai_run_selection``).@@ -8098,7 +8128,7 @@ def _with_ai_run_defaults(data: dict, *, team_id: int, acting_user_id: int | Non)updated = dict(data)- apply_ai_run_defaults(updated, team_id, acting_user_id)+ apply_ai_run_defaults(updated, team_id, acting_user_id, runtime=runtime)return updated@@ -8976,6 +9006,7 @@ def run_task(team_id=task.team_id,acting_user_id=user_id if user_id is not None else task.created_by_id,internal=task.internal,+ runtime=task.runtime,)access_state = {@@ -9226,8 +9257,8 @@ def run_task("fast_mode": fast_mode,}if is_pi_task:- for key in ("runtime_adapter", "provider", "model", "reasoning_effort"):- run_state_values.pop(key)+ run_state_values.pop("runtime_adapter")+ run_state_values.pop("provider")extra_state = extra_state or {}extra_state["pr_base_branch"] = branchfor key, value in run_state_values.items():diff --git a/products/tasks/backend/logic/services/agent_server_launcher.py b/products/tasks/backend/logic/services/agent_server_launcher.pyindex 5527de61c4dd..6f4aa21de26b 100644--- a/products/tasks/backend/logic/services/agent_server_launcher.py+++ b/products/tasks/backend/logic/services/agent_server_launcher.py@@ -335,6 +335,7 @@ class AgentServerLaunchMixin(SandboxBase):rtk_enabled: bool = True,benjamin_enabled: bool = False,peer_messaging: bool = False,+ pi_acp_conversation: bool = False,posthog_exec_permission_regex: str | None = None,claude_model_access: str | None = None,codex_model_access: str | None = None,@@ -361,6 +362,7 @@ class AgentServerLaunchMixin(SandboxBase):rtk_enabled=rtk_enabled,benjamin_enabled=benjamin_enabled,peer_messaging=peer_messaging,+ pi_acp_conversation=pi_acp_conversation,unset_bedrock=self.disable_direct_bedrock,)subscription_flag = build_subscription_flags(claude_model_access, codex_model_access)@@ -701,6 +703,7 @@ class AgentServerLaunchMixin(SandboxBase):rtk_enabled: bool = True,benjamin_enabled: bool = False,peer_messaging: bool = False,+ pi_acp_conversation: bool = False,claude_model_access: str | None = None,codex_model_access: str | None = None,codex_run_token: str | None = None,@@ -787,6 +790,7 @@ class AgentServerLaunchMixin(SandboxBase):rtk_enabled=rtk_enabled,benjamin_enabled=benjamin_enabled,peer_messaging=peer_messaging,+ pi_acp_conversation=pi_acp_conversation,posthog_exec_permission_regex=exec_permission_regex,claude_model_access=claude_model_access,codex_model_access=codex_model_access,diff --git a/products/tasks/backend/logic/services/ai_run_defaults.py b/products/tasks/backend/logic/services/ai_run_defaults.pyindex 673fd8b8a026..d6e4b44da2e7 100644--- a/products/tasks/backend/logic/services/ai_run_defaults.py+++ b/products/tasks/backend/logic/services/ai_run_defaults.py@@ -115,7 +115,9 @@ def _canonical_team_id(team_id: int) -> int:return resolve_effective_team_id(team_id)-def apply_ai_run_defaults(selection: dict, team_id: int, user_id: int | None) -> ResolvedAIRunConfig | None:+def apply_ai_run_defaults(+ selection: dict, team_id: int, user_id: int | None, *, runtime: str = ACP+) -> ResolvedAIRunConfig | None:"""Fill `selection`'s `(runtime_adapter, model, reasoning_effort)` keys in place fromthe stored defaults, returning the config that applied — or `None` when the callerpinned a selection or no level has one, leaving `selection` untouched.@@ -127,6 +129,7 @@ def apply_ai_run_defaults(selection: dict, team_id: int, user_id: int | None) ->resolved = resolve_ai_run_selection(team_id,user_id,+ runtime=runtime,runtime_adapter=selection.get("runtime_adapter"),model=selection.get("model"),reasoning_effort=selection.get("reasoning_effort"),diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex a7caa37ad6c6..fa9b538c07a4 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -978,6 +978,7 @@ class DockerSandbox(AgentServerLaunchMixin):rtk_enabled: bool = True,benjamin_enabled: bool = False,peer_messaging: bool = False,+ pi_acp_conversation: bool = False,posthog_exec_permission_regex: str | None = None,claude_model_access: str | None = None,codex_model_access: str | None = None,@@ -1008,6 +1009,7 @@ class DockerSandbox(AgentServerLaunchMixin):rtk_enabled=rtk_enabled,benjamin_enabled=benjamin_enabled,peer_messaging=peer_messaging,+ pi_acp_conversation=pi_acp_conversation,)subscription_flag = build_subscription_flags(claude_model_access, codex_model_access)create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex d8ba10dde0ce..4d10f52960e5 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -377,6 +377,7 @@ def build_agent_runtime_env_prefix(rtk_enabled: bool = True,benjamin_enabled: bool = False,peer_messaging: bool = False,+ pi_acp_conversation: bool = False,unset_bedrock: bool = False,) -> str:env_vars = {@@ -409,6 +410,7 @@ def build_agent_runtime_env_prefix(# both states so a stale "1" in a resumed sandbox can't outlive a flag rollback;# the peers endpoints re-check authorization server-side regardless."POSTHOG_AGENT_PEER_MESSAGING": "1" if peer_messaging else "0",+ "POSTHOG_PI_CONVERSATION_FORMAT": "acp" if pi_acp_conversation else "pi",}assignments = " ".join(f"{name}={shlex.quote(value)}" for name, value in env_vars.items() if value is not None and value != ""@@ -679,6 +681,7 @@ class SandboxBase(ABC):rtk_enabled: bool = True,benjamin_enabled: bool = False,peer_messaging: bool = False,+ pi_acp_conversation: bool = False,claude_model_access: str | None = None,codex_model_access: str | None = None,codex_run_token: str | None = None,diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 3802051ecf27..5c620b436cce 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -882,6 +882,8 @@ class TestModalSandboxAgentServer:({"benjamin_enabled": True}, "POSTHOG_BENJAMIN=1"),({"benjamin_enabled": False}, "POSTHOG_BENJAMIN=0"),({}, "POSTHOG_BENJAMIN=0"),+ ({"pi_acp_conversation": True}, "POSTHOG_PI_CONVERSATION_FORMAT=acp"),+ ({}, "POSTHOG_PI_CONVERSATION_FORMAT=pi"),],)def test_start_agent_server_toggle_env(self, mock_sandbox: Any, toggles, expected_env):diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 8277f76f3ff5..e1f407591708 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2932,6 +2932,31 @@ class TaskRun(models.Model):chain.reverse()return chain+ def get_history_chain(self, max_depth: int = 10) -> list["TaskRun"]:+ """The runs whose logs make up this run's conversation, oldest first, ending with this run.++ An ACP run continues its parent through `state.resume_from_run_id`, so its history is the+ resume chain. A resumed Pi run continues a task session instead: the Pi server reopens the+ session rather than replaying a parent run, so its history is the earlier runs of that+ session. Only the `logs` endpoint reads this; resume and artifact lookups keep the resume chain.+ """+ if (+ not (self.state or {}).get("resume_from_run_id")+ and self.active_task_session_id is not None+ and self.task.runtime == Task.Runtime.PI+ ):+ return self._task_session_chain(max_depth)+ return self.get_resume_chain(max_depth)++ def _task_session_chain(self, max_depth: int) -> list["TaskRun"]:+ earlier = list(+ self.task.runs.only("id", "team_id", "task_id", "created_at")+ .filter(active_task_session_id=self.active_task_session_id, created_at__lt=self.created_at)+ .order_by("-created_at")[:max_depth]+ )+ earlier.reverse()+ return [*earlier, self]+def find_artifact_in_resume_chain(self, storage_path: str) -> dict | None:"""Find an artifact by storage_path on this run or any ancestor in the resume chain."""# Iterate newest-first since artifact is more likely to be on this run.diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 3eb8843bd935..79713374d34c 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -81,6 +81,20 @@ logger = logging.getLogger(__name__)TASK_RUN_REASONING_EFFORT_CHOICES = [effort.value for effort in ReasoningEffort]+PI_TASK_INCOMPATIBLE_RUN_FIELDS = ("runtime_adapter", "context_window", "fast_mode", "initial_permission_mode")+++def _pi_task_run_request_errors(attrs: dict[str, Any]) -> dict[str, str]:+ errors: dict[str, str] = {}+ if attrs.get("claude_model_access") == "own-subscription":+ errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."+ if attrs.get("codex_model_access") == "own-subscription":+ errors["codex_model_access"] = "Pi tasks cannot use a ChatGPT plan."+ for field in PI_TASK_INCOMPATIBLE_RUN_FIELDS:+ if attrs.get(field) is not None:+ errors[field] = "This field cannot be used with a Pi task."+ return errors+def _is_pi_task_run_request(context: dict[str, Any]) -> bool:if "task_runtime" in context:@@ -3657,7 +3671,10 @@ class TaskRunCreateRequestSerializer(required=False,default=None,allow_blank=False,- help_text="LLM model identifier. The server derives the runtime adapter when it is omitted.",+ help_text=(+ "LLM model identifier. The server derives the runtime adapter when it is omitted. "+ "A Pi task runs any listed model and takes no runtime adapter."+ ),)reasoning_effort = serializers.ChoiceField(choices=REASONING_EFFORT_CHOICES,@@ -3712,7 +3729,7 @@ class TaskRunCreateRequestSerializer(if attrs.get("claude_model_access") == "own-subscription":errors["claude_model_access"] = "Scheduled runs must use the PostHog gateway."if attrs.get("model") and attrs.get("runtime_adapter") is None:- attrs["runtime_adapter"] = get_runtime_adapter_for_model(attrs["model"]) or next(+ model_runtime_adapter = get_runtime_adapter_for_model(attrs["model"]) or next((RuntimeAdapter(choice.runtime_adapter)for choice in available_model_choices(TASK_RUN_GATEWAY_PRODUCT)@@ -3720,12 +3737,12 @@ class TaskRunCreateRequestSerializer(),None,)- if attrs["runtime_adapter"] is None:+ if model_runtime_adapter is None:errors["model"] = "Unknown model. Use tasks-models-retrieve to list available models."+ elif not is_pi_task:+ attrs["runtime_adapter"] = model_runtime_adapterif is_pi_task:- for field in ("runtime_adapter", "model", "reasoning_effort", "initial_permission_mode"):- if attrs.get(field) is not None:- errors[field] = "This field cannot be used with a Pi task. Remove it and try again."+ errors.update(_pi_task_run_request_errors(attrs))if collision_error := get_relayed_imported_mcp_name_collision_error(attrs):errors["relayed_mcp_servers"] = collision_errorinitial_permission_mode = attrs.get("initial_permission_mode")@@ -3735,16 +3752,23 @@ class TaskRunCreateRequestSerializer(pending_user_message = attrs.get("pending_user_message")pending_user_artifact_ids = attrs.get("pending_user_artifact_ids") or []- if attrs.get("claude_model_access") == "own-subscription" and is_pi_task:- errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."- if attrs.get("codex_model_access") == "own-subscription" and is_pi_task:- errors["codex_model_access"] = "Pi tasks cannot use a ChatGPT plan."if pending_user_message is not None:trimmed_message = pending_user_message.strip()attrs["pending_user_message"] = trimmed_message or Noneif not attrs.get("pending_user_message") and not pending_user_artifact_ids:attrs.pop("pending_user_message", None)+ if is_pi_task:+ if "model" not in errors and (+ model_access_error := get_model_access_error(+ attrs.get("model"), distinct_id=request_distinct_id(self.context)+ )+ ):+ errors["model"] = model_access_error+ if errors:+ raise serializers.ValidationError(errors)+ return attrs+runtime_fields = ("runtime_adapter", "model")has_runtime_selection = any(attrs.get(field) is not None@@ -3906,19 +3930,8 @@ class TaskRunBootstrapCreateRequestSerializer(errors["relayed_mcp_servers"] = collision_errorinitial_permission_mode = attrs.get("initial_permission_mode")runtime_adapter = attrs.get("runtime_adapter")- is_pi_task = _is_pi_task_run_request(self.context)- if is_pi_task:- if attrs.get("claude_model_access") == "own-subscription":- errors["claude_model_access"] = "Pi tasks cannot use a Claude subscription."- if attrs.get("codex_model_access") == "own-subscription":- errors["codex_model_access"] = "Pi tasks cannot use a ChatGPT plan."- pi_incompatible_fields = ("runtime_adapter", "context_window", "fast_mode", "initial_permission_mode")- for field in pi_incompatible_fields:- if attrs.get(field) is not None:- errors[field] = "This field cannot be used with a Pi task."- if attrs.get("reasoning_effort") == ReasoningEffort.ULTRACODE:- errors["reasoning_effort"] = "This reasoning effort cannot be used with a Pi task."-+ if _is_pi_task_run_request(self.context):+ errors.update(_pi_task_run_request_errors(attrs))if errors:raise serializers.ValidationError(errors)return attrsdiff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 1c7afeb7fdac..7229deaa813b 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -3243,7 +3243,9 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"Fetch the logs for a task run as JSONL. If the run resumes from ""another (state.resume_from_run_id), each ancestor's log is ""concatenated first (oldest ancestor → ... → this run) so resume "- "consumers see a single continuous history."+ "consumers see a single continuous history. A resumed Pi run "+ "includes the earlier runs of its task session the same way, each "+ "preceded by a pi_run_started entry that names its run."),)@action(detail=True, methods=["get"], url_path="logs", required_scopes=["task:read"])@@ -3251,7 +3253,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):task_id = self._ensure_task_accessible()timer = ServerTimingsGathered()with timer("s3_read"):- log_content = tasks_facade.read_task_run_logs(pk, task_id, self.team_id)+ log_content = tasks_facade.read_task_run_conversation_logs(pk, task_id, self.team_id)if log_content is None:raise NotFound()@@ -3440,6 +3442,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if task_runtime == tasks_facade.TaskRuntime.PI and method not in {"user_message","cancel",+ "permission_response",+ "set_config_option","pi/rpc","queue_get","queue_clear",diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.pyindex 7f2846434f8c..5c409ce51492 100644--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py@@ -32,6 +32,7 @@ from products.tasks.backend.constants import (HOGLAND_SANDBOX_FEATURE_FLAG,MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,OVERLAP_CLONE_BOOT_FEATURE_FLAG,+ PI_ACP_FEATURE_FLAG,PR_BABYSIT_SNAPSHOT_FEATURE_FLAG,PR_LOOP_ENABLED_STATE_KEY,RTK_DISABLED_FEATURE_FLAG,@@ -168,6 +169,7 @@ class TaskProcessingContext:# Whether agent peer messaging tools should surface in this run (flag + Pi runtime).# Exposure only: the peers endpoints re-check authorization server-side on every call.peer_messaging_enabled: bool = False+ pi_acp_conversation_enabled: bool = False# Which sandbox provider this run provisions on ("modal" or "hogland"). Captured at# workflow start and persisted into TaskRun.state at provision time, so activities# and out-of-band consumers route deterministically for the run's whole life.@@ -459,6 +461,28 @@ def _is_peer_messaging_enabled(return enabled+def _is_pi_acp_enabled(+ *,+ distinct_id: str,+ organization_id: str,+ run_id: str,+) -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ PI_ACP_FEATURE_FLAG,+ distinct_id=distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception as e:+ log_with_activity_context("pi_acp_flag_check_failed", run_id=run_id, error=str(e))+ return False++def _is_rtk_enabled(*,distinct_id: str,@@ -1743,4 +1767,10 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskProorganization_id=organization_id,run_id=run_id,),+ pi_acp_conversation_enabled=task.runtime == Task.Runtime.PI+ and _is_pi_acp_enabled(+ distinct_id=distinct_id,+ organization_id=organization_id,+ run_id=run_id,+ ),)diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex a64433a701ec..b0c518f314ce 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -644,6 +644,7 @@ def _invoke_start_agent_server(rtk_enabled=ctx.rtk_enabled,benjamin_enabled=ctx.benjamin_enabled,peer_messaging=ctx.peer_messaging_enabled,+ pi_acp_conversation=ctx.pi_acp_conversation_enabled,claude_model_access=ctx.model_access.access_for("claude"),codex_model_access=ctx.model_access.access_for("codex"),codex_run_token=params.codex_run_token,diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 9178f834661e..005c37203cb9 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -200,6 +200,9 @@ OVER_LIMIT = CodeUsageStatus()+ACP_RUN_DEFAULT = {"runtime_adapter": "claude", "model": "claude-opus-4-8", "reasoning_effort": "high"}++class BaseTaskAPITest(TestCase):OVER_LIMIT: ClassVar[CodeUsageStatus] = OVER_LIMITorganization: ClassVar[Organization]@@ -3746,6 +3749,91 @@ class TestTaskAPI(BaseTaskAPITest):self.assertNotIn("mode", run.state)self.assertNotIn("pending_user_message", run.state)+ @parameterized.expand(+ [+ (+ "explicit_selection",+ ACP_RUN_DEFAULT,+ None,+ {"model": "gpt-5.6-terra", "reasoning_effort": "high"},+ "gpt-5.6-terra",+ "high",+ ),+ ("acp_team_default_is_ignored", ACP_RUN_DEFAULT, None, {}, None, None),+ (+ "pi_team_default_applies",+ {"runtime": "pi", "runtime_adapter": None, "model": "gpt-5.6-terra", "reasoning_effort": "low"},+ None,+ {},+ "gpt-5.6-terra",+ "low",+ ),+ (+ "explicit_effort_survives_acp_team_default",+ ACP_RUN_DEFAULT,+ None,+ {"reasoning_effort": "low"},+ None,+ "low",+ ),+ (+ "resume_carries_the_previous_selection",+ ACP_RUN_DEFAULT,+ {"model": "gpt-5.6-terra", "reasoning_effort": "low"},+ {},+ "gpt-5.6-terra",+ "low",+ ),+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_keeps_pi_model_selection(+ self,+ _name: str,+ team_default: dict[str, str | None],+ previous_state: dict[str, str] | None,+ payload: dict[str, str],+ expected_model: str | None,+ expected_effort: str | None,+ mock_workflow,+ ):+ update_team_ai_run_preferences(self.team.id, **team_default)+ task = self.create_task(runtime=Task.Runtime.PI)+ if previous_state is not None:+ previous = TaskRun.objects.create(+ task=task, team=self.team, status=TaskRun.Status.COMPLETED, state=previous_state+ )+ payload = {**payload, "resume_from_run_id": str(previous.id), "pending_user_message": "Continue"}++ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/", payload, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ run = task.runs.order_by("-created_at").first()+ assert run is not None+ self.assertEqual(+ {key: run.state.get(key) for key in ("model", "reasoning_effort", "runtime_adapter", "provider")},+ {"model": expected_model, "reasoning_effort": expected_effort, "runtime_adapter": None, "provider": None},+ )++ @parameterized.expand(+ [+ ("runtime_adapter", {"runtime_adapter": "codex"}),+ ("initial_permission_mode", {"initial_permission_mode": "plan"}),+ ("model", {"model": "not-a-listed-model"}),+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_rejects_invalid_configuration_for_pi(self, field: str, config: dict[str, str], mock_workflow):+ task = self.create_task(runtime=Task.Runtime.PI)++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/run/", {"model": "gpt-5.6-terra", **config}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], field)+ mock_workflow.assert_not_called()+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_rejects_pi_task_when_disabled(self, mock_workflow):task = self.create_task(runtime=Task.Runtime.PI)@@ -4342,7 +4430,6 @@ class TestTaskAPI(BaseTaskAPITest):("context_window", {"context_window": "1m"}),("fast_mode", {"fast_mode": True}),("initial_permission_mode", {"initial_permission_mode": "plan"}),- ("reasoning_effort", {"reasoning_effort": "ultracode"}),("claude_model_access", {"claude_model_access": "own-subscription"}),])@@ -10435,6 +10522,47 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.content.decode("utf-8").splitlines(), expected_lines)+ @parameterized.expand(+ [+ ("earlier_run_in_session", "same", -1, ["earlier", "target"]),+ ("run_in_another_session", "other", -1, ["target"]),+ ("later_run_in_session", "same", 1, ["target"]),+ ]+ )+ @patch("posthog.storage.object_storage.read")+ def test_logs_endpoint_reads_pi_task_session(+ self, _name: str, sibling_session: str, sibling_offset_minutes: int, expected_runs: list[str], mock_read+ ):+ task = self.create_task(runtime=Task.Runtime.PI)+ session = TaskSession.create_for_task(task)+ target = TaskRun.objects.create(task=task, team=self.team, active_task_session=session)+ sibling = TaskRun.objects.create(+ task=task,+ team=self.team,+ active_task_session=session if sibling_session == "same" else TaskSession.create_for_task(task),+ created_at=target.created_at + timedelta(minutes=sibling_offset_minutes),+ )+ logs = {sibling.log_url: '{"line":"earlier"}\n', target.log_url: '{"line":"target"}\n'}+ mock_read.side_effect = lambda path, missing_ok=False: logs.get(path)++ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{target.id}/logs/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ lines = [json.loads(line) for line in response.content.decode("utf-8").splitlines()]+ runs = {"earlier": str(sibling.id), "target": str(target.id)}+ if len(expected_runs) == 1:+ self.assertEqual(lines, [{"line": "target"}])+ return+ self.assertEqual(+ [(line.get("type"), line.get("runId"), line.get("line")) for line in lines],+ [+ ("pi_run_started", runs["earlier"], None),+ (None, None, "earlier"),+ ("pi_run_started", runs["target"], None),+ (None, None, "target"),+ ],+ )+@parameterized.expand([(None,), (True,), (False,)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_connection_token_returns_jwt(self, subscription_owner):@@ -13346,15 +13474,37 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self._command_url(task, run),{"jsonrpc": "2.0",- "method": "permission_response",- "params": {"requestId": "request-1", "optionId": "allow"},+ "method": "close","id": "req-1",},format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(response.json()["error"], "permission_response is not supported for Pi tasks.")+ self.assertEqual(response.json()["error"], "close is not supported for Pi tasks.")++ @parameterized.expand(+ [+ ("permission_response", {"requestId": "request-1", "optionId": "allow"}),+ ("set_config_option", {"configId": "effort", "value": "high"}),+ ]+ )+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")+ def test_command_proxies_acp_session_commands_for_pi_task(self, method, params, mock_post):+ reset_sandbox_jwt_key_cache()+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "id": "req-1", "result": {}})+ task = self.create_task(runtime=Task.Runtime.PI)+ run = self._create_run_with_sandbox(task)++ response = self.client.post(+ self._command_url(task, run),+ {"jsonrpc": "2.0", "method": method, "params": params, "id": "req-1"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(mock_post.call_args.kwargs["json"]["method"], method)@parameterized.expand([("claude", True), ("claude", False), ("codex", True), ("codex", False)])@patch("products.tasks.backend.temporal.client.signal_task_followup_message")diff --git a/tsconfig.json b/tsconfig.jsonindex eeb333e01b19..517532275409 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -22,6 +22,7 @@"@posthog/replay-shared/*": ["./common/replay-shared/src/*"],"@posthog/llm-normalizer": ["./packages/llm-normalizer/src/index.ts"],"@posthog/llm-normalizer/*": ["./packages/llm-normalizer/src/*"],+ "@posthog/agent-contracts/*": ["./packages/agent/packages/agent-contracts/src/*"],"@posthog/quill-charts": ["./packages/quill/packages/charts/src/index.ts"],"@posthog/quill-charts/*": ["./packages/quill/packages/charts/src/*"],// These packages are installed under frontend/node_modules only, which product