# JSON Schema structured output

`Runtime.exec(..., response_format=...)` is the one public entry. Whatever the provider claims, the result is strictly parsed and validated against the caller's original schema. Ordinary calls still return `str`.

## Modes

| `mode` | How | Chosen when |
| --- | --- | --- |
| `native` | Provider JSON Schema field | Adapter supports it, model field not `False`, schema projects losslessly, current tools supported |
| `tool` | Hidden tool `__openprogram_submit_json` | `fallback="auto"`, strict tool schemas, lossless, `tool_choice` allows it |
| `prompt` | Compact schema in the system layer; local check only | Only with explicit `fallback="prompt"` |
| none | `StructuredOutputUnsupportedError` before sending | Otherwise |

An invalid schema fails first. `Model.structured_output=None` means unknown, never `False`. A lossy projection reports its exact path and disables native.

## Adapters

| API | Native payload | Capability |
| --- | --- | --- |
| `openai-completions` | `response_format={type:"json_schema", json_schema:{…}}` | supported, with tools |
| `openai-responses` | `text.format={type:"json_schema", …}` | supported, with tools |
| `anthropic-messages` | `output_config.format`, merged with `effort` | supported, with tools |
| `google-generative-ai` | `response_mime_type` and `response_json_schema` | supported, no tools, Google subset |
| `azure-openai-responses` | Responses `text.format` | per model, opt-in |
| `bedrock-converse-stream` | `outputConfig.textFormat.structure.jsonSchema`, as a JSON string | per model, opt-in |
| `openai-codex` | none | tool fallback |
| `gemini-subscription` | none | unknown: explicit prompt only |

## One attempt

1. Text and tool deltas go to a client candidate buffer, with `output_attempt`; nothing persists.
2. After the provider's raw `done`, parse and validate. Success: `structured_output_end`, then one `done`. Stream end with no terminal fails as `incomplete`.
3. Repairable failure: `structured_output_retry`; clients clear the buffer; a new provider stream starts.
4. Budget gone: `error`, no `done`, no invalid assistant message persisted.

## Failure handling

| Failure | Request | Repair |
| --- | --- | --- |
| Invalid schema | Not sent: `StructuredOutputSchemaError` | No |
| Unsupported or conflicting | Not sent: `StructuredOutputUnsupportedError` | No |
| JSON syntax, schema violation, missing or mixed submission | Sent | Yes, up to `max_validation_retries` |
| Refusal, content filter | Sent | No: `refusal` |
| `max_tokens`, incomplete, context length | Sent | No: reason kept, limits unchanged |
| Transport, rate limit, provider internal | Sent | Existing retry, shared budget |
| Cancellation, deadline | Sent | No: propagates |

`max_validation_retries` (0, 1 or 2; default 2) caps repairs; `max_retries` caps every provider call at the Runtime boundary, so repair needs both. Retry events fire only when a repair will really run. Repair prompts hold only the failure type and bounded issues, and last for this exec.

## With tools

| Case | Behaviour |
| --- | --- |
| Native, adapter `with_tools` | Every round carries the schema; the no-tool round's text is validated |
| Native, tools unverified | Hidden tool if `auto`, else preflight failure |
| Hidden tool, user tools | Offered together; ordinary tools run for many rounds; submit ends. `parallel_tool_calls=False`. |
| Submit with ordinary tools in one response | `mixed_submission`: rejected, no tool runs |
| Plain text, no submit | `missing_submission` |
| Forced tool, `none`, or requested parallel | Not overridden: native if possible, else unsupported |

Submit is not executed and has no `ToolResultMessage`. Validation sits at the Agent-loop no-tool boundary; there is no separate provider path, so tools, deadlines, DAG and record/replay stay one.

## Surfaces

| Surface | Contract |
| --- | --- |
| Python | Returns `JsonValue`; raises `StructuredOutputError` with `code`, `provider`, `model`, `attempts`, `issues` |
| `openprogram --print --json-schema PATH` (`-` for stdin) | Stdout is one compact UTF-8 JSON document. Exit 2 invalid, 3 unsupported, 4 generation or validation failure; stderr has only the code. |
| WebSocket chat, `POST /api/function/{name}` | `response_format?`; result in `chat_response` with `structured_output` and `structured_output_mode`; the HTTP route still only acknowledges with `{session_id,msg_id}` |
| Web chat | No schema by default, no schema editor; retry clears candidate text |
| Session history | Canonical JSON content; mode, attempt, schema hash in metadata; invalid candidates never enter |

**Types**

```
@dataclass(frozen=True)
class JsonSchemaOutput:
    schema: dict[str, Any]     # never mutated
    name: str = "response"     # ^[A-Za-z_][A-Za-z0-9_-]{0,63}$
    description: str | None = None
    strict: bool = True
    fallback: Literal["auto", "none", "prompt"] = "auto"
    max_validation_retries: Literal[0, 1, 2] = 2
    type: Literal["json_schema"] = "json_schema"

Runtime.exec(content=..., response_format={"type": "object", ...}) -> JsonValue
Runtime.exec(content=..., response_format=JsonSchemaOutput(...)) -> JsonValue
Runtime.exec(content=..., response_format=None) -> str
```

A bare dict is the schema, not a provider payload. `Model.structured_output`, `StreamOptions.response_format`, and `AssistantMessage.structured_output`, `structured_output_mode`, `structured_output_attempt`. Raw JSON text stays in assistant content for history and audit. `jsonschema>=4.23` is a direct dependency. Error `code`: `invalid_schema`, `unsupported`, `invalid_json`, `validation_failed`, `missing_submission`, `mixed_submission`, `refusal`, `incomplete`.

**Parsing and limits**

- `json.loads` rejecting `NaN`, `Infinity`, Markdown fences, surrounding text and trailing content; no forgiving parser, also for hidden-tool arguments.
- `validator_for(schema)`, a registry with no external access, errors sorted by instance path, schema path, message.
- Preflight rejects any `$ref`, `$dynamicRef`, `$recursiveRef` that does not resolve inside the schema, and direct reference cycles. Finite recursion is allowed.
- Schema budget: 1 MiB, 4096 container nodes, 8192 edges, depth 100; over it is `invalid_schema`.
- At most 20 issues, 500 characters each.
- Tool arguments: strict export turns optional fields into required nullable ones; shared normalization restores only added nulls, on a copy, before canonical validation. Enum, conditional and combinator constraints stay.

**Record and replay**

`RECORDING_FORMAT_VERSION` is 2. Requests record normalized `response_format`; raw provider events are recorded, and retry, end and error are rebuilt deterministically on replay. Each repair is a new provider call and `call_index`. v1 structured recordings are rejected; ordinary v1 stays compatible. The schema is hashed (SHA-256, sorted keys) for logs, DAG and errors; recordings retain the whole schema.

**Session title consumer**

`conversation/turn_runtime/titles.py`: `TITLE_SCHEMA` is `{title: string, 1–80}`, `toolset="none"`, `max_iterations=2`, `fallback="prompt"`, `max_validation_retries=1`. Best-effort: a structured error keeps the placeholder. The consumer does only Unicode trim and storage-length protection; logs hold fixed lifecycle labels only.

**What was not taken**

- Provider strict alone, with raw text returned: refusals, truncation and compatible endpoints need local checks.
- Partial or forgiving JSON repair.
- Parsing every delta into objects.
- A separate structured provider path.
- Lossy schema rewriting, automatic Pydantic types, cross-language codegen, incremental JSON AST.

`references/pi-ai` shares options and strict tool schemas but has no response schema. Each adapter needs a payload contract test before a capability is enabled.

**Files**

| File | Holds |
| --- | --- |
| `models/providers/structured_output.py` | Normalization, preflight, negotiation, parsing, errors |
| `models/providers/types.py` | Fields and events |
| `providers/catalog/{api_registry,register}.py` | Adapter capabilities |
| `providers/schema/` | Dialects, strict projection |
| `runtime/agent/loop/` | Terminal validation, hidden tool, repair |
| `runtime/agent/runtime/` | Parsed returns, callable models |
| `runtime/conversation/event_parsing.py` | Stream events |
| `providers/recording/{recording,replay}.py` | Format 2 |
| `interfaces/cli/{parser,application,chat,print_turn}.py` | One-shot CLI |
| `interfaces/server/ws_actions/chat/`, `routes/chat.py` | WebSocket and API |
