How the Codex Plugin Handles Structured Output Parsing from Codex Models

The Codex plugin converts raw Codex model responses into type-safe JavaScript objects by extracting JSON blocks, validating them against predefined schemas using ajv, and wrapping valid results in a CodexResult class.

The openai/codex-plugin-cc repository implements a robust pipeline for structured output parsing that transforms free-form text from Codex models into validated, schema-compliant data. This approach ensures downstream automation receives predictable, programmatically accessible objects rather than unstructured text. Understanding this parsing mechanism is essential for developers extending the plugin or debugging model integration issues.

Schema-Driven Prompt Architecture

The foundation of reliable structured output parsing begins with explicit schema definitions. The plugin stores JSON schemas in plugins/codex/schemas/, such as review-output.schema.json, which define the exact structure expected from model responses. These schemas enforce type safety and field requirements before any parsing occurs.

When invoking commands like codex result or codex review, the plugin embeds schema requirements directly into prompts sent to the model. This instructs Codex to emit responses conforming to the expected JSON structure, minimizing parsing errors at the source.

JSON Extraction and Parsing Pipeline

Raw model responses often contain explanatory text surrounding the actual JSON payload. In plugins/codex/scripts/lib/codex.mjs, the extractJSON function handles this noise using a regular expression to isolate the first JSON block:

function extractJSON(text) {
  const match = text.match(/\{[\s\S]*\}/);
  if (!match) throw new Error('No JSON block found');
  return match[0];
}

The runCodexCommand function orchestrates the full pipeline. It captures the raw string from the model, invokes extractJSON to isolate the JSON string, and parses it using JSON.parse:

export async function runCodexCommand(command, payload) {
  const raw = await invokeModel(command, payload);
  const jsonStr = extractJSON(raw);
  const data = JSON.parse(jsonStr);
  // Validation step follows
  return new CodexResult(data);
}

Schema Validation and Error Recovery

After parsing, the plugin validates the resulting object against the appropriate JSON schema using the ajv validator. The validation logic compiles the schema for the specific command and throws descriptive errors when constraints are violated:

const validate = ajv.compile(getSchemaFor(command));
if (!validate(data)) {
  throw new Error('Schema validation failed: ' + ajv.errorsText(validate.errors));
}

When validation or parsing fails, the plugin activates error recovery mechanisms. The plugins/codex/agents/codex-rescue.md skill contains logic to re-prompt the model with explicit correction instructions, requesting a properly formatted JSON payload. This retry loop ensures robustness against model hallucinations or formatting errors.

Typed Result Propagation

Upon successful validation, the plugin wraps the parsed data in a CodexResult class defined in plugins/codex/scripts/lib/codex.mjs. This class provides typed accessors for schema-defined fields, allowing downstream commands to consume structured data safely without repeated validation checks.

For example, consuming a review result:

import { runCodexCommand } from './plugins/codex/scripts/lib/codex.mjs';

async function getResult(prompt) {
  const result = await runCodexCommand('result', { prompt });
  // Returns a CodexResult instance with validated fields
  return result;
}

getResult('Summarize the changes in this PR')
  .then(res => {
    console.log('Summary:', res.summary);
    console.log('Files changed:', res.files);
  })
  .catch(err => {
    console.error('Failed to parse structured output:', err);
  });

Key Files and Components

The structured output parsing system spans several critical files in the repository:

Summary

  • The Codex plugin leverages schema-driven prompts to encourage valid JSON output from models.
  • The extractJSON function uses regex pattern matching to isolate JSON blocks from surrounding text in plugins/codex/scripts/lib/codex.mjs.
  • ajv validates parsed objects against command-specific schemas stored in plugins/codex/schemas/.
  • The CodexResult class provides typed wrappers for validated data, ensuring type-safe downstream consumption.
  • Error recovery via codex-rescue.md allows automatic retry when parsing or validation fails.

Frequently Asked Questions

How does the plugin handle malformed JSON responses?

When the model returns malformed JSON, the extractJSON function throws a No JSON block found error if it cannot locate a valid JSON pattern. If JSON.parse fails or ajv validation rejects the structure, the plugin logs the problematic output and may invoke the rescue agent defined in plugins/codex/agents/codex-rescue.md to request a corrected payload.

What validation library does the Codex plugin use?

The plugin uses ajv (Another JSON Schema Validator) to compile and validate parsed JSON against predefined schemas. This ensures all structured outputs conform to type constraints and required fields defined in files like plugins/codex/schemas/review-output.schema.json.

Where are the JSON schemas defined in the repository?

JSON schemas reside in the plugins/codex/schemas/ directory. The review-output.schema.json file defines the structure for review outputs, while additional schemas exist for other command types. These schemas are referenced dynamically based on the command being executed.

How does error recovery work when parsing fails?

Error recovery activates when validation or parsing exceptions occur. The plugin logs the raw response and can trigger a retry mechanism through the rescue agent skill. This agent re-prompts the Codex model with explicit instructions to fix formatting errors and return valid JSON, creating a robust feedback loop for handling edge cases.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →