{"record":{"id":"ae7911a20575ac07","repo":"mastra-ai/mastra","slug":"codex-stream-error-json-stringify-payload-error","errorCode":null,"errorMessage":"Codex stream error: ${JSON.stringify(payload.error ?? payload)}","messagePattern":"Codex stream error: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/providers/openai-codex.ts","lineNumber":339,"sourceCode":"      }\n      case 'response.output_item.done': {\n        if (typeof payload.output_index === 'number' && payload.item) {\n          items.set(payload.output_index, payload.item);\n        }\n        break;\n      }\n      case 'response.output_text.delta': {\n        const key = `${payload.output_index}:${payload.content_index ?? 0}`;\n        textBuffers.set(key, (textBuffers.get(key) ?? '') + (payload.delta ?? ''));\n        break;\n      }\n      case 'response.completed': {\n        finalResponse = payload.response ?? finalResponse;\n        break;\n      }\n      case 'response.error':\n      case 'error': {\n        throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);\n      }\n      default:\n        // Ignore reasoning / unknown events\n        break;\n    }\n  };\n\n  // SSE parser: events separated by blank line; lines like \"event: x\" / \"data: y\"\n  // Normalize CRLF→LF so \\r\\n\\r\\n event boundaries parse correctly (SSE spec allows CRLF).\n  const processChunk = (chunk: string) => {\n    buffer += chunk.replace(/\\r\\n/g, '\\n');\n    let sepIdx: number;\n    while ((sepIdx = buffer.indexOf('\\n\\n')) !== -1) {\n      const raw = buffer.slice(0, sepIdx);\n      buffer = buffer.slice(sepIdx + 2);\n      const event: { event?: string; data?: string } = {};\n      const dataLines: string[] = [];\n      for (const line of raw.split('\\n')) {","sourceCodeStart":321,"sourceCodeEnd":357,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/providers/openai-codex.ts#L321-L357","documentation":"While aggregating the Codex SSE stream, handleEvent inspects each parsed event. When the server sends a 'response.error' or 'error' event, the library surfaces it as a plain Error containing the JSON of payload.error (or the whole payload), aborting aggregation. This is the server reporting a failure mid-stream (e.g. invalid request, quota, upstream model error).","triggerScenarios":"A Codex streaming request receives an SSE event of type 'response.error' or 'error' — e.g. invalid model id, exceeded usage limits, malformed request parameters, or an upstream OpenAI failure after the stream opened.","commonSituations":"Expired/invalid bearer token accepted at connection but rejected during generation; requesting a model the account cannot access; payload too large or unsupported parameters; transient OpenAI server errors mid-stream.","solutions":["Parse the JSON in the error message to read the server's error code/message and fix the request accordingly.","Verify the model ID and request parameters are valid for your Codex account/plan.","Re-authenticate if the error indicates an auth problem (token expired mid-flight).","Retry with backoff for transient upstream (5xx/rate-limit) errors."],"exampleFix":"// before\nconst text = await aggregated; // throws Error('Codex stream error: {\"code\":...}')\n// after\ntry {\n  const text = await aggregated;\n} catch (e) {\n  const detail = JSON.parse(e.message.replace('Codex stream error: ', ''));\n  if (detail.code === 'rate_limit_exceeded') await sleep(backoff); // then retry\n  throw e;\n}","handlingStrategy":"try-catch","validationCode":"// Validate request before sending:\nif (!modelId || !SUPPORTED_CODEX_MODELS.includes(modelId)) {\n  throw new Error(`Unsupported Codex model: ${modelId}`);\n}","typeGuard":"null","tryCatchPattern":"try {\n  const text = await aggregated;\n} catch (e) {\n  if (e.message.startsWith('Codex stream error:')) {\n    const payload = JSON.parse(e.message.slice('Codex stream error: '.length));\n    // inspect payload.error.code: rate_limit / invalid_model / auth, react accordingly\n  }\n  throw e;\n}","preventionTips":["Parse stream error payloads and branch on the server error code.","Retry with exponential backoff for rate-limit/transient codes only.","Re-authenticate when the error indicates token problems.","Validate model IDs and parameters against your account's allowed list."],"tags":["streaming","network","openai-codex","server-error"],"backgroundTag":"stream-error-event","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}