Files
leleka/docs/api-contract.md
T

13 KiB

Responses contract status

The Rust control plane has a POST /v1/responses route and a reusable response trace builder. The route parses a subset of Responses requests and returns OpenAI-shaped JSON errors. It returns 503 worker_not_ready until the engine handshake completes. With a configured native tokenizer it can execute a text, function-call, reasoning and validated structured-output preview. It accepts string input or a text-only array of messages and paired function calls/results. Non-streaming and live SSE paths are connected to the resident worker; ordinary unstructured streams with effort none send text deltas and complete, schema-validated function calls before worker DONE. Reasoning streams send live reasoning deltas and buffer final answer/tool items; structured text is validated before publication. Unsupported live features return 501 unsupported_live_feature; a ready worker without tokenizer returns 501 inference_adapter_missing. Text/tool JSON and SSE, continuation, cancellation and crash recovery have passed small real-model Linux GPU checks; full recorded-agent qualification remains open.

The offline trace builder accepts text fragments, function-call argument fragments, and token usage. It assembles a non-streaming response or an ordered SSE stream ending in response.completed. Tool arguments must form a JSON object. text.format supports text, json_object, and json_schema validation in both live serving and the offline builder. External schema references are rejected. The synthetic fixture at benchmarks/fixtures/responses/structured-tool.json demonstrates text plus a tool call; it is not evidence of live Codex compatibility.

control-plane/src/wire.rs encodes the upstream GEN request line and parses the current T, PP, DONE, and ERR output lines. The supervisor accepts an internal token-ID generation command, checks its context budget, and sends it to a resident worker. It can return a buffered result or stream bounded token events. Dropping the SSE receiver cancels generation. Native Qwen prompt assembly matches pinned text-only and one representative tool golden case byte-for-byte. The live Qwen parser holds split call markers and rejects incomplete calls; it validates full argument objects before publishing function-call events.

Current request parsing supports model, string or array input, stream, instructions, max_output_tokens, previous_response_id, parallel_tool_calls, reasoning, text, named function tools, tool_choice, temperature, top_p, truncation, metadata, and store. Unknown fields are rejected. Terminal responses are stored by default; store: false disables this. previous_response_id replays a stored response with the new input, including function calls and matching results. The store is process-local and bounded to 64 responses or 128 MiB, whichever is reached first; old IDs become unavailable after eviction or restart. Multimodal input remains unsupported. The body limit is 16 MiB.

Before switching the testing runtime, exercise all engine stop conditions and tool calls with the real tokenizer and model on Linux GPU, and compare sanitized real Codex replays against the upstream Python server. Native reasoning now has its own output items, streaming events and continuation path. Do not mark Gate A complete based on synthetic fixtures.

Engine prefix metadata

The engine's RESUME <n> and REUSED <n> lines are validated as nonnegative prefix counts and treated as nonterminal metadata. Usage counters come from DONE. These lines must not fail or finish a generation; unknown wire tags and malformed counts still fail the protocol.

Cancellation failure isolation

Dropping a generation receiver sends STOP and drains that generation's output for at most 20 seconds. Tokens or progress emitted after STOP are discarded and do not extend the deadline. A terminal line before the deadline permits the next queued request. If the worker does not terminate in time, readiness is revoked, the process is killed and reaped, and queued receivers are closed. The supervisor never reuses an unaligned output stream.

Both text and function-call SSE relays observe the HTTP consumer closing even while the engine produces no events. They then drop their generation receiver so cancellation reaches the supervisor immediately.

A sanitized shell worker that consumes STOP without reporting DONE covers this failure path. This regression does not qualify full-model soak stability.

Worker recovery policy

After a failure of a worker that previously sent READY, the supervisor can start a fresh process. The default lifetime budget is three restarts, with delays of 2, 4 and 8 seconds. Set engine.max_restarts in the JSON config or STRATA_MAX_WORKER_RESTARTS to an integer from 0 through 3; zero disables recovery. Environment overrides the file. Successful requests do not replenish the lifetime budget. Initial or replacement startup failure stops recovery.

An active failed generation is not retried. Queued commands are failed during recovery; requests arriving while restarting or starting are rejected. The worker reports restarting during backoff, then starting, with no context or readiness until a new positive READY handshake. Shutdown interrupts backoff. After the lifetime budget is exhausted, the runtime must be restarted by its operator. A real-model reload has passed; sustained soak remains open.

Live structured text

Requests may select text.format.type as json_object or json_schema. The runtime adds JSON-format instructions and, for schemas, the schema itself to the model prompt. Invalid schemas and external references are rejected before worker admission. Completed text must parse as an object and, in schema mode, pass the supplied schema. The same validation applies with strict true, false, or omitted. This implementation uses prompt guidance and final validation; it does not yet constrain next-token sampling with a JSON grammar and cannot guarantee successful generation for every schema.

JSON requests return HTTP 502 if completed model output fails validation. Structured SSE sends response.created / response.in_progress immediately, then buffers output until engine DONE. Valid output is emitted with the normal item/text/terminal events. Invalid completed output emits response.failed without publishing text or function-call items. This buffering trades token-by- token structured output for validation before publication. Plain text streaming is unchanged. Disconnect still cancels the active generation while buffering.

A token-budget stop returns response.incomplete with incomplete_details.reason: "max_output_tokens"; its partial text may be invalid JSON and must not be treated as a schema-valid completed result. Tool-only turns remain valid: their arguments are checked against the tool schema, while the text format applies to the eventual answer after tool results. History stores successful and incomplete responses, never schema-failed responses.

Example format:

{"text":{"format":{"type":"json_schema","name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}}

The field names and incomplete-result handling follow the OpenAI structured output contract. Recorded Codex/MCP replay remains a separate milestone.

Native Qwen reasoning

reasoning.effort accepts none, low, medium, high, or xhigh. Omitted/null effort uses upstream's xhigh default. The pinned model template maps high to its xhigh instruction; none closes the thinking block in the prompt. Effort is a template instruction, not a separate token budget. max_output_tokens includes both reasoning and answer tokens.

Generated reasoning is returned as an output item with type: "reasoning", content: [{"type":"reasoning_text","text":"..."}] and summary: []. SSE emits response.reasoning_text.delta during generation, followed by its text/content/item done events and the normal answer or function-call events. The current reasoning path buffers the final answer/tool items until DONE; structured answers are validated before publication. effort: none plain-text and tool streaming retain their incremental behavior. Disconnect during reasoning cancels the worker generation.

The first Qwen </think> marker separates reasoning from answer text, even when split over tokens. A normal stop without that marker fails; a token-budget stop while thinking returns an incomplete reasoning item and no invented final answer. usage.output_tokens_details.reasoning_tokens counts original emitted tokens up to and including the closing-marker token; if one token straddles the boundary it is assigned to reasoning. Truncated thinking counts all its tokens. EOS tokens remain in total output usage, not reasoning usage.

Stored continuation and stateless replay preserve raw reasoning alongside assistant messages/tool calls in the Qwen template. Reasoning-only incomplete turns can precede a new user message. Summary-only and encrypted reasoning cannot reconstruct this local model's raw context and are rejected explicitly. reasoning.summary: "auto" or null is accepted, but no summarizer is implemented: summary remains empty, and raw text is never mislabeled as a summary. Explicit concise/detailed summaries are unsupported.

The reasoning content and event shapes follow the Responses raw-reasoning extension. This local Qwen implementation does not provide OpenAI encrypted reasoning.

Console request compatibility

The native route accepts the console's include, prompt_cache_key, and string-valued client_metadata fields. Only reasoning.encrypted_content is accepted in include: it is an optional inclusion hint, and this runtime still returns raw reasoning content, not encrypted content. Metadata is not added to the model prompt or persisted by the runtime. The cache key is a routing hint; it does not partition the single worker's token-verified prefix cache.

Function namespaces are lowered to deterministic, collision-checked aliases for the Qwen template. Output items retain the original function name and namespace, and replay uses the same alias even for historical functions no longer advertised. Duplicate identities, alias collisions, nested namespaces, custom/free-form tools, and server-side web search are rejected. Typed argument validation applies after namespace lowering on both JSON and SSE paths. function_call_output.output accepts text or an array of input_text parts; parts are joined with a newline. Image/file parts remain unsupported.

When max_output_tokens is omitted, generation reserves up to 32,768 tokens, limited by the remaining context minus the worker's eight-token margin. An explicit output limit is preserved. Configuring model (or STRATA_MODEL_ID) exposes that identity in /status and rejects requests for another model. An omitted configured identity preserves the earlier single-worker API behavior.

The opt-in console integration is installed with python3 scripts/install-qwen-native.py. It adds the strata-native backend to qwen-codex-ctl and uses a direct Responses provider in qwen-codex. This path has no Python serving bridge. The launcher itself remains a local convenience script. Existing selections remain unchanged, and an installation backup is retained. QWEN_CODEX_PROFILE selects a separate console profile for tests.

The native preview requires a loopback connection (an SSH tunnel for a remote GPU) because it does not yet authenticate API clients. Native discovery uses /status, requires a configured model identity and a ready 256K worker, and does not synthesize legacy /props or /slots. stop refuses to operate on this externally managed runtime; logs identifies its host-side logs.

Approval/review requests can append developer messages after user input. The native adapter stably coalesces these instruction messages into the leading Qwen system section, preserving their content and order. It does not demote approval instructions to user messages or bypass the console's review step.

Stateless replay keeps adjacent assistant commentary and function calls in one assistant turn, with their reasoning content attached. The commentary-to-call separator matches the pinned Qwen template, including trimming commentary's trailing whitespace. The sanitized commentary-tool-prompt.json fixture checks this against an independently rendered upstream template, byte for byte.

Parallel tool outputs are matched by call_id and replayed in their original call order. Qwen's tool-response markup has no ID field, so retaining arrival order would swap results when parallel tools finish in another order. A regression checks that ordered and reversed delivery produce identical prompts.

An omitted temperature uses the engine's greedy default (0), and response metadata reports 0. Explicit temperature values are preserved. This reflects the existing engine protocol rather than changing sampling for console runs.