:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): classify agent-reported run failures by cause (#115337)
Alessandro Pogliaghiecb48499c8fc
diff --git a/packages/agent/packages/agent-contracts/src/api-http-client.ts b/packages/agent/packages/agent-contracts/src/api-http-client.tsindex 1cab24dec45e..b1be02554532 100644--- a/packages/agent/packages/agent-contracts/src/api-http-client.ts+++ b/packages/agent/packages/agent-contracts/src/api-http-client.ts@@ -28,6 +28,7 @@ export type TaskRunUpdate = Partial<"status" | "branch" | "stage" | "error_message" | "output" | "state">> & {+ error_type?: string;state_remove_keys?: string[];state_append?: Record<string, unknown>;};diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.finish.test.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.finish.test.tsindex c4f01ca202df..5b493934fa42 100644--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.finish.test.ts+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.finish.test.ts@@ -100,6 +100,7 @@ describe("ClaudeAcpAgent.buildRequestFinish", () => {expect(mocks.updateTaskRun).toHaveBeenCalledWith("task-1", "run-1", {status: "failed",error_message: "blocked on missing credentials",+ error_type: "agent_declined",});});@@ -109,6 +110,7 @@ describe("ClaudeAcpAgent.buildRequestFinish", () => {expect(mocks.updateTaskRun).toHaveBeenCalledWith("task-1", "run-1", {status: "failed",+ error_type: "agent_declined",});});diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.tsindex e7335e0f3e71..5b5c67954268 100644--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts@@ -631,7 +631,7 @@ describe("ClaudeAcpAgent session creation", () => {await vi.waitFor(() => {expect(createdQueries[0]?.setModel).toHaveBeenCalledTimes(1);});- await vi.advanceTimersByTimeAsync(30_001);+ await vi.advanceTimersByTimeAsync(61_001);await expect(promise).rejects.toThrow(error);expect(createdQueryOptions[0]?.abortController?.signal.aborted).toBe(@@ -651,6 +651,37 @@ describe("ClaudeAcpAgent session creation", () => {},);+ it("retries a failed model switch once and keeps the session", async () => {+ vi.useFakeTimers();+ try {+ let attempts = 0;+ nextSetModel = () =>+ attempts++ === 0+ ? Promise.reject(new Error("set model boom"))+ : Promise.resolve();+ const agent = makeAgent();+ const params = {+ sessionId: "0197a000-0000-7000-8000-0000000000fb",+ cwd,+ mcpServers: [],+ _meta: { taskRunId: "run-set-model-transient" },+ };++ const promise = agent.newSession(params);+ await vi.waitFor(() => {+ expect(createdQueries[0]?.setModel).toHaveBeenCalledTimes(1);+ });+ await vi.advanceTimersByTimeAsync(1_000);++ await expect(promise).resolves.toHaveProperty("sessionId");+ expect(createdQueries).toHaveLength(1);+ expect(createdQueries[0]?.setModel).toHaveBeenCalledTimes(2);+ expect(createdQueries[0]?.close).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+it("preserves RequestError metadata when naming a rejected startup control", async () => {const requestError = new RequestError(42, "set model boom", {source: "sdk",@@ -929,6 +960,7 @@ describe("ClaudeAcpAgent session creation", () => {const settings = String(createdQueryOptions[0]?.extraArgs?.settings);expect(settings.startsWith(configDir)).toBe(true);expect(existsSync(settings)).toBe(true);+ nextSetModel = () => Promise.reject(new Error("set model boom"));rejectSetModel(new Error("set model boom"));await rejection;diff --git a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts b/packages/agent/packages/agent/src/adapters/claude/claude-agent.tsindex aaa7980d5ff1..e43ba6208daf 100644--- a/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts+++ b/packages/agent/packages/agent/src/adapters/claude/claude-agent.ts@@ -3063,6 +3063,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {await new PostHogAPIClient(config).updateTaskRun(taskId, taskRunId, {status,...(status === "failed" && message ? { error_message: message } : {}),+ ...(status === "failed" ? { error_type: "agent_declined" } : {}),});} catch (error) {this.logger.error("finish tool failed to mark run terminal", error);@@ -3546,11 +3547,25 @@ export class ClaudeAcpAgent extends BaseAcpAgent {try {if (isResume || resolvedModelId !== options.model) {startupStep = "model switch";- await this.awaitStartupControl(- startupStep,- this.session.query.setModel(resolvedModelId),- startupErrorData,- );+ try {+ await this.awaitStartupControl(+ startupStep,+ this.session.query.setModel(resolvedModelId),+ startupErrorData,+ );+ } catch (modelSwitchError) {+ startupLogger.warn("Session model switch failed; retrying once", {+ ...startupErrorData,+ modelId: resolvedModelId,+ errorDetail: serializeError(modelSwitchError),+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 1000));+ await this.awaitStartupControl(+ startupStep,+ this.session.query.setModel(resolvedModelId),+ startupErrorData,+ );+ }}// Keep thinking enabled by default for effort-capable models (seediff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.tsindex fcb2c60a4a65..65d063146108 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts@@ -1651,47 +1651,74 @@ describe("CodexAppServerAgent", () => {expect((tc.content as Array<{ type?: string }>)[0]?.type).toBe("diff");});- it("passes outputSchema to turn/start and fires onStructuredOutput", async () => {- const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });- const { client } = makeFakeClient();- const outputs: Array<Record<string, unknown>> = [];- const schema = {- type: "object",- properties: { repo: { type: "string" } },- required: ["repo"],- };- const agent = new CodexAppServerAgent(client, {- processOptions: { binaryPath: "/x/codex" },- rpcFactory: stub.factory,- onStructuredOutput: async (o) => {- outputs.push(o);+ it.each([+ [+ "passes outputSchema to turn/start",+ {+ type: "object",+ properties: { repo: { type: "string" }, note: { type: "string" } },+ required: ["repo"],},- });+ true,+ ],+ [+ "omits outputSchema for a dictionary schema",+ {+ type: "object",+ properties: {+ repo: { type: "string" },+ note: { type: "string" },+ labels: { type: "object", additionalProperties: { type: "string" } },+ },+ required: ["repo"],+ },+ false,+ ],+ ])(+ "%s and fires onStructuredOutput without synthetic nulls",+ async (_, schema, sendsOutputSchema) => {+ const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });+ const { client } = makeFakeClient();+ const outputs: Array<Record<string, unknown>> = [];+ const agent = new CodexAppServerAgent(client, {+ processOptions: { binaryPath: "/x/codex" },+ rpcFactory: stub.factory,+ onStructuredOutput: async (o) => {+ outputs.push(o);+ },+ });- await agent.newSession({- cwd: "/r",- _meta: { jsonSchema: schema },- } as unknown as NewSessionRequest);- const done = agent.prompt({- sessionId: "t",- prompt: [{ type: "text", text: "pick a repo" }],- } as unknown as PromptRequest);+ await agent.newSession({+ cwd: "/r",+ _meta: { jsonSchema: schema },+ } as unknown as NewSessionRequest);+ const done = agent.prompt({+ sessionId: "t",+ prompt: [{ type: "text", text: "pick a repo" }],+ } as unknown as PromptRequest);- // The schema-constrained final message is pure JSON.- stub.emit("item/completed", {- item: {- type: "agentMessage",- id: "a1",- text: '{"repo":"posthog/posthog"}',- },- });- stub.emit("turn/completed", { turn: { status: "completed" } });- await done;+ // The schema-constrained final message is pure JSON.+ stub.emit("item/completed", {+ item: {+ type: "agentMessage",+ id: "a1",+ text: '{"repo":"posthog/posthog","note":null}',+ },+ });+ stub.emit("turn/completed", { turn: { status: "completed" } });+ await done;- const turnStart = stub.requests.find((r) => r.method === "turn/start");- expect(turnStart?.params).toMatchObject({ outputSchema: schema });- expect(outputs).toEqual([{ repo: "posthog/posthog" }]);- });+ const turnStart = stub.requests.find((r) => r.method === "turn/start");+ if (sendsOutputSchema) {+ expect(turnStart?.params).toMatchObject({+ outputSchema: { required: ["repo", "note"] },+ });+ } else {+ expect(turnStart?.params).not.toHaveProperty("outputSchema");+ }+ expect(outputs).toEqual([{ repo: "posthog/posthog" }]);+ },+ );it("injects task instructions and mcp_servers into thread/start", async () => {const stub = makeStubRpc({ "thread/start": { thread: { id: "t" } } });diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.tsindex 8ed88e74dcfa..f5d532f8d4b9 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts@@ -111,7 +111,11 @@ import {type CodexAppServerProcessOptions,spawnCodexAppServerProcess,} from "./spawn";-import { parseStructuredOutput } from "./structured-output";+import {+ parseStructuredOutput,+ stripSyntheticNulls,+ toStrictOutputSchema,+} from "./structured-output";import { TurnController } from "./turn-controller";import { mergeUsage, UsageTracker } from "./usage-tracker";@@ -1131,6 +1135,9 @@ export class CodexAppServerAgent extends BaseAcpAgent {private turnStartParams(input: CodexUserInput[]): Record<string, unknown> {const approvalPolicy = this.config.approvalPolicy();const sandboxPolicy = this.sandboxPolicyForTurn();+ const outputSchema = this.jsonSchema+ ? toStrictOutputSchema(this.jsonSchema)+ : null;return {threadId: this.threadId,input,@@ -1150,7 +1157,7 @@ export class CodexAppServerAgent extends BaseAcpAgent {? { sandboxPolicy }: {}),// Constrain the final message to the task schema for parseable structured output.- ...(this.jsonSchema ? { outputSchema: this.jsonSchema } : {}),+ ...(outputSchema ? { outputSchema } : {}),};}@@ -2159,7 +2166,9 @@ export class CodexAppServerAgent extends BaseAcpAgent {const parsed = parseStructuredOutput(message);if (parsed) {try {- await this.onStructuredOutput(parsed);+ await this.onStructuredOutput(+ stripSyntheticNulls(parsed, this.jsonSchema),+ );} catch (err) {this.logger.warn("onStructuredOutput callback threw", { error: err });}diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.test.tsindex 4a1e6b9b60fe..fef3fa38217e 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.test.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vitest";-import { parseStructuredOutput } from "./structured-output";+import {+ parseStructuredOutput,+ stripSyntheticNulls,+ toStrictOutputSchema,+} from "./structured-output";describe("parseStructuredOutput", () => {it("parses a bare JSON object", () => {@@ -42,3 +46,225 @@ describe("parseStructuredOutput", () => {expect(parseStructuredOutput('leading {"a": 1')).toBeNull();});});++describe("toStrictOutputSchema", () => {+ it("closes nested objects and requires every property", () => {+ const schema = {+ type: "object",+ properties: {+ repo: {+ type: "object",+ properties: { name: { type: "string" } },+ required: ["name"],+ },+ },+ required: ["repo"],+ };+ expect(toStrictOutputSchema(schema)).toEqual({+ type: "object",+ properties: {+ repo: {+ type: "object",+ properties: { name: { type: "string" } },+ required: ["name"],+ additionalProperties: false,+ },+ },+ required: ["repo"],+ additionalProperties: false,+ });+ });++ it("closes objects inside arrays, anyOf and $defs", () => {+ const strict = toStrictOutputSchema({+ type: "object",+ properties: {+ rows: {+ type: "array",+ items: { type: "object", properties: { id: { type: "number" } } },+ },+ choice: { anyOf: [{ $ref: "#/$defs/thing" }, { type: "string" }] },+ },+ required: ["rows", "choice"],+ $defs: { thing: { type: "object", properties: {} } },+ });+ expect(strict).toMatchObject({+ properties: {+ rows: {+ items: {+ properties: { id: { type: ["number", "null"] } },+ required: ["id"],+ additionalProperties: false,+ },+ },+ },+ $defs: { thing: { required: [], additionalProperties: false } },+ });+ });++ it("makes optional properties required but nullable", () => {+ const strict = toStrictOutputSchema({+ type: "object",+ properties: {+ name: { type: "string" },+ label: { type: "string", enum: ["a", "b"] },+ value: { anyOf: [{ type: "string" }, { type: "number" }] },+ },+ required: ["name"],+ });+ expect(strict).toEqual({+ type: "object",+ properties: {+ name: { type: "string" },+ label: { type: ["string", "null"], enum: ["a", "b", null] },+ value: {+ anyOf: [{ type: "string" }, { type: "number" }, { type: "null" }],+ },+ },+ required: ["name", "label", "value"],+ additionalProperties: false,+ });+ });++ it("leaves the input schema untouched", () => {+ const schema = {+ type: "object",+ properties: {+ nested: { type: "object", properties: { a: { type: "string" } } },+ },+ };+ const before = structuredClone(schema);+ toStrictOutputSchema(schema);+ expect(schema).toEqual(before);+ });++ it.each([+ [+ "a top-level dictionary",+ {+ type: "object",+ additionalProperties: { type: "string" },+ minProperties: 1,+ },+ ],+ [+ "a nested dictionary",+ {+ type: "object",+ properties: {+ labels: {+ type: "object",+ additionalProperties: { type: "string" },+ minProperties: 1,+ },+ },+ required: ["labels"],+ },+ ],+ [+ "a dictionary behind $defs",+ {+ type: "object",+ properties: { rows: { type: "array", items: { $ref: "#/$defs/m" } } },+ $defs: { m: { type: "object", additionalProperties: true } },+ },+ ],+ [+ "patternProperties",+ { type: "object", patternProperties: { "^x-": { type: "string" } } },+ ],+ ])("returns null for %s, which strict mode cannot represent", (_, schema) => {+ expect(toStrictOutputSchema(schema)).toBeNull();+ });++ it("still converts a schema that already sets additionalProperties: false", () => {+ expect(+ toStrictOutputSchema({+ type: "object",+ properties: { name: { type: "string" } },+ additionalProperties: false,+ }),+ ).toEqual({+ type: "object",+ properties: { name: { type: ["string", "null"] } },+ required: ["name"],+ additionalProperties: false,+ });+ });+});++describe("stripSyntheticNulls", () => {+ const schema = {+ type: "object",+ properties: {+ note: { type: "string" },+ reason: { type: ["string", "null"] },+ owner: { type: ["string", "null"] },+ kind: { enum: ["a", null] },+ repo: {+ type: "object",+ properties: { name: { type: "string" }, branch: { type: "string" } },+ required: ["name"],+ },+ rows: { type: "array", items: { $ref: "#/$defs/row" } },+ parent: { anyOf: [{ $ref: "#/$defs/row" }, { type: "null" }] },+ },+ required: ["owner"],+ $defs: {+ row: {+ type: "object",+ properties: { id: { type: "number" }, tag: { type: "string" } },+ required: ["id"],+ },+ },+ };++ it("drops nulls the original schema rejects and keeps the ones it accepts", () => {+ expect(+ stripSyntheticNulls(+ {+ note: null,+ reason: null,+ owner: null,+ kind: null,+ repo: { name: "posthog", branch: null },+ rows: [+ { id: 1, tag: null },+ { id: 2, tag: "x" },+ ],+ parent: { id: 3, tag: null },+ extra: null,+ },+ schema,+ ),+ ).toEqual({+ reason: null,+ owner: null,+ kind: null,+ repo: { name: "posthog" },+ rows: [{ id: 1 }, { id: 2, tag: "x" }],+ parent: { id: 3 },+ extra: null,+ });+ });++ it("keeps a null for a required property", () => {+ const strict = {+ type: "object",+ properties: { note: { type: "string" } },+ required: ["note"],+ };+ expect(stripSyntheticNulls({ note: null }, strict)).toEqual({+ note: null,+ });+ });++ it("leaves the input output and schema untouched", () => {+ const output = { note: null, repo: { name: "posthog", branch: null } };+ const before = structuredClone(output);+ const schemaBefore = structuredClone(schema);+ stripSyntheticNulls(output, schema);+ expect(output).toEqual(before);+ expect(schema).toEqual(schemaBefore);+ });+});diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.tsindex dca29bb0f9c0..f49dc85b8cc1 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/structured-output.ts@@ -62,3 +62,214 @@ function findBalancedObjectEnd(text: string, start: number): number {}return -1;}++export function toStrictOutputSchema(+ schema: Record<string, unknown>,+): Record<string, unknown> | null {+ if (!isStrictRepresentable(schema)) return null;+ return toStrictSchemaNode(schema) as Record<string, unknown>;+}++function isStrictRepresentable(node: unknown): boolean {+ if (Array.isArray(node)) return node.every(isStrictRepresentable);+ if (!isPlainObject(node)) return true;+ if (+ node.additionalProperties === true ||+ isPlainObject(node.additionalProperties) ||+ "patternProperties" in node ||+ "propertyNames" in node+ ) {+ return false;+ }+ for (const key of ["items", "anyOf", "oneOf", "allOf"]) {+ if (key in node && !isStrictRepresentable(node[key])) return false;+ }+ for (const key of ["$defs", "definitions", "properties"]) {+ const children = node[key];+ if (+ isPlainObject(children) &&+ !Object.values(children).every(isStrictRepresentable)+ ) {+ return false;+ }+ }+ return true;+}++function toStrictSchemaNode(node: unknown): unknown {+ if (Array.isArray(node)) return node.map(toStrictSchemaNode);+ if (!isPlainObject(node)) return node;+ const result: Record<string, unknown> = { ...node };+ for (const key of ["items", "anyOf", "oneOf", "allOf"]) {+ if (key in node) result[key] = toStrictSchemaNode(node[key]);+ }+ for (const key of ["$defs", "definitions"]) {+ const defs = node[key];+ if (isPlainObject(defs)) {+ result[key] = Object.fromEntries(+ Object.entries(defs).map(([name, def]) => [+ name,+ toStrictSchemaNode(def),+ ]),+ );+ }+ }+ const properties = isPlainObject(node.properties) ? node.properties : null;+ const isObjectType =+ node.type === "object" ||+ (Array.isArray(node.type) && node.type.includes("object"));+ if (properties && !isObjectType) {+ result.properties = Object.fromEntries(+ Object.entries(properties).map(([name, property]) => [+ name,+ toStrictSchemaNode(property),+ ]),+ );+ }+ if (isObjectType) {+ const required = new Set(Array.isArray(node.required) ? node.required : []);+ if (properties) {+ result.properties = Object.fromEntries(+ Object.entries(properties).map(([name, property]) => {+ const strict = toStrictSchemaNode(property);+ return [name, required.has(name) ? strict : toNullableSchema(strict)];+ }),+ );+ }+ result.required = Object.keys(properties ?? {});+ result.additionalProperties = false;+ }+ return result;+}++export function stripSyntheticNulls(+ output: Record<string, unknown>,+ schema: Record<string, unknown>,+): Record<string, unknown> {+ return stripSyntheticNullsNode(output, schema, schema) as Record<+ string,+ unknown+ >;+}++function stripSyntheticNullsNode(+ value: unknown,+ node: unknown,+ root: Record<string, unknown>,+): unknown {+ const schema = resolveLocalRef(node, root);+ if (!isPlainObject(schema)) return value;+ if (Array.isArray(value)) {+ return isPlainObject(schema.items)+ ? value.map((item) => stripSyntheticNullsNode(item, schema.items, root))+ : value;+ }+ if (!isPlainObject(value)) return value;+ const objectBranch = singleObjectBranch(schema, root);+ if (objectBranch) return stripSyntheticNullsNode(value, objectBranch, root);+ const isObjectType =+ schema.type === "object" ||+ (Array.isArray(schema.type) && schema.type.includes("object"));+ if (!isObjectType || !isPlainObject(schema.properties)) return value;+ const properties = schema.properties;+ const required = new Set(+ Array.isArray(schema.required) ? schema.required : [],+ );+ const result: Record<string, unknown> = {};+ for (const [name, entry] of Object.entries(value)) {+ if (!(name in properties)) {+ result[name] = entry;+ continue;+ }+ if (+ entry === null &&+ !required.has(name) &&+ !acceptsNull(properties[name], root)+ ) {+ continue;+ }+ result[name] = stripSyntheticNullsNode(entry, properties[name], root);+ }+ return result;+}++function singleObjectBranch(+ schema: Record<string, unknown>,+ root: Record<string, unknown>,+): unknown {+ for (const key of ["anyOf", "oneOf"]) {+ const options = schema[key];+ if (!Array.isArray(options)) continue;+ const objectOptions = options.filter((option) => {+ const resolved = resolveLocalRef(option, root);+ return (+ isPlainObject(resolved) &&+ (resolved.type === "object" ||+ (Array.isArray(resolved.type) && resolved.type.includes("object")))+ );+ });+ if (objectOptions.length === 1) return objectOptions[0];+ }+ return null;+}++function acceptsNull(node: unknown, root: Record<string, unknown>): boolean {+ const schema = resolveLocalRef(node, root);+ if (!isPlainObject(schema)) return false;+ if (schema.type === "null") return true;+ if (Array.isArray(schema.type) && schema.type.includes("null")) return true;+ if (Array.isArray(schema.enum) && schema.enum.includes(null)) return true;+ for (const key of ["anyOf", "oneOf"]) {+ const options = schema[key];+ if (+ Array.isArray(options) &&+ options.some((option) => acceptsNull(option, root))+ ) {+ return true;+ }+ }+ return false;+}++function resolveLocalRef(+ node: unknown,+ root: Record<string, unknown>,+): unknown {+ let current = node;+ for (let guard = 0; guard < 32; guard++) {+ if (!isPlainObject(current) || typeof current.$ref !== "string") {+ return current;+ }+ const match = current.$ref.match(/^#\/(\$defs|definitions)\/([^/]+)$/);+ const defs = match ? root[match[1]] : null;+ if (!match || !isPlainObject(defs)) return current;+ current = defs[match[2]];+ }+ return current;+}++function toNullableSchema(node: unknown): unknown {+ if (!isPlainObject(node)) return node;+ const result: Record<string, unknown> = { ...node };+ if (Array.isArray(node.type)) {+ if (!node.type.includes("null")) result.type = [...node.type, "null"];+ } else if (typeof node.type === "string") {+ if (node.type !== "null") result.type = [node.type, "null"];+ } else if (Array.isArray(node.anyOf)) {+ if (+ !node.anyOf.some(+ (option) => isPlainObject(option) && option.type === "null",+ )+ ) {+ result.anyOf = [...node.anyOf, { type: "null" }];+ }+ }+ if (Array.isArray(node.enum) && !node.enum.includes(null)) {+ result.enum = [...node.enum, null];+ }+ return result;+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}diff --git a/packages/agent/packages/agent/src/server/agent-server.test.ts b/packages/agent/packages/agent/src/server/agent-server.test.tsindex 7f228fe2d2dc..7917e8defd78 100644--- a/packages/agent/packages/agent/src/server/agent-server.test.ts+++ b/packages/agent/packages/agent/src/server/agent-server.test.ts@@ -1138,6 +1138,7 @@ describe("AgentServer HTTP Mode", () => {{status: "failed",error_message: `agent_error: ${expected}`,+ error_type: "agent_error",state: { agent_version: expect.any(String) },},);@@ -1280,6 +1281,7 @@ describe("AgentServer HTTP Mode", () => {{status: "failed",error_message: "agent_error: old run failed",+ error_type: "agent_error",state: { agent_version: expect.any(String) },},);diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.tsindex d97be642521b..43ae2700d5b6 100644--- a/packages/agent/packages/agent/src/server/agent-server.ts+++ b/packages/agent/packages/agent/src/server/agent-server.ts@@ -1270,6 +1270,7 @@ export class AgentServer {{status: "failed",error_message: `Agent server crashed: ${errorMessage}`,+ error_type: "agent_server_crash",state: { agent_version: this.agentVersion },},);@@ -4822,6 +4823,9 @@ export class AgentServer {await this.posthogAPI.updateTaskRun(payload.task_id, payload.run_id, {status,error_message: persistedErrorMessage,+ ...(options?.errorCategory+ ? { error_type: options.errorCategory }+ : {}),state: { agent_version: this.agentVersion },});this.logger.debug("Task completion signaled", { status, stopReason });diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.tsindex 2a2589f88682..c1a9f97db0d1 100644--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts@@ -312,6 +312,7 @@ export class PiAgentServer {.updateTaskRun(this.config.taskId, this.config.runId, {status: "failed",error_message: `Pi agent server crashed: ${message}`,+ error_type: "agent_server_crash",state: { agent_version: this.agentVersion },}).catch((updateError) =>diff --git a/packages/agent/packages/agent/src/server/question-relay.test.ts b/packages/agent/packages/agent/src/server/question-relay.test.tsindex 4d591d6f8177..0f71e3a37b45 100644--- a/packages/agent/packages/agent/src/server/question-relay.test.ts+++ b/packages/agent/packages/agent/src/server/question-relay.test.ts@@ -1061,6 +1061,7 @@ describe("Question relay", () => {{status: "failed",error_message: `upstream_connection_error: ${UPSTREAM_PROVIDER_FAILURE_MESSAGE}`,+ error_type: "upstream_connection_error",state: { agent_version: expect.any(String) },},);diff --git a/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.test.ts b/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.test.tsindex 98aaec6b6460..a74fce385aa1 100644--- a/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.test.ts+++ b/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.test.ts@@ -189,7 +189,11 @@ describe("finish tool", () => {expect(updateTaskRun).toHaveBeenCalledWith("task-1","run-1",- { status: "failed", error_message: "blocked" },+ {+ status: "failed",+ error_message: "blocked",+ error_type: "agent_declined",+ },expect.any(AbortSignal),);expect(result.isError).toBeUndefined();diff --git a/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.ts b/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.tsindex c758521c9319..a9fd597c93c3 100644--- a/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.ts+++ b/packages/agent/packages/harness/src/extensions/local-tools/tools/finish.ts@@ -75,6 +75,7 @@ function resolveRequestFinish(...(status === "failed" && message? { error_message: message }: {}),+ ...(status === "failed" ? { error_type: "agent_declined" } : {}),},signal,),diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex c77bfb9a1c7d..14fde9072b75 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -1427,7 +1427,7 @@ async def run_multi_turn_research("""own_pr_url = "\n".join(target.pr_url for target in implementation_context.candidates) or Nonefrom products.tasks.backend.facade import api as tasks_facade- from products.tasks.backend.facade.agents import MultiTurnSession+ from products.tasks.backend.facade.agents import MultiTurnSession, turn_failure_error_typetotal = len(signals)if total == 0:@@ -1702,7 +1702,7 @@ async def run_multi_turn_research(await session.end()except (Exception, asyncio.CancelledError) as e:# Shield so the session ending cannot itself be canceled - must complete- await asyncio.shield(session.end(status="failed", error=str(e)))+ await asyncio.shield(session.end(status="failed", error=str(e), error_type=turn_failure_error_type(e)))raisenew_finding_count = sum(1 for artefact in new_artefacts if isinstance(artefact, SignalFinding))diff --git a/products/signals/backend/scout_harness/suggestions_runner.py b/products/signals/backend/scout_harness/suggestions_runner.pyindex f3b641526639..b6018380a661 100644--- a/products/signals/backend/scout_harness/suggestions_runner.py+++ b/products/signals/backend/scout_harness/suggestions_runner.py@@ -47,7 +47,7 @@ from products.signals.backend.temporal.agentic import ()from products.skills.backend.api.skill_serializers import validate_new_skill_name_valuefrom products.tasks.backend.facade import api as tasks_facade-from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession+from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession, turn_failure_error_typelogger = structlog.get_logger(__name__)@@ -291,17 +291,17 @@ async def arun_scout_suggestions(raiseexcept Exception as error:logger.warning("scout_suggestions: generation failed", team_id=team.id, error=str(error), exc_info=True)- await _end_failed(session, str(error))+ await _end_failed(session, str(error), turn_failure_error_type(error))await database_sync_to_async(mark_generation_failed, thread_sensitive=False)(team.id, task_run_id=task_run_id)return _finish("failed", task_run_id=task_run_id)return _finish("completed", task_run_id=task_run_id, suggestion_count=len(items))-async def _end_failed(session: MultiTurnSession | None, error: str) -> None:+async def _end_failed(session: MultiTurnSession | None, error: str, error_type: str | None = None) -> None:if session is None:return# Shielded so the failure status still lands when a cancel re-fires mid-signal.- await asyncio.shield(session.end(status="failed", error=error))+ await asyncio.shield(session.end(status="failed", error=error, error_type=error_type))__all__ = ["SuggestionRunResult", "arun_scout_suggestions", "validate_suggestion_items"]diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.pyindex afead88e35f9..e8b248134f18 100644--- a/products/signals/backend/test/test_agentic_report_activity.py+++ b/products/signals/backend/test/test_agentic_report_activity.py@@ -1630,7 +1630,7 @@ async def test_run_multi_turn_research_requests_verification_note_as_the_final_alabels = [call.kwargs["label"] for call in session.send_followup.await_args_list]assert labels == expected_labelsif failure is asyncio.CancelledError:- session.end.assert_awaited_once_with(status="failed", error=str(verification_error))+ session.end.assert_awaited_once_with(status="failed", error=str(verification_error), error_type=None)else:session.end.assert_awaited_once_with()if failure is not None and failure is not asyncio.CancelledError:diff --git a/products/signals/backend/test/test_scout_suggestions.py b/products/signals/backend/test/test_scout_suggestions.pyindex 8c720bc897d8..aaf292b4ea28 100644--- a/products/signals/backend/test/test_scout_suggestions.py+++ b/products/signals/backend/test/test_scout_suggestions.py@@ -913,6 +913,7 @@ async def test_runner_fails_a_batch_that_validates_down_to_nothing(asuggestion_t# The TaskRun must not read as completed when nothing was stored: triage reads its status.session.end.assert_awaited_once()assert session.end.await_args.kwargs["status"] == "failed"+ assert session.end.await_args.kwargs["error_type"] == "output_parse_failed"@pytest.mark.asynciodiff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.pyindex b2f19f988d46..5dba0124d44d 100644--- a/products/tasks/backend/agent_proxy_callback.py+++ b/products/tasks/backend/agent_proxy_callback.py@@ -201,7 +201,7 @@ class AgentProxyCallbackDispatcher:def _turn_failed(self) -> CallbackOutcome:if self._load_run() is None:return CallbackOutcome()- signal_workflow_completion(self.run_id, "failed", PI_RUNTIME_ERROR_MESSAGE)+ signal_workflow_completion(self.run_id, "failed", PI_RUNTIME_ERROR_MESSAGE, "pi_runtime_error")return CallbackOutcome(dispatched=True)def _budget_steer(self) -> CallbackOutcome:diff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.pyindex 1e55c68c6a41..0fdf65075f84 100644--- a/products/tasks/backend/facade/agents.py+++ b/products/tasks/backend/facade/agents.py@@ -21,7 +21,10 @@ from products.tasks.backend.logic.services.custom_prompt_internals import (extract_json_from_text,poll_for_agent_task as poll_for_turn,)-from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import MultiTurnSession+from products.tasks.backend.logic.services.custom_prompt_multi_turn_runner import (+ MultiTurnSession,+ turn_failure_error_type,+)from products.tasks.backend.logic.services.dev_sandbox_context import resolve_sandbox_context_for_local_devfrom products.tasks.backend.logic.services.local_skills import (ENV_DISABLE_BUNDLED_SKILLS,@@ -62,4 +65,5 @@ __all__ = ["extract_json_from_text","poll_for_turn","resolve_sandbox_context_for_local_dev",+ "turn_failure_error_type",]diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex d013da5a94d5..c769d7fab979 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -344,6 +344,7 @@ __all__ = ["read_task_run_log_content","read_task_run_logs","record_comment_activity",+ "record_run_failure_cause","signal_task_run_client_activity","redispatch_task_run","relay_task_run_message",@@ -2085,6 +2086,13 @@ def update_task_run_state(return TaskRun.update_state_atomic(run_id, updates=updates, remove_keys=remove_keys)+def record_run_failure_cause(run_id: str | UUID, error_type: str) -> None:+ try:+ TaskRun.update_state_atomic(run_id, updates={"failure_error_type": error_type})+ except Exception:+ logger.warning("Failed to record failure cause for task run %s", run_id, exc_info=True)++def promote_run_to_user_authorship(run_id: str | UUID, actor_user_id: int) -> bool:"""Promote a bot-authored run to user authorship when the actor now has a usable GitHub install.@@ -2687,6 +2695,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("token_cost","token_cost_incomplete","compute_cost",+ "failure_error_type","unprocessed_request_ids",TASK_OWNERSHIP_VERSION_STATE_KEY,"pr_authorship_mode",@@ -2827,6 +2836,25 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(_TERMINAL_TASK_RUN_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)+TASK_RUN_FAILURE_ERROR_TYPES = (+ "agent_reported",+ "agent_server_crash",+ "agent_declined",+ "output_parse_failed",+ "poll_timeout",+ "pi_runtime_error",+ "upstream_stream_terminated",+ "upstream_connection_error",+ "upstream_timeout",+ "upstream_provider_failure",+ "upstream_request_rejected",+ "content_block_rejection",+ "turn_ended_without_response",+ "subscription_usage_limit",+ "task_spend_limit",+ "agent_error",+)+# `output.pr_merged` is GitHub's word, recorded by the PR webhook (`_record_run_pr_merged`) — never# the caller's. Signals reads it to decide refund finality (billing.report_pr_is_merged): a report# whose PR merged keeps its resolved status through a refund instead of being suppressed and having@@ -3054,7 +3082,9 @@ def get_task_run_stream_info()-def signal_workflow_completion(run_id: str | UUID, status: str, error_message: str | None) -> None:+def signal_workflow_completion(+ run_id: str | UUID, status: str, error_message: str | None, error_type: str | None = None+) -> None:"""Send a completion signal to a run's Temporal workflow (best-effort)."""import asyncio # noqa: PLC0415 — only needed when signalling@@ -3067,6 +3097,8 @@ def signal_workflow_completion(run_id: str | UUID, status: str, error_message: srun = TaskRun.objects.filter(pk=run_id).first()if run is None or (run.scheduled_at is not None and run.queued_at is None):return+ if error_type is not None:+ record_run_failure_cause(run.id, error_type)try:client = sync_connect()handle = client.get_workflow_handle(run.workflow_id)@@ -3380,7 +3412,7 @@ def update_task_run(setattr(run, key, _apply_caller_output(existing_output, value, merged_output))update_fields.add(key)continue- if key in ("state_remove_keys", "state_append"):+ if key in ("state_remove_keys", "state_append", "error_type"):continueif key == "state" and has_state_merge:existing_state = run.state if isinstance(run.state, dict) else {}@@ -3465,7 +3497,7 @@ def update_task_run("task_run_failed",{"error_message": truncate_error_message(run.error_message),- "error_type": "agent_reported",+ "error_type": validated_data.get("error_type") or "agent_reported","duration_seconds": run._duration_seconds(),**run.failure_sandbox_backend_properties(),},@@ -3477,7 +3509,9 @@ def update_task_run(observe_prewarmed_unused_if_never_activated(run, reason="released" if new_status == TaskRun.Status.CANCELLED else "other")- signal_workflow_completion(run.id, new_status, validated_data.get("error_message"))+ signal_workflow_completion(+ run.id, new_status, validated_data.get("error_message"), validated_data.get("error_type")+ )if new_status == TaskRun.Status.CANCELLED:from products.tasks.backend.push_dispatcher import ( # noqa: PLC0415 — keep push deps off the api import pathnotify_task_run_cancelled,diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.pyindex b992b25cd863..649a03af2a68 100644--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py@@ -8,8 +8,9 @@ from dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any, TypeVarfrom uuid import UUID-from pydantic import BaseModel, JsonValue+from pydantic import BaseModel, JsonValue, ValidationError+from products.tasks.backend.facade.api import record_run_failure_causefrom products.tasks.backend.models import MCPBuiltInAgentKey, Task, TaskRunif TYPE_CHECKING:@@ -20,6 +21,7 @@ from products.tasks.backend.logic.services.custom_prompt_internals import (CustomPromptSandboxContext,EmptyAgentTurnError,OutputFn,+ TurnPollTimeout,_create_task_and_trigger as create_task_and_trigger,extract_json_from_text,poll_for_turn,@@ -45,6 +47,14 @@ def _required_model_keys(model: type[BaseModel]) -> set[str]:return {key for key, required in keys.items() if required} or set(keys)+def turn_failure_error_type(error: BaseException) -> str | None:+ if isinstance(error, TurnPollTimeout):+ return "poll_timeout"+ if isinstance(error, (EmptyAgentTurnError, ValidationError, ValueError)):+ return "output_parse_failed"+ return None++# Mutable: per-turn log offsets (`log_lines_seen`, `printed_lines`) are updated in place.@dataclass(frozen=False)class MultiTurnSession:@@ -187,7 +197,7 @@ class MultiTurnSession:# own teardown. End it here so a first-turn parse failure (or a Temporal timeout,# which raises CancelledError — a BaseException) doesn't leave the run wedged in# IN_PROGRESS. Shield so the failure signal still lands if the cancel re-fires.- await asyncio.shield(session.end(status="failed", error=str(e)))+ await asyncio.shield(session.end(status="failed", error=str(e), error_type=turn_failure_error_type(e)))raisereturn session, parsed@@ -301,7 +311,7 @@ class MultiTurnSession:# here so a first-turn poll failure (or a Temporal timeout, which raises# CancelledError — a BaseException) doesn't leave the run wedged in IN_PROGRESS.# Shield so the failure signal still lands if the cancel re-fires mid-cleanup.- await asyncio.shield(session.end(status="failed", error=str(e)))+ await asyncio.shield(session.end(status="failed", error=str(e), error_type=turn_failure_error_type(e)))raisereturn session, turn.last_message@@ -406,7 +416,7 @@ class MultiTurnSession:json_data = extract_json_from_text(text=text, label=label, required_keys=_required_model_keys(model))return model.model_validate(json_data, context=validation_context)- async def end(self, *, status: str = "completed", error: str | None = None) -> None:+ async def end(self, *, status: str = "completed", error: str | None = None, error_type: str | None = None) -> None:"""Signal the workflow to shut down, recording `status` as the terminal TaskRun state.Pass `status="failed"` (with an `error` message) when ending because of an error, so@@ -416,6 +426,8 @@ class MultiTurnSession:if not self._workflow_handle:raise RuntimeError("Workflow handle is not available in this session.")try:+ if error_type is not None:+ await asyncio.to_thread(record_run_failure_cause, self.task_run.id, error_type)await self._workflow_handle.signal(ProcessTaskWorkflow.complete_task, args=[status, error])logger.info("multi_turn: ended session run=%s status=%s", self.task_run.id, status)except Exception:diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex ab6ed1de3542..e21a68d65a3f 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -684,7 +684,7 @@ def _dispatch_turn_failed_sync(run_id: str) -> None:if not settings.TEST:close_old_connections()- signal_workflow_completion(run_id, "failed", PI_RUNTIME_ERROR_MESSAGE)+ signal_workflow_completion(run_id, "failed", PI_RUNTIME_ERROR_MESSAGE, "pi_runtime_error")def _is_session_update(event: dict) -> bool:diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 06de40153ace..026e129a64c8 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2616,6 +2616,7 @@ class TaskRun(models.Model):"sandbox_jwt_kid","sandbox_connect_token","sandbox_backend",+ "failure_error_type",)def restore_cloud_resume_state(self, prior_state: dict[str, Any]) -> None:diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex c969f1bcab5b..3587c22f0044 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -28,7 +28,7 @@ from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDSfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.agent_instructions import AGENT_INSTRUCTIONS_MAX_LENGTH-from products.tasks.backend.facade.api import CHANNEL_INSTRUCTIONS_MAX_BYTES+from products.tasks.backend.facade.api import CHANNEL_INSTRUCTIONS_MAX_BYTES, TASK_RUN_FAILURE_ERROR_TYPESfrom products.tasks.backend.facade.client_provenance import is_api_key_request, is_sandbox_oauth_requestfrom products.tasks.backend.facade.contracts import (ChannelContributorsDTO,@@ -336,6 +336,12 @@ class TaskRunUpdateSerializer(serializers.Serializer):error_message = serializers.CharField(required=False, allow_null=True, allow_blank=True, help_text="Error message if execution failed")+ error_type = serializers.ChoiceField(+ choices=TASK_RUN_FAILURE_ERROR_TYPES,+ required=False,+ allow_null=True,+ help_text="Why the run failed, set by the caller that marked it failed.",+ )class TaskRunSkillBundleMetadataSerializer(serializers.Serializer):diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex f9bc36ddf009..379e72686d2c 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -20,6 +20,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connectionsfrom products.slack_app.backend.facade.api import agent_plan_steps, phase_for_tool_call, tool_call_from_acp_update+from products.tasks.backend.facade.api import record_run_failure_causefrom products.tasks.backend.feature_flags import run_stream_presence_gated, run_stream_thin_tailfrom products.tasks.backend.logic.services.agent_command import (is_hogland_sandbox_url,@@ -559,6 +560,7 @@ async def _relay_loop(# A pi runtime error ends the turn but is not a# successful completion — fail the run outright rather# than reporting the turn as answered.+ await asyncio.to_thread(record_run_failure_cause, run_id, "pi_runtime_error")await _signal_safely(workflow_handle, "complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE])diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 3b74ba2c08a6..612a491aea6f 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -1082,6 +1082,8 @@ class TestRelaySandboxEventsErrorHandling:notify = MagicMock()monkeypatch.setattr("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed", notify)monkeypatch.setattr(relay_sandbox_events_module.asyncio, "to_thread", run_sync)+ record_cause = MagicMock()+ monkeypatch.setattr(relay_sandbox_events_module, "record_run_failure_cause", record_cause)metric = "posthog_tasks_turn_completed_suppressed_total"labels = {"reason": "idle_resume"}suppressed_before = REGISTRY.get_sample_value(metric, labels) or 0@@ -1098,8 +1100,10 @@ class TestRelaySandboxEventsErrorHandling:)if turn_failed:+ record_cause.assert_called_once_with("run-id", "pi_runtime_error")handle.signal.assert_awaited_once_with("complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE])else:+ record_cause.assert_not_called()await asyncio.wait_for(dispatch_done.wait(), timeout=5)assert handle.signal.await_args_list == [call("agent_state_changed", arg=False),diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.pyindex bb88a767f43d..8d425090e858 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py@@ -397,10 +397,11 @@ class TestUpdateTaskRunStatusActivity:@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(- "error_type,expected_error_type",+ "error_type,failure_state,expected_error_type",[- ("ActivityError", "ActivityError"),- (None, "unspecified"),+ ("ActivityError", {}, "ActivityError"),+ (None, {}, "unspecified"),+ ("agent_reported", {"failure_error_type": "agent_declined"}, "agent_declined"),],)@pytest.mark.parametrize(@@ -419,12 +420,13 @@ class TestUpdateTaskRunStatusActivity:activity_environment: ActivityEnvironment,test_task_run: TaskRun,error_type: str | None,+ failure_state: dict[str, str],expected_error_type: str,sandbox_backend: str | None,persisted_state: dict[str, str],expected_backend: str | None,) -> None:- test_task_run.state = persisted_state+ test_task_run.state = {**persisted_state, **failure_state}test_task_run.save(update_fields=["state"])error_message = "x" * 1400 + "TypeError: cannot read boot manifest"input_data = UpdateTaskRunStatusInput(diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.pyindex c47a741ddb8f..890272289aad 100644--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py@@ -1,4 +1,4 @@-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import Any, Optionalfrom django.db import transaction@@ -123,6 +123,9 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:type="TaskRunDeletedError",)+ if input.status == TaskRun.Status.FAILED:+ input = replace(input, error_type=(task_run.state or {}).get("failure_error_type") or input.error_type)+# Side effects run after commit, outside the row lock (repo convention: no side effects in atomic).if input.status in _TERMINAL_STATUSES:try:diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.pyindex 6966b9213fc4..3355ace0830e 100644--- a/products/tasks/backend/tests/test_agent_proxy_callback.py+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py@@ -362,7 +362,9 @@ class TestAgentProxyCallback(TestCase):response = self._post(self._body(kind="turn_failed", agent_active=False), token=self._token())self.assertEqual(response.status_code, 200)self.assertTrue(response.json()["dispatched"])- signal_workflow_completion.assert_called_once_with(str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE)+ signal_workflow_completion.assert_called_once_with(+ str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE, "pi_runtime_error"+ )@parameterized.expand([diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 32f7575e7b7a..04844b505dc4 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -3906,9 +3906,29 @@ class TestTaskAPI(BaseTaskAPITest):@parameterized.expand([- ("merge", {"state": {"run_source": "manual", "pr_base_branch": "other"}}, True),- ("remove", {"state_remove_keys": ["run_source", "pr_base_branch"]}, True),- ("append", {"state_append": {"run_source": ["manual"], "pr_base_branch": ["other"]}}, True),+ (+ "merge",+ {+ "state": {+ "run_source": "manual",+ "pr_base_branch": "other",+ "failure_error_type": "ComputeBillingLimitError",+ }+ },+ True,+ ),+ ("remove", {"state_remove_keys": ["run_source", "pr_base_branch", "failure_error_type"]}, True),+ (+ "append",+ {+ "state_append": {+ "run_source": ["manual"],+ "pr_base_branch": ["other"],+ "failure_error_type": ["ComputeBillingLimitError"],+ }+ },+ True,+ ),("empty_list", {"state": []}, False),("default_branch", {"branch": "other", "state": {"branch": "other"}}, True),]@@ -3943,6 +3963,7 @@ class TestTaskAPI(BaseTaskAPITest):run.refresh_from_db()self.assertEqual(run.state["run_source"], "agent")self.assertEqual(run.state["pr_base_branch"], base_branch)+ self.assertNotIn("failure_error_type", run.state)run.status = TaskRun.Status.COMPLETEDrun.save(update_fields=["status"])@@ -7896,26 +7917,43 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(run.status, TaskRun.Status.QUEUED)mock_resume.assert_called_once_with(str(run.id), run.workflow_id)- @patch("products.tasks.backend.facade.api.signal_workflow_completion")- def test_update_run_status_to_failed_signals_workflow_with_error(self, mock_signal):+ @parameterized.expand(+ [+ ("with_error_type", {"error_type": "agent_declined"}, "agent_declined"),+ ("without_error_type", {}, None),+ ]+ )+ @patch("posthog.temporal.common.client.sync_connect")+ def test_update_run_status_to_failed_signals_workflow_with_error(+ self, _name, error_type_payload, expected_failure_error_type, mock_connect+ ):+ handle = mock_connect.return_value.get_workflow_handle.return_value+ handle.signal = AsyncMock()task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)response = self.client.patch(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",- {"status": "failed", "error_message": "Something went wrong"},+ {"status": "failed", "error_message": "Something went wrong", "error_type": "bogus"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",+ {"status": "failed", "error_message": "Something went wrong", **error_type_payload},format="json",)self.assertEqual(response.status_code, status.HTTP_200_OK)- mock_signal.assert_called_once()- call_args = mock_signal.call_args- self.assertEqual(call_args[0][1], "failed")- self.assertEqual(call_args[0][2], "Something went wrong")+ handle.signal.assert_awaited_once()+ self.assertEqual(handle.signal.call_args.args[0].__name__, "complete_task")+ self.assertEqual(handle.signal.call_args.kwargs["args"], ["failed", "Something went wrong"])run.refresh_from_db()self.assertEqual(run.status, TaskRun.Status.FAILED)self.assertEqual(run.error_message, "Something went wrong")+ self.assertEqual(run.state.get("failure_error_type"), expected_failure_error_type)@patch("products.tasks.backend.facade.api.signal_workflow_completion")def test_update_run_status_to_cancelled_signals_workflow(self, mock_signal):diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex 07b8be88ac19..4b9d4a0a2150 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -669,7 +669,9 @@ class TestTaskRunEventIngest(TestCase):self.assertEqual(status, 200)signal_turn_completed.assert_not_called()- signal_workflow_completion.assert_called_once_with(str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE)+ signal_workflow_completion.assert_called_once_with(+ str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE, "pi_runtime_error"+ )@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_workflow_heartbeat_does_not_block_event_loop(self) -> None:diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex ee1e2c29e031..a6293d9fc146 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -1266,11 +1266,13 @@ class TestTaskRun(TestCase):"snapshot_external_id": "snapshot-1","pending_user_message": "Review the attachment","pending_user_artifact_ids": ["artifact-1"],+ "failure_error_type": "poll_timeout",},)run.prepare_for_cloud_resume()+ self.assertNotIn("failure_error_type", run.state)self.assertNotIn("sandbox_id", run.state)self.assertNotIn("sandbox_url", run.state)self.assertNotIn("sandbox_jwt_kid", run.state)diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex 9c3173aac5d5..dce3f3f40aee 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -1435,7 +1435,19 @@ class TestMultiTurnSessionStartCleanup:inactivity timeout."""@pytest.mark.asyncio- async def test_cleans_up_when_initial_poll_fails(self):+ @pytest.mark.parametrize(+ "poll_error,expected_failure_error_type",+ [+ (RuntimeError("storage explode"), None),+ (+ TurnPollTimeout(+ "storage explode", stage="silent", elapsed=1, stale_seconds=1, total_lines=0, turn_relevant_lines=0+ ),+ "poll_timeout",+ ),+ ],+ )+ async def test_cleans_up_when_initial_poll_fails(self, poll_error, expected_failure_error_type):fake_task = MagicMock()fake_task.id = "task-id"fake_run = MagicMock()@@ -1456,8 +1468,11 @@ class TestMultiTurnSessionStartCleanup:),patch("products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.poll_for_turn",- new=AsyncMock(side_effect=RuntimeError("storage explode")),+ new=AsyncMock(side_effect=poll_error),),+ patch(+ "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner.record_run_failure_cause"+ ) as record_cause,pytest.raises(RuntimeError, match="storage explode"),):await MultiTurnSession.start(@@ -1468,6 +1483,11 @@ class TestMultiTurnSessionStartCleanup:# session.end() must have signalled the workflow exactly once on the cleanup path.mock_handle.signal.assert_called_once()+ assert mock_handle.signal.call_args.kwargs["args"] == ["failed", "storage explode"]+ if expected_failure_error_type is None:+ record_cause.assert_not_called()+ else:+ record_cause.assert_called_once_with("run-id", expected_failure_error_type)@pytest.mark.django_db(transaction=True)diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.pyindex a32e153d47e8..5d6fb210a4c8 100644--- a/products/tasks/backend/tests/test_task_run_metrics.py+++ b/products/tasks/backend/tests/test_task_run_metrics.py@@ -355,12 +355,16 @@ class TestTaskRunMetrics(TestCase):@parameterized.expand([- ("modal", {}),- ("hogland", {"sandbox_backend": "hogland"}),+ ("modal", {}, {}, "agent_reported"),+ ("hogland", {"sandbox_backend": "hogland"}, {"error_type": "agent_declined"}, "agent_declined"),])def test_patch_terminal_failure_captures_single_typed_task_run_failed(- self, sandbox_backend: str, sandbox_state: dict[str, str]+ self,+ sandbox_backend: str,+ sandbox_state: dict[str, str],+ error_type_payload: dict[str, str],+ expected_error_type: str,) -> None:from products.tasks.backend.facade import api as facade@@ -379,13 +383,13 @@ class TestTaskRunMetrics(TestCase):run.id,self.task.id,self.team.id,- validated_data={"status": "failed", "error_message": long_error},+ validated_data={"status": "failed", "error_message": long_error, **error_type_payload},)captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_failed"]assert len(captured) == 1props = captured[0].kwargs["properties"]- assert props["error_type"] == "agent_reported"+ assert props["error_type"] == expected_error_typeassert props["sandbox_backend"] == sandbox_backendassert len(props["error_message"]) == 500assert props["error_message"].endswith("Error: wizard exited with code 7")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex aaa02757f63c..fd29eacefd11 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3684,6 +3684,45 @@ export const RunStatusEnumApi = {Cancelled: 'cancelled',} as const+/**+ * * `agent_reported` - agent_reported+ * * `agent_server_crash` - agent_server_crash+ * * `agent_declined` - agent_declined+ * * `output_parse_failed` - output_parse_failed+ * * `poll_timeout` - poll_timeout+ * * `pi_runtime_error` - pi_runtime_error+ * * `upstream_stream_terminated` - upstream_stream_terminated+ * * `upstream_connection_error` - upstream_connection_error+ * * `upstream_timeout` - upstream_timeout+ * * `upstream_provider_failure` - upstream_provider_failure+ * * `upstream_request_rejected` - upstream_request_rejected+ * * `content_block_rejection` - content_block_rejection+ * * `turn_ended_without_response` - turn_ended_without_response+ * * `subscription_usage_limit` - subscription_usage_limit+ * * `task_spend_limit` - task_spend_limit+ * * `agent_error` - agent_error+ */+export type ErrorTypeEnumApi = (typeof ErrorTypeEnumApi)[keyof typeof ErrorTypeEnumApi]++export const ErrorTypeEnumApi = {+ AgentReported: 'agent_reported',+ AgentServerCrash: 'agent_server_crash',+ AgentDeclined: 'agent_declined',+ OutputParseFailed: 'output_parse_failed',+ PollTimeout: 'poll_timeout',+ PiRuntimeError: 'pi_runtime_error',+ UpstreamStreamTerminated: 'upstream_stream_terminated',+ UpstreamConnectionError: 'upstream_connection_error',+ UpstreamTimeout: 'upstream_timeout',+ UpstreamProviderFailure: 'upstream_provider_failure',+ UpstreamRequestRejected: 'upstream_request_rejected',+ ContentBlockRejection: 'content_block_rejection',+ TurnEndedWithoutResponse: 'turn_ended_without_response',+ SubscriptionUsageLimit: 'subscription_usage_limit',+ TaskSpendLimit: 'task_spend_limit',+ AgentError: 'agent_error',+} as const+export interface PatchedTaskRunUpdateApi {/** Current execution status*@@ -3717,6 +3756,25 @@ export interface PatchedTaskRunUpdateApi {* @nullable*/error_message?: string | null+ /** Why the run failed, set by the caller that marked it failed.+ *+ * * `agent_reported` - agent_reported+ * * `agent_server_crash` - agent_server_crash+ * * `agent_declined` - agent_declined+ * * `output_parse_failed` - output_parse_failed+ * * `poll_timeout` - poll_timeout+ * * `pi_runtime_error` - pi_runtime_error+ * * `upstream_stream_terminated` - upstream_stream_terminated+ * * `upstream_connection_error` - upstream_connection_error+ * * `upstream_timeout` - upstream_timeout+ * * `upstream_provider_failure` - upstream_provider_failure+ * * `upstream_request_rejected` - upstream_request_rejected+ * * `content_block_rejection` - content_block_rejection+ * * `turn_ended_without_response` - turn_ended_without_response+ * * `subscription_usage_limit` - subscription_usage_limit+ * * `task_spend_limit` - task_spend_limit+ * * `agent_error` - agent_error */+ error_type?: ErrorTypeEnumApi | null}/**diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 7220ad16f82e..983d53f1a7da 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -2752,6 +2752,36 @@ export const TasksRunsPartialUpdateBody = /* @__PURE__ */ zod.object({'State keys whose value to append to the list stored at that key, atomically under the row lock. Use instead of sending the whole list back through `state`, which loses concurrent appends to a read-modify-write race.'),error_message: zod.string().nullish().describe('Error message if execution failed'),+ error_type: zod+ .union([+ zod+ .enum([+ 'agent_reported',+ 'agent_server_crash',+ 'agent_declined',+ 'output_parse_failed',+ 'poll_timeout',+ 'pi_runtime_error',+ 'upstream_stream_terminated',+ 'upstream_connection_error',+ 'upstream_timeout',+ 'upstream_provider_failure',+ 'upstream_request_rejected',+ 'content_block_rejection',+ 'turn_ended_without_response',+ 'subscription_usage_limit',+ 'task_spend_limit',+ 'agent_error',+ ])+ .describe(+ '\* `agent_reported` - agent_reported\n\* `agent_server_crash` - agent_server_crash\n\* `agent_declined` - agent_declined\n\* `output_parse_failed` - output_parse_failed\n\* `poll_timeout` - poll_timeout\n\* `pi_runtime_error` - pi_runtime_error\n\* `upstream_stream_terminated` - upstream_stream_terminated\n\* `upstream_connection_error` - upstream_connection_error\n\* `upstream_timeout` - upstream_timeout\n\* `upstream_provider_failure` - upstream_provider_failure\n\* `upstream_request_rejected` - upstream_request_rejected\n\* `content_block_rejection` - content_block_rejection\n\* `turn_ended_without_response` - turn_ended_without_response\n\* `subscription_usage_limit` - subscription_usage_limit\n\* `task_spend_limit` - task_spend_limit\n\* `agent_error` - agent_error'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Why the run failed, set by the caller that marked it failed.\n\n\* `agent_reported` - agent_reported\n\* `agent_server_crash` - agent_server_crash\n\* `agent_declined` - agent_declined\n\* `output_parse_failed` - output_parse_failed\n\* `poll_timeout` - poll_timeout\n\* `pi_runtime_error` - pi_runtime_error\n\* `upstream_stream_terminated` - upstream_stream_terminated\n\* `upstream_connection_error` - upstream_connection_error\n\* `upstream_timeout` - upstream_timeout\n\* `upstream_provider_failure` - upstream_provider_failure\n\* `upstream_request_rejected` - upstream_request_rejected\n\* `content_block_rejection` - content_block_rejection\n\* `turn_ended_without_response` - turn_ended_without_response\n\* `subscription_usage_limit` - subscription_usage_limit\n\* `task_spend_limit` - task_spend_limit\n\* `agent_error` - agent_error'+ ),})/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f9c414659b1b..db3b1361666e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -41869,6 +41869,46 @@ export namespace Schemas {content_hash: string;}+ /**+ * * `agent_reported` - agent_reported+ * * `agent_server_crash` - agent_server_crash+ * * `agent_declined` - agent_declined+ * * `output_parse_failed` - output_parse_failed+ * * `poll_timeout` - poll_timeout+ * * `pi_runtime_error` - pi_runtime_error+ * * `upstream_stream_terminated` - upstream_stream_terminated+ * * `upstream_connection_error` - upstream_connection_error+ * * `upstream_timeout` - upstream_timeout+ * * `upstream_provider_failure` - upstream_provider_failure+ * * `upstream_request_rejected` - upstream_request_rejected+ * * `content_block_rejection` - content_block_rejection+ * * `turn_ended_without_response` - turn_ended_without_response+ * * `subscription_usage_limit` - subscription_usage_limit+ * * `task_spend_limit` - task_spend_limit+ * * `agent_error` - agent_error+ */+ export type ErrorTypeEnum = typeof ErrorTypeEnum[keyof typeof ErrorTypeEnum];+++ export const ErrorTypeEnum = {+ AgentReported: 'agent_reported',+ AgentServerCrash: 'agent_server_crash',+ AgentDeclined: 'agent_declined',+ OutputParseFailed: 'output_parse_failed',+ PollTimeout: 'poll_timeout',+ PiRuntimeError: 'pi_runtime_error',+ UpstreamStreamTerminated: 'upstream_stream_terminated',+ UpstreamConnectionError: 'upstream_connection_error',+ UpstreamTimeout: 'upstream_timeout',+ UpstreamProviderFailure: 'upstream_provider_failure',+ UpstreamRequestRejected: 'upstream_request_rejected',+ ContentBlockRejection: 'content_block_rejection',+ TurnEndedWithoutResponse: 'turn_ended_without_response',+ SubscriptionUsageLimit: 'subscription_usage_limit',+ TaskSpendLimit: 'task_spend_limit',+ AgentError: 'agent_error',+ } as const;+export interface EstimateExperimentScope {/*** The experiment an experiment scanner watches.@@ -85596,6 +85636,25 @@ export namespace Schemas {* @nullable*/error_message?: string | null;+ /** Why the run failed, set by the caller that marked it failed.+ *+ * * `agent_reported` - agent_reported+ * * `agent_server_crash` - agent_server_crash+ * * `agent_declined` - agent_declined+ * * `output_parse_failed` - output_parse_failed+ * * `poll_timeout` - poll_timeout+ * * `pi_runtime_error` - pi_runtime_error+ * * `upstream_stream_terminated` - upstream_stream_terminated+ * * `upstream_connection_error` - upstream_connection_error+ * * `upstream_timeout` - upstream_timeout+ * * `upstream_provider_failure` - upstream_provider_failure+ * * `upstream_request_rejected` - upstream_request_rejected+ * * `content_block_rejection` - content_block_rejection+ * * `turn_ended_without_response` - turn_ended_without_response+ * * `subscription_usage_limit` - subscription_usage_limit+ * * `task_spend_limit` - task_spend_limit+ * * `agent_error` - agent_error */+ error_type?: ErrorTypeEnum | null;}/**