mastra-ai/mastra · error

Codex stream error: ${JSON.stringify(payload.error ?? payloa

Error message

Codex stream error: ${JSON.stringify(payload.error ?? payload)}

What it means

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).

Source

Thrown at mastracode/sdk/src/providers/openai-codex.ts:339

      }
      case 'response.output_item.done': {
        if (typeof payload.output_index === 'number' && payload.item) {
          items.set(payload.output_index, payload.item);
        }
        break;
      }
      case 'response.output_text.delta': {
        const key = `${payload.output_index}:${payload.content_index ?? 0}`;
        textBuffers.set(key, (textBuffers.get(key) ?? '') + (payload.delta ?? ''));
        break;
      }
      case 'response.completed': {
        finalResponse = payload.response ?? finalResponse;
        break;
      }
      case 'response.error':
      case 'error': {
        throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);
      }
      default:
        // Ignore reasoning / unknown events
        break;
    }
  };

  // SSE parser: events separated by blank line; lines like "event: x" / "data: y"
  // Normalize CRLF→LF so \r\n\r\n event boundaries parse correctly (SSE spec allows CRLF).
  const processChunk = (chunk: string) => {
    buffer += chunk.replace(/\r\n/g, '\n');
    let sepIdx: number;
    while ((sepIdx = buffer.indexOf('\n\n')) !== -1) {
      const raw = buffer.slice(0, sepIdx);
      buffer = buffer.slice(sepIdx + 2);
      const event: { event?: string; data?: string } = {};
      const dataLines: string[] = [];
      for (const line of raw.split('\n')) {

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Parse the JSON in the error message to read the server's error code/message and fix the request accordingly.
  2. Verify the model ID and request parameters are valid for your Codex account/plan.
  3. Re-authenticate if the error indicates an auth problem (token expired mid-flight).
  4. Retry with backoff for transient upstream (5xx/rate-limit) errors.

Example fix

// before
const text = await aggregated; // throws Error('Codex stream error: {"code":...}')
// after
try {
  const text = await aggregated;
} catch (e) {
  const detail = JSON.parse(e.message.replace('Codex stream error: ', ''));
  if (detail.code === 'rate_limit_exceeded') await sleep(backoff); // then retry
  throw e;
}
Defensive patterns

Strategy: try-catch

Validate before calling

// Validate request before sending:
if (!modelId || !SUPPORTED_CODEX_MODELS.includes(modelId)) {
  throw new Error(`Unsupported Codex model: ${modelId}`);
}

Type guard

null

Try / catch

try {
  const text = await aggregated;
} catch (e) {
  if (e.message.startsWith('Codex stream error:')) {
    const payload = JSON.parse(e.message.slice('Codex stream error: '.length));
    // inspect payload.error.code: rate_limit / invalid_model / auth, react accordingly
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/ae7911a20575ac07. Report an issue: GitHub.