control-plane/src/{prompt,response_tools,tool_output}.rs (pure text logic: pinned chat template renderer, tool catalog, tool-call
parser) move by git mv to the new leaf crate crates/gateway-text. strata-control re-exports them under the same module paths
(crate::prompt, crate::tool_output keep working for tests and callers); strata-desktop-core replaces its three #[path] includes with
imports. The leleka-runtime GPU proof modules that hash prompt.rs follow the new location. The only text change in the moved files is
the relative include_str path to engine/strata. serde_json features (preserve_order + float_roundtrip) equal what both hosts already
got through unification.
Verified: cargo test strata-control + strata-desktop-core + gateway-text on the host: 504 tests, 0 failed; the 30 tests that vanish
are exactly the duplicate runtime_prompt/runtime_tool_catalog/runtime_tool_parser copies of the same 30 tests (11+2+17), which now run
once. WSL x86_64-linux cargo check --tests leleka-runtime: 62 warnings, unchanged. fmt clean on the new crate.
996 lines
72 KiB
Markdown
996 lines
72 KiB
Markdown
# Native API contract status
|
||
|
||
## Idle SSE transport
|
||
|
||
Native Responses (text, tools and buffered structured/reasoning output), Chat
|
||
Completions and Messages streams emit `: keep-alive` SSE comments after 15 seconds
|
||
without a stream event. These transport comments contain no model output, usage,
|
||
sequence number or completion signal. SSE clients must ignore comment-only frames.
|
||
The internal adapters and offline replay verifier do so. A finished stream ends
|
||
normally; keep-alive does not extend generation deadlines or retain disconnected
|
||
requests. Normal backpressure still applies; this is not a guarantee against
|
||
proxy timeouts shorter than 15 seconds or intermediaries that buffer SSE.
|
||
|
||
## Chat Completions (text/function subset)
|
||
|
||
`POST /v1/chat/completions` uses the native Responses generation path. The wire
|
||
shape follows [Chat Completions create](https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create):
|
||
JSON `chat.completion` and live SSE `chat.completion.chunk` with one indexed choice,
|
||
assistant content/function calls, `stop` / `length` / `tool_calls` finish reasons,
|
||
and a final `data: [DONE]`. SSE text deltas arrive before engine completion.
|
||
Function calls are published only after native tool validation, with a complete
|
||
argument string in one delta per call. This deliberately does not stream
|
||
unvalidated argument fragments.
|
||
|
||
Supported inputs:
|
||
|
||
- `model`, `messages` with system/developer/user/assistant text and tool results;
|
||
text strings or arrays of `{"type":"text","text":"..."}` parts;
|
||
- assistant `tool_calls` (`id`, `type: function`, `function.name/arguments`) and
|
||
tool `tool_call_id`/text; complete returned assistant messages can be reused;
|
||
- function tools, `auto`/`none`/`required` or a forced function name,
|
||
`parallel_tool_calls`, temperature and top_p, and the sampling controls listed under
|
||
"Sampling controls" below (`frequency_penalty`, `presence_penalty`, `seed`, `top_k`, `min_p`,
|
||
`repetition_penalty`, `penalty_last_n`);
|
||
- `max_completion_tokens` or the older `max_tokens` alias (not both), `n: 1`;
|
||
- `response_format` text, json_object, or json_schema containing name/schema/strict
|
||
under `json_schema`; the same native schema subset and final validation apply.
|
||
This is validation of generated output, not constrained token sampling;
|
||
- `stream` and `stream_options.include_usage`: when requested, normal chunks carry
|
||
`usage: null`, followed by a final empty-choices usage chunk before `[DONE]`.
|
||
|
||
This first subset always uses `reasoning_effort: none` (also the default here)
|
||
and `store: false`; no hidden reasoning is requested or returned. Other efforts,
|
||
storage, multiple choices, multimodal input/output, custom/namespace tools,
|
||
custom stop sequences, log probabilities,
|
||
schema descriptions, non-null refusal text and unknown fields are rejected before
|
||
worker generation. It does not implement the full upstream API or stored Chat
|
||
retrieval. Omitted optional values use existing Responses defaults, including its
|
||
output-token limit. A Chat ID is not a Responses history ID.
|
||
|
||
Usage renames native input/output/total counters to prompt/completion/total tokens,
|
||
including cached/reasoning detail counters. Incomplete output uses `length` and
|
||
does not publish a truncated tool call. An error emits the native error object
|
||
(and `[DONE]` for SSE) without a successful finish reason or final usage. Text
|
||
already streamed before final schema validation can precede that error.
|
||
|
||
Auth, 16 MiB request bodies, admission/drain/queue limits and worker cancellation
|
||
are shared with Responses. The adapter bounds each native SSE event or JSON body
|
||
at 64 MiB; exceeding it fails explicitly. A disconnected Chat stream drops the
|
||
native stream consumer, triggering existing STOP/drain isolation; a failed request
|
||
is never replayed automatically. Request text and completions are not persisted.
|
||
|
||
The CPU HTTP gate compares actual engine `GEN` token IDs and fixture outputs
|
||
against equivalent Responses with tolerance zero, including tools/continuation,
|
||
Unicode, JSON/SSE/usage, errors and live disconnect→STOP→fresh request. This is
|
||
protocol qualification only; real-model/harness rollout remains a separate gate.
|
||
|
||
## Anthropic Messages (text/client-tool subset)
|
||
|
||
`POST /v1/messages` uses the same native Responses worker, with
|
||
`anthropic-version: 2023-06-01`. It follows the [Messages request/response](https://platform.claude.com/docs/en/api/messages/create)
|
||
and [named streaming events](https://platform.claude.com/docs/en/build-with-claude/streaming)
|
||
shapes for text and client tools. This serves the configured local model, not a
|
||
Claude model or an Anthropic cloud service.
|
||
|
||
Inputs are `model`, required positive `max_tokens`, optional `system` text/blocks,
|
||
user/assistant `messages`, `tools` with name/description/input_schema, `tool_choice`
|
||
(`auto`, `any`, `tool` with name, `none`) and `disable_parallel_tool_use`, `stream`,
|
||
temperature (0..1), top_p and top_k (plus the extension controls under "Sampling controls"). Text parts join with newlines; consecutive turns of
|
||
the same role combine. This initial subset requires first and last user messages;
|
||
assistant prefill is rejected. Assistant `tool_use` carries an object `input` and
|
||
ID; user `tool_result` returns the same `tool_use_id` and text or text blocks.
|
||
Omitted result `content` means empty text; explicit null and non-text blocks remain
|
||
invalid. [Client-tool errors](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls)
|
||
with `is_error: true` are supported. Because the native template has text tool
|
||
outputs, the adapter serializes `{"content":"<normalized text>","is_error":true}`
|
||
as that call's tool output, preserving the flag and text (including escaped
|
||
control characters). Normal/`is_error: false` results retain their existing text
|
||
unchanged. Counting and serving share this conversion. This supports transport
|
||
of failures; recovery behavior still requires model qualification.
|
||
Tool names, arguments, results and choice policies reuse native validation.
|
||
|
||
Thinking is disabled (omitted or `{"type":"disabled"}`); requests are stateless.
|
||
Thinking/redacted signatures, images/documents, cache_control, nonempty
|
||
stop_sequences, server tools, metadata, structured-output options,
|
||
beta headers and unknown fields are rejected before GEN. This does not implement all Messages features or certify a Claude SDK agent.
|
||
|
||
`POST /v1/messages/count_tokens` follows the [token count response shape](https://platform.claude.com/docs/en/api/messages/count_tokens)
|
||
and returns `{"input_tokens": N}`. It accepts `model`, `messages`, optional `system`,
|
||
`tools`, `tool_choice` and disabled `thinking` from the subset above. Generation
|
||
fields (`max_tokens`, `stream`, sampling options) and unknown fields are rejected.
|
||
It uses the same serving conversion, prompt template and configured local tokenizer;
|
||
the count includes system/tool overhead and the generation prefix, without a cache
|
||
discount. It is not a Claude tokenizer estimate or a context/VRAM fit guarantee.
|
||
No worker generation or response-history writes occur, and it works while the
|
||
worker is unavailable if the tokenizer is configured. The same Messages version,
|
||
key/Bearer, body limit, admission/drain and error rules apply. CPU HTTP fixtures
|
||
compare the count to actual GEN input IDs with tolerance zero, including tool history.
|
||
|
||
JSON returns ordered text/tool_use blocks with `end_turn`, `tool_use` or
|
||
`max_tokens` stop reasons and null stop_sequence. SSE uses message_start,
|
||
content_block_start/delta/stop, message_delta and message_stop (no `[DONE]`).
|
||
Text streams before DONE; validated tool inputs arrive as one complete JSON string
|
||
in an input_json_delta. There is no fine-grained unvalidated tool streaming.
|
||
Errors use `{"type":"error","error":{"type":"...","message":"..."}}` and a named
|
||
SSE error event; failed streams never emit a successful message_stop. Partial
|
||
text can precede a final validation error. Malformed or incomplete tool syntax
|
||
fails explicitly instead of publishing a tool block.
|
||
|
||
Engine counters become known at DONE: message_start usage is provisional zero,
|
||
and the final message_delta supplies cumulative input/output/cache totals.
|
||
This uses the [SDK's optional cumulative input/cache usage fields](https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/message_delta_usage.py).
|
||
Clients must replace these totals, not add them. input_tokens excludes native
|
||
reused tokens, cache_read_input_tokens reports reuse, cache_creation_input_tokens
|
||
is zero (no provider cache-directive contract), and output_tokens is native total
|
||
output. Older clients that ignore final input/cache updates may display zero input
|
||
usage during streaming. JSON carries final totals directly.
|
||
|
||
The existing local key can be sent as `x-api-key` **only on this route**, or as
|
||
Bearer. When authentication is configured, duplicate keys or a key combined with
|
||
Authorization are rejected; other API routes retain Bearer authentication.
|
||
The route shares the 16 MiB body limit, admission/drain and cancellation rules.
|
||
The bounded native SSE reader (64 MiB/event) is shared with Chat; each adapter
|
||
buffers at most eight output events. Disconnect releases the native consumer,
|
||
sends STOP and preserves the next request. No request/response history is stored.
|
||
|
||
The actual CPU HTTP gate compares GEN tokens and fixture output to equivalent
|
||
Responses (tolerance zero), reconstructs ordered JSON from named SSE, and checks
|
||
Unicode, system/combined turns, tools/continuation, usage, headers/errors,
|
||
admission/drain and live disconnect→STOP→fresh generation. Existing Chat/auth
|
||
regressions run alongside it; real-model/harness/GPU qualification remains open.
|
||
|
||
## Sampling controls
|
||
|
||
Every route that generates (Responses, Chat Completions, Messages) takes the Original server's
|
||
sampling fields at the top level of the request body, with the Original's defaults (an absent field
|
||
keeps the engine's greedy default) and ranges, and fails closed on a value outside them
|
||
(`crates/sampler-ref` `RequestSampling`, `docs/sampler-reference.md`):
|
||
|
||
| Field | Range | Notes |
|
||
| --- | --- | --- |
|
||
| `temperature` | 0..2 | `0` is greedy (Messages: 0..1) |
|
||
| `top_p` | 0..1 | `1` disables nucleus filtering |
|
||
| `top_k` | integer >= 0 | the sampler keeps at most 64: `0` and values above 64 use 64 |
|
||
| `min_p` | 0..1 | |
|
||
| `repetition_penalty` | > 0 | `1` is off |
|
||
| `frequency_penalty`, `presence_penalty` | -2..2 | |
|
||
| `penalty_last_n` | 0..2147483647 | a penalty without a window uses the last 64 tokens; the kernel caps the history at 4096 |
|
||
| `seed` | unsigned integer | `0` or absent draws a fresh clock seed per request |
|
||
| `strata_tune` | `{pcie_frac, spec_min_p}` in 0..1 | engine settings for this request only |
|
||
| `experimental_speed_projection` | boolean | switches a loaded control vector for this request (`cvec=0|1`) |
|
||
| `reasoning_budget_tokens` | whole number, `0` = none | see "Reasoning budget" |
|
||
|
||
The worker `GEN` line is built by the same code the Python server's `StrataEngine.sampling_keys`
|
||
is checked against (`control-plane/tests/fixtures/golden/gen_lines.json`, produced by running that
|
||
code). The Chat route no longer refuses nonzero presence/frequency penalties.
|
||
|
||
Server-wide defaults fill what a request leaves out: the config `sampling` block, then the Chat
|
||
settings shared through `POST /settings`; the request always wins and an explicit `temperature: 0`
|
||
stays greedy. A shared `max_tokens` and `reasoning_effort` apply to Responses requests that carry none
|
||
(Chat and Messages fix their own effort).
|
||
|
||
### Reasoning budget
|
||
|
||
With thinking on, a request's `reasoning_budget_tokens` (else the config's) caps how long the model
|
||
may think. At the budget, on a clean token boundary (no `</think>` prefix held back, no UTF-8
|
||
character split), the worker stops the pass, appends the Original's wrap-up text
|
||
(`"I have thought about this long enough; time to give my answer.\n</think>\n\n"`) to the output
|
||
and continues from `prompt + generated + wrap-up`, so the engine keeps its cached prefix. If the
|
||
wrap-up leaves no room to answer the request ends as `length`. The client sees one token stream and
|
||
one `DONE`: `generated` counts delivered tokens, `prompt_tokens`/`reused` are the first pass's,
|
||
timings are summed.
|
||
|
||
## Operational surface
|
||
|
||
Ported from `engine/strata/serve/server.py` and replayed against the real Python handlers in
|
||
`control-plane/tests/http_surface.rs`:
|
||
|
||
- `GET /props` (llama-server compatible: default generation settings from the config and shared
|
||
settings, chat template, `models_autoload`, `is_sleeping`), `GET /slots`, `GET /v1/status`,
|
||
`GET /api/health` (the Python `/health` body; `/health` keeps the minimal liveness body);
|
||
- `GET|POST /settings` (shared Chat settings, persisted next to the config; JSON from the server's
|
||
own page or a `trusted_origins` origin only);
|
||
- `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload` (own page, JSON object, `409
|
||
model_busy` while a request runs or waits), lazy start (`engine.lazy_load`), idle unload
|
||
(`engine.idle_unload_s`), reload gates (`engine.before_load`, `engine.min_free_vram_mib`); the next
|
||
request after an unload loads the engine again;
|
||
- CORS for `/v1/*` (`cors_origins`, `"*"` allowed) with the preflight answered before
|
||
authentication; model `aliases`; unknown paths answer `{"error":{"message":"not found"}}`;
|
||
- engine stall watchdog (`engine.stall_timeout_s`): no engine line for that long during a request
|
||
ends the engine, fails the request with a clear error and uses the restart budget.
|
||
- MCP hub (`control-plane/src/mcp.rs`, tested against `engine/strata/serve/mcp_fake_server.py` in
|
||
`control-plane/tests/mcp_hub.rs`): `mcp_servers` / Claude Desktop's `mcpServers` / `mcp_config_file`
|
||
and the `mcp` block (`timeout_s`, `max_result_chars`, `max_rounds`, `start_timeout_s`) are
|
||
validated at start; stdio and Streamable HTTP servers start in the background, tools are listed
|
||
(all pages) and namespaced `<server>__<tool>`, a server that stopped is started again by its next
|
||
call, results are text capped at `max_result_chars`, failures become `error:` text, a cancelled call
|
||
sends `notifications/cancelled`. `GET /mcp` (authenticated) reports servers, state and tools
|
||
(`{"servers":[],"tools":0}` when none). Not ported on purpose: the server-side tool loop
|
||
(`strata_mcp: true`, `run_with_mcp`) of the Python web page. Responses, Chat and Messages return
|
||
tool calls to the client, so no endpoint executes MCP tools on a client's behalf.
|
||
|
||
Differences from the Python server: authentication is Bearer on every path except `/health` and
|
||
`/api/health` (the Messages routes also take `x-api-key`), unknown paths need authentication too, and
|
||
error bodies of the Rust authentication layer are its own.
|
||
|
||
## Model discovery
|
||
|
||
`GET /v1/models` returns the single configured `model` / `STRATA_MODEL_ID`, or
|
||
an empty `data` array when no ID is configured. `GET /v1/models/{id}` returns
|
||
the same record; percent-encode the ID as one path segment (including `/`).
|
||
Unknown IDs return JSON `404 model_not_found`. Both routes use existing optional
|
||
bearer authentication. Nonempty query parameters return `400 unsupported_query`;
|
||
POST and DELETE are unsupported and never install or remove a model.
|
||
|
||
The response follows the [Models list](https://developers.openai.com/api/reference/resources/models/methods/list)
|
||
and [retrieve](https://developers.openai.com/api/reference/resources/models/methods/retrieve)
|
||
object shapes: `id`, `object: "model"`, `created: 0`, `owned_by: "local"`, wrapped
|
||
in `{"object":"list","data":[...]}` for the list. `created: 0` is this runtime's
|
||
explicit unknown-timestamp sentinel; `local` identifies a local deployment,
|
||
not the upstream model owner. No model provenance metadata is inferred.
|
||
|
||
This is configuration discovery. It stays available while the worker is loading,
|
||
failed or draining and does not acquire a generation slot or touch model files.
|
||
Use `/ready` to check inference availability. Listing does not download, start,
|
||
test or certify the model, and does not expose filesystem paths or credentials.
|
||
|
||
## Input token counting
|
||
|
||
`POST /v1/responses/input_tokens` returns
|
||
`{"object":"response.input_tokens","input_tokens":123}` using the same native
|
||
history expansion, prompt template and tokenizer as generation. The shape follows
|
||
the [Responses input token count endpoint](https://developers.openai.com/api/reference/resources/responses/subresources/input_tokens/methods/count).
|
||
The local subset requires `model` and `input` and accepts the supported create-request
|
||
fields; unknown fields and unsupported live features are rejected. Instructions,
|
||
reasoning, text format and tool definitions contribute exactly as they do to the
|
||
rendered generation prompt. `previous_response_id` includes the saved transcript
|
||
and new input; new instructions replace prior instructions. Missing, deleted or
|
||
evicted parents return `404 response_not_found`.
|
||
|
||
Counting requires a configured tokenizer, but does not require a ready worker,
|
||
queue inference, create a response ID or modify history (`store` has no effect).
|
||
It always returns ordinary JSON, including when `stream: true` is supplied.
|
||
Generation-only settings are validated but do not generate output. The count is
|
||
for the full rendered prompt, not only newly evaluated tokens or a prediction of
|
||
cache reuse, output length, model quality or available context space. It does not
|
||
truncate input or guarantee the request fits the worker's context.
|
||
|
||
The route shares optional bearer auth, the 16 MiB body limit and bounded HTTP
|
||
admission with create: drain returns 503 and exhausted admission returns 429.
|
||
It remains available during worker failure when the service is not draining.
|
||
The isolated CPU test compares counts against actual `GEN` token IDs, with exact
|
||
integer equality; this does not qualify real-model inference.
|
||
|
||
## Engine activity metrics
|
||
|
||
`GET /metrics` returns JSON (`schema_version: 1`), protected by the same optional
|
||
bearer key as `/status`. This is a native JSON endpoint, not Prometheus text.
|
||
`/status` remains a stable discovery response. Metrics require the new binary;
|
||
the preserved console trial has not been upgraded to this feature.
|
||
|
||
- `active` and `active_elapsed_ms` cover an admitted generation from the attempt
|
||
to write `GEN` until engine `DONE`, `ERR`, or supervisor interruption. They
|
||
do not indicate GPU utilization or HTTP response completion.
|
||
- `queue_capacity` and `queue_used` describe the bounded command channel
|
||
(including reserved capacity), excluding the active command and HTTP handlers
|
||
waiting to enqueue. An unconfigured channel reports null. These snapshots
|
||
are observations, not an admission or safe-restart guarantee.
|
||
- `generation.started` counts admitted attempts. Context/validation rejections,
|
||
abandoned queued requests and requests rejected during restart are excluded.
|
||
`completed` counts non-cancelled DONEs, including length stops. `cancelled`
|
||
counts DONEs with cancel finish or a disconnected consumer. `failed_or_interrupted`
|
||
counts started attempts without DONE, including engine ERR, protocol failure,
|
||
expired cancellation drain and shutdown. Each attempt enters one terminal
|
||
bucket. Engine completion does not imply valid JSON/tool calls or task success.
|
||
- `done_generated_tokens`, `done_prompt_tokens`, `done_decode_ms`, and
|
||
`done_prefill_ms` sum engine DONE values, including cancelled generations.
|
||
Counts for failed attempts are unknown and excluded. Prompt counts are engine
|
||
input counts, not necessarily newly evaluated tokens. Integer totals saturate
|
||
at u64 max and timing totals at the largest finite f64.
|
||
- `done_decode_tokens_per_second` is total DONE tokens divided by total DONE
|
||
decode seconds. `last_done` exposes the last DONE's counts, milliseconds,
|
||
decode rate, raw finish reason, optional reused-token/draft/expert counters.
|
||
Unavailable counters and zero-duration/nonfinite rates are null. There is no
|
||
instantaneous token speed, prefill rate, TTFT, percentile or quality score.
|
||
|
||
Counters survive supervised child restarts and reset when the control-plane
|
||
process restarts. They contain no prompts, generated text, token IDs or keys.
|
||
Updates happen at generation boundaries; no per-token metrics lock is added.
|
||
Existing `T`/`PP`/`DONE` events are forwarded unchanged. These metrics support
|
||
observation; paired workload and quality measurements remain necessary for any
|
||
performance claim.
|
||
|
||
### Monitor members, Prometheus text and `GET /api/requests`
|
||
|
||
`/metrics` also carries the members of the Python service's Monitor (`engine/strata/serve/server.py` `Service.metrics`), added beside the
|
||
native ones above, which are unchanged (`schema_version` stays 1):
|
||
|
||
| member | content |
|
||
| --- | --- |
|
||
| `engine` | `model`, `max_context`, `images`, `version`, `api_monitor`, and `settings` (the settings the engine reports: context, prefill chunk, caches, workers) |
|
||
| `live` | `state` (`idle`, `reading`, `generating`, or the worker state while it is not ready), `active`, `queued` (generations waiting for the engine), `phase`, `prompt_tokens`, `generated`, `elapsed_s`, `tok_s`, `tok_s_mean`, `prefill_tok_s_mean`; `prompt_read`, `prompt_total`, `max_tokens` and `tok_s_window_s` are `null` (the runtime does not report them) |
|
||
| `requests`, `requests_kept` | the last 12 settled generations, newest first (`?requests=all`: every one kept, up to 500): `time`, `duration_s`, `finish` (`stop`, `length`, `cancel`, `disconnect`, `error`), `prompt_tokens`, `reused`, `output_tokens`, `engine_generated`, `prompt_ms`, `decode_ms`, `decode_tok_s`, `hit_rate`, `drafts_offered`, `drafts_accepted`; `null` where the engine did not say or the attempt had no DONE. Counts and timings only, no payload |
|
||
| `totals` | since the process started: `requests`, `prompt_tokens`, `reused`, `output_tokens`, `prompt_ms`, `decode_ms`, `drafts_offered`, `drafts_accepted` |
|
||
| `hardware`, `hardware_static`, `history` | the engine's telemetry document (GPU, host RAM, CPU, throughput) in the Python names and units (bytes, percent, watts, degrees Celsius): `gpu_util`, `gpu_mem_used`, `gpu_mem_total`, `gpu_temp`, `gpu_power`, `cpu`, `ram_used`, `ram_total`, `tok_s`, `prefill_tok_s_mean`, ...; `gpu_name`, `gpu_count`, `threads`; and `history`, the last 60 samples of the headline series (one per engine health tick, 2 s by default; a burst of ticks within a second counts once). A figure the engine does not report is absent, never zero; the three are empty while the engine publishes no telemetry (it publishes once the model is loaded) |
|
||
| `telemetry`, `time` | the raw telemetry document (the same as `/v1/status` `machine`, without its age) and the wall-clock second |
|
||
|
||
The GPU block comes from NVML; where `libnvidia-ml` cannot be loaded (WSL2, containers without the management library) the engine polls
|
||
`nvidia-smi --query-gpu=...` instead (at most every 2 s, `leleka-memory/src/smi.rs`), so the block is present on those hosts too.
|
||
|
||
**Prometheus.** `GET /metrics?format=prometheus`, or any request whose `Accept` asks for `text/plain` or OpenMetrics before JSON (what a
|
||
Prometheus scraper sends), returns the text exposition (`text/plain; version=0.0.4`) of the same document under the same bearer-key rule:
|
||
counters `leleka_generations_{started,completed,cancelled,failed}_total`, `leleka_prompt_tokens_total`,
|
||
`leleka_prompt_tokens_reused_total`, `leleka_generated_tokens_total`, `leleka_{prefill,decode}_seconds_total`, draft counters,
|
||
`leleka_memory_gate_rejections_total`; gauges `leleka_up`, `leleka_generation_active`, `leleka_requests_queued`, `leleka_queue_used`,
|
||
`leleka_context_{max,live}_tokens`, `leleka_context_used_percent`, `leleka_gpu_{utilization_percent,memory_used_bytes,memory_total_bytes,temperature_celsius,power_watts,sm_clock_megahertz}`,
|
||
`leleka_host_{memory_used_bytes,memory_total_bytes,swap_used_bytes,cpu_busy_percent}`, `leleka_engine_{resident_bytes,pinned_bytes,cpu_busy_cores}`,
|
||
`leleka_decode_tokens_per_second{window=live|last|average|lifetime}`, `leleka_prefill_tokens_per_second{window=last|average|lifetime}`,
|
||
`leleka_prefix_cache_*`, `leleka_engine_phase{phase=...}` and `leleka_info{model=...}`. Unmeasured figures are not exposed (no zeros for "unknown").
|
||
The table in `control-plane/src/prometheus.rs` is the contract. JSON stays the default for every other client.
|
||
|
||
**`GET /api/requests`** is the Python service's opt-in request monitor. It is off unless the config sets `"api_monitor": true` (then
|
||
the route answers 404, as the Original's does): it keeps prompts and answers in memory. It records `/v1/chat/completions`,
|
||
`/v1/messages` and `/v1/responses` (the Original: the first two), the last 100 of them, bounded to 256 KiB per captured text
|
||
(`input_truncated`, `output_truncated`, `reasoning_truncated`, `response_truncated`). Without `id` it lists them newest first without
|
||
payload (`{"requests": [...], "retention": 100, "persistent": false, "loaded": ..., "auto_load": ...}`); `?id=ID` returns one whole
|
||
record (`input` as pretty JSON, `output`, `reasoning`, `response` of a buffered reply, `usage`, `error`, `http_status`,
|
||
`first_token_s`, `wallclock_s`), or 404 `request no longer retained` once evicted. States: `queued` until the first generated text,
|
||
`generating`, then `completed`, `error` (an error body or HTTP status >= 400) or `disconnected` (the consumer left before the stream
|
||
ended). Headers and API keys are never captured. Differences from the Python monitor: `queue_s` and `load_s` are `null` (the wait for
|
||
the engine is not attributed per request; `live.queued` shows the queue), and there is no `/api-monitor` HTML page.
|
||
|
||
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.
|
||
|
||
For native Qwen tool parameters, a direct property `type: "string"` preserves
|
||
raw text, including quotes. A direct type array containing `"string"` now does
|
||
the same unless the text parses as a declared **non-string** JSON type. Thus
|
||
`["string", "null"]` preserves `123`, `false`, `{}` and quoted text as strings,
|
||
while the literal `null` selects null. `["string", "integer"]` selects an integer
|
||
for `123` and a string for `1.5`. This is a deterministic interpretation of an
|
||
ambiguous raw-text format, not a search for any schema-valid coercion. Full-schema
|
||
validation still runs before publishing a callable item; enum/range violations
|
||
are not retried as strings. Scalar declarations and untyped handling retain
|
||
their previous behavior. Type inference through `$ref`, `anyOf` or `oneOf` is
|
||
not added by this rule. JSON and both live SSE paths use the same decoder;
|
||
CPU fixtures verify argument equality, not real-model tool-call quality.
|
||
|
||
`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. By default 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.
|
||
|
||
### Opt-in durable history (Unix preview)
|
||
|
||
Set `response_history_dir` in the serve config or `STRATA_RESPONSE_HISTORY_DIR`
|
||
(environment wins) to an absolute dedicated directory whose parent already exists.
|
||
The service creates it with mode `0700`; an existing directory must be owned by
|
||
its user with exactly that mode. Snapshot and lock files must be owned regular
|
||
`0600` files with one link. Symlinks are refused. An OS lock permits only one
|
||
service to use the directory. `check-config` reports `durable_unchecked` without
|
||
opening, creating or locking it. `provision` also leaves history untouched.
|
||
|
||
This explicitly persists **plaintext input, tool results, and terminal responses**;
|
||
use a private external volume, outside Git. It has the same single-operator API
|
||
key scope as memory history, with no encryption or tenant separation. Changing
|
||
API keys does not erase the store. `store: false` writes nothing. Omitting the
|
||
option retains memory-only behavior. Windows durable storage is not supported.
|
||
|
||
Completed/incomplete responses, expanded continuation transcripts and input-item
|
||
IDs survive service restarts. DELETE and oldest-entry eviction are committed too.
|
||
The existing limits remain 64 responses and 128 MiB of serialized response plus
|
||
transcript data. A versioned snapshot is bounded to 129 MiB including metadata;
|
||
this is not a total resident-memory bound. Each mutation writes a full snapshot
|
||
on a blocking pool, flushes it, atomically renames it and flushes the directory
|
||
before acknowledging success. Budget space for the current and staged snapshots.
|
||
This feature is not a throughput optimization.
|
||
|
||
Startup validates the store before asset preparation, worker or listener startup.
|
||
Invalid schema, SHA-256 checksum mismatch, corruption, insecure files, excess size or an occupied lock fail
|
||
startup without resetting history. An interrupted unpublished stage is discarded
|
||
under the lock; the committed snapshot is restored. Disk failures produce the
|
||
existing `response_storage_failed` JSON error or terminal SSE `response.failed`,
|
||
never a false successful commit. Earlier text deltas may already be visible.
|
||
A failed store fences further mutations until restart; existing in-memory GETs
|
||
remain available. Failure before rename preserves the previous snapshot. Failure
|
||
after rename while flushing the directory has an **uncertain outcome**: the
|
||
request was not acknowledged, but its record can be present after restart.
|
||
A disconnected client can likewise miss an already committed result. DELETE is
|
||
logical deletion, not secure erasure of filesystem blocks or backups.
|
||
No in-progress stream, worker state, KV state or automatic retry is restored.
|
||
|
||
|
||
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.
|
||
|
||
## Stored response resources
|
||
|
||
`GET /v1/responses/{response_id}` returns the exact saved completed or incomplete
|
||
response object, including output, tool call IDs/arguments, reasoning, metadata
|
||
and usage. `DELETE` on the same path returns
|
||
`{"id":"...","object":"response.deleted","deleted":true}` and removes that
|
||
entry's response and continuation transcript. These route shapes follow the
|
||
official OpenAI [retrieve](https://developers.openai.com/api/reference/resources/responses/methods/retrieve)
|
||
and [delete](https://developers.openai.com/api/reference/resources/responses/methods/delete)
|
||
references; the implementation supports the bounded history subset described here.
|
||
|
||
- Both routes share the optional bearer authentication policy. They remain
|
||
available while draining or when the worker is unavailable; they do not invoke
|
||
the model. There is still one operator credential, without tenant isolation.
|
||
- Unknown, deleted, evicted, memory-only restarted and `store:false` IDs return
|
||
`404 response_not_found`. Repeated deletion also returns 404. Failed generations
|
||
are not stored; these routes do not poll or cancel in-progress jobs.
|
||
- Nonempty query strings return `400 unsupported_query`. Retrieval streaming,
|
||
stream resumption and optional include/query fields are not implemented.
|
||
- The shared FIFO limit is 64 entries or **128 MiB of serialized response plus
|
||
transcript data**. Both objects count toward the budget; this is not a process
|
||
RSS cap. Oversized records fail storage before publishing a successful terminal
|
||
response. Eviction removes both objects together; retrieval does not refresh
|
||
retention order. Disk storage is disabled unless explicitly configured above.
|
||
- Deletion prevents subsequent continuation using that ID. It does not erase
|
||
copies already included in descendant responses or an in-flight request that
|
||
obtained the transcript before deletion, and does not cancel generation.
|
||
|
||
These routes require the newer preview; the preserved user trial is unchanged.
|
||
CPU verification: `python3 scripts/smoke-response-history.py /path/to/strata-next`;
|
||
add `--durable` for actual process restart, corruption and disk-failure coverage.
|
||
|
||
### Input item listing
|
||
|
||
`GET /v1/responses/{response_id}/input_items` returns an authenticated list with
|
||
`data`, `first_id`, `last_id`, and `has_more`, following the documented
|
||
[OpenAI input-items route](https://developers.openai.com/api/reference/python/resources/responses/subresources/input_items/methods/list).
|
||
It accepts `order=asc|desc` (default `desc`), `limit=1..100` (default 20), and an
|
||
`after` item cursor. Unknown, duplicate or malformed query options and foreign
|
||
cursors return `400 invalid_input_items_query`; optional `include` is not supported.
|
||
|
||
This is a projection of the stored effective input, including expanded
|
||
`previous_response_id` history and excluding this response's own output.
|
||
Instructions remain a separate request field and are not added to the list.
|
||
Message text is projected into role-appropriate typed text parts. List item IDs identify occurrences
|
||
within this response and remain stable while it is retained; they replace
|
||
client item IDs in this view so duplicate IDs cannot make pagination ambiguous.
|
||
Tool `call_id`, name, namespace, arguments and custom input are unchanged.
|
||
The transcript used to render subsequent model prompts is never modified.
|
||
|
||
The route shares the configured history retention, deletion and authentication
|
||
policy. It works during drain/worker outage without generating tokens. Missing,
|
||
`store:false`, deleted and evicted responses return 404. Restart clears default
|
||
memory history; the opt-in durable store described above also preserves these
|
||
input pages. No payload logging or tenant isolation is added.
|
||
CPU HTTP coverage includes both response modes, exact tool-payload replay,
|
||
pagination, stable cursors, failure cases and no extra worker generation.
|
||
|
||
## 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.
|
||
|
||
## Date in the system prompt
|
||
|
||
The gpt-oss template writes `Current date: YYYY-MM-DD` into the system message, so the date is part of the prefix on which
|
||
a worker's KV cache is matched: with the default `prompt_date: "utc"` (or `STRATA_PROMPT_DATE=utc`) every cache misses after
|
||
it once a day, at midnight UTC. Two other values exist:
|
||
|
||
* `"YYYY-MM-DD"` pins the date for the life of the process (stable prefix; the model believes it is that day);
|
||
* `"none"` (experimental) leaves the line out, keeping the blank line that follows it, for clients that offer the date as a
|
||
function tool instead. The control plane does not host tools: the client (an agent harness or its MCP server) supplies
|
||
something like `get_current_date()` and returns an ISO date, and the model calls it when it needs the date.
|
||
|
||
The model is trained with the line. Teacher-forced on four prompts of 770-957 tokens, leaving it out moves the next-token
|
||
distribution by mean KL 0.034-0.056 (best token unchanged at 89-90% of positions); changing only the date value moves it
|
||
by 0.023-0.040 (92-93%); both are above the numerical noise of 0.005-0.023 (93-97%). Task quality was not measured, so
|
||
`none` is not the default (`benchmarks/results/prompt-date-sensitivity-2026-10-17.txt`).
|
||
|
||
## Worker pool (experimental)
|
||
|
||
`engine.extra_workers` (a list of `{ "executable": ..., "args": [...] }`, at most 7) starts further workers with the
|
||
engine's timeouts and restart budget, served together with `engine` through one dispatcher
|
||
(`control-plane/src/pool.rs`). Each worker runs one generation at a time. A request goes to an idle, ready worker,
|
||
preferring the one whose last prompt shares the longest prefix with it (each worker reuses only its own cache), with
|
||
ties to the worker listed first; while every worker is busy, requests wait in arrival order. `/ready` and `/status`
|
||
report ready only when every member is ready; status and metrics otherwise describe the first worker. A worker that
|
||
fails is restarted by its own supervisor as above; while no member can come back, waiting requests fail. Measured use:
|
||
`docs/worker-pool.md`.
|
||
|
||
The pool feeds stdio engine children through `worker::run_with_requests`, which has no administrative channel, so the
|
||
config rejects `extra_workers` together with `runtime` (a `leleka-inference` backend), `engine.lazy_load`,
|
||
`engine.idle_unload_s` (no load/unload on demand) and `vision` (images are read by the single supervised worker).
|
||
|
||
## Model families in one control plane
|
||
|
||
`engine.tokenizer_dir` selects the Qwen3.5 family (ChatML template, control-token marks, pictures, reasoning budget, the
|
||
`runtime` backend); `engine.gptoss_gguf` selects gpt-oss (Harmony prompt, tokenizer read from the GGUF) through the same
|
||
`codec::TextCodec` seam, and the two exclude each other. The gpt-oss worker's `GEN` line carries `temperature`, `top_p` and
|
||
`seed` only: a request that sets `top_k`, `min_p` or a repetition, frequency or presence penalty is refused with
|
||
`400 unsupported_parameter`, and defaults for those from the `sampling` block or the shared settings are dropped for that
|
||
family. The Qwen-only features (`vision`, `reasoning_budget_tokens` wrap-up, `runtime`) are not available for gpt-oss.
|
||
|
||
## 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:
|
||
|
||
```json
|
||
{"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](https://developers.openai.com/api/docs/guides/structured-outputs).
|
||
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, unless the
|
||
text ends on whole tool calls of declared tools (see "Tool-call parsing"); 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](https://developers.openai.com/cookbook/articles/gpt-oss/handle-raw-cot).
|
||
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. It also accepts, validates and ignores the hosted-service hints a Codex
|
||
configuration may add: `service_tier` (`auto`, `default`, `flex`, `priority`, `scale`), `user`, `text.verbosity` (`low`,
|
||
`medium`, `high`; `text.format` may then be absent and means plain text), `reasoning.effort: minimal` (served as `low`, the template's
|
||
brief-thinking instruction) and `reasoning.summary: none`. Still refused: `concise`/`detailed` summaries, `max_tool_calls`,
|
||
other `include` values and unknown 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). Optional bearer authentication is described below; it does not add TLS.
|
||
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.
|
||
|
||
### Optional bearer authentication
|
||
|
||
Set `api_key_file` in the server JSON configuration or `STRATA_API_KEY_FILE`
|
||
(takes precedence) to enable one operator credential. The source must be a
|
||
regular private file (no group/other permissions on Unix), containing 32–512
|
||
printable ASCII bytes without whitespace; an optional trailing LF/CRLF is
|
||
accepted. Total file size is bounded at 514 bytes. Invalid/missing sources fail
|
||
startup before binding or launching the engine. FIFO sources fail without
|
||
blocking. Without a configured file, previous authentication-free behavior is
|
||
unchanged; the existing trial remains in that mode on loopback.
|
||
|
||
All routes except minimal `/health` require `Authorization: Bearer TOKEN`.
|
||
Missing, wrong, malformed or repeated Authorization headers return a generic
|
||
401 `invalid_api_key` and `WWW-Authenticate: Bearer` before request parsing.
|
||
`/status` and `/ready` are protected as well. No supplied credential is echoed.
|
||
The server's retained credential state is a SHA-256 digest, compared using
|
||
`subtle::ConstantTimeEq`; the key is never sent to the engine. This is one shared
|
||
operator credential, not multi-user authorization or response-history isolation.
|
||
Changing the key requires a deliberate server restart; hot rotation is not
|
||
implemented.
|
||
|
||
Rerun `scripts/install-qwen-native.py` to upgrade an existing native launcher;
|
||
fresh installs also include key-file support. Then an authenticated endpoint can
|
||
be selected with `qwen-codex-ctl connect strata-native --url LOOPBACK_URL
|
||
--key-file PRIVATE_FILE`. Discovery validates file permissions and uses the
|
||
credential header. Agent launch configures `/bin/cat` as the provider's auth
|
||
command, with only the absolute key-file path in its arguments. The token is
|
||
not written to launcher argv, environment or generated configuration. Existing
|
||
`--no-auth` connections and `native-service` commands remain unchanged.
|
||
|
||
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.
|
||
|
||
## Custom text tools
|
||
|
||
Native Responses accepts `{"type":"custom","name":"run"}` with an optional
|
||
string description and optional `"format":{"type":"text"}`. Namespace
|
||
containers may include custom tools. Regex format has the validation-only
|
||
preview described below. Lark, unknown custom fields and non-text outputs are
|
||
explicitly rejected. `tool_choice` supports `auto`, `none`, `required`, `allowed_tools`, and forced top-level custom
|
||
tools; see [Tool choice and call count](#tool-choice-and-call-count).
|
||
|
||
Custom calls expose `type: custom_tool_call`, `input`, `name`, `call_id` and
|
||
optional `namespace`; they never expose the internal JSON `arguments` wrapper.
|
||
SSE uses `response.custom_tool_call_input.delta` and
|
||
`response.custom_tool_call_input.done`, bracketed by the normal output-item
|
||
events. The names and public fields follow the official
|
||
[custom tools contract](https://developers.openai.com/api/docs/guides/function-calling)
|
||
and [streaming events](https://developers.openai.com/api/reference/resources/responses/streaming-events).
|
||
|
||
Internally, the Qwen template receives a function with one required string
|
||
parameter named `input`. Its complete envelope is validated before a callable
|
||
item is published. The public input is unwrapped without trimming or interpreting
|
||
its contents. This uses the engine's existing tool markup and its delimiter
|
||
limitations; it adds no grammar-constrained decoding. In ordinary text streaming,
|
||
validated complete calls can appear before engine DONE. Reasoning/structured
|
||
paths retain their existing buffering rules.
|
||
|
||
Replay accepts `custom_tool_call_output` with a string or `input_text` parts,
|
||
including `previous_response_id` continuation. Call IDs, namespace identities
|
||
and function/custom output kinds must remain paired; mixed parallel outputs
|
||
are reordered by call order. No custom tool is executed by the runtime.
|
||
|
||
CPU fixtures verify transport and replay, including multiline Unicode and
|
||
whitespace, with exact equality. Real-model custom-tool quality and constrained
|
||
sampling remain unqualified; the existing GPU user trial has not been upgraded.
|
||
|
||
### Regex custom input validation preview
|
||
|
||
The native preview also accepts
|
||
`"format":{"type":"grammar","syntax":"regex","definition":"[0-9]+"}`.
|
||
The request shape and Rust regex dialect follow the official
|
||
[Regex CFG documentation](https://developers.openai.com/api/docs/guides/function-calling#regex-cfg).
|
||
Strata provides prompt guidance and complete-input validation; it does **not**
|
||
constrain token sampling. A mismatch fails the response rather than repairing
|
||
or retrying the call. This distinction applies to this preview even though the
|
||
wire format uses `grammar`.
|
||
|
||
The entire input must match, including whitespace and Unicode; a substring match
|
||
is insufficient. Valid input is returned byte-for-byte. A completed call is
|
||
validated before its item-added, input delta or done events. Invalid input
|
||
produces a JSON generation failure or terminal `response.failed`; no callable
|
||
item for that invalid call is published. Earlier valid calls/text in a stream
|
||
cannot be retracted. Namespace lowering and continuation preserve their existing
|
||
identities and exact inputs. Replayed historical calls are not revalidated under
|
||
new tool definitions.
|
||
|
||
Definitions must be nonempty single-line strings, at most 8192 bytes; use escaped
|
||
`\n` to match newlines. Each request allows at most 32 regex tools and 64 KiB of
|
||
definitions, including namespaced tools. Each compiled regex and DFA cache has a
|
||
1 MiB limit; AST nesting is limited to 64. Lookarounds, backreferences, lazy
|
||
repetitions, verbose (`x`) and swap-greed (`U`) flags are rejected before inference,
|
||
as are malformed/unknown format fields and Lark. These are compilation/cache
|
||
bounds, not a total runtime memory or latency guarantee. Existing unformatted
|
||
and explicit text custom tools retain their semantics.
|
||
|
||
## Tool choice and call count
|
||
|
||
`tool_choice` omitted or `"auto"` preserves automatic tool selection.
|
||
`"none"` hides current tool declarations from the prompt and prevents any
|
||
generated callable item from being published. Declarations are still validated,
|
||
response metadata preserves the caller's tools/choice, and historical calls and
|
||
results remain in the replay transcript. Literal text that resembles tool markup
|
||
with no declared tools remains text, as in the existing no-tools path.
|
||
|
||
`parallel_tool_calls: false` permits zero or one function/custom call per
|
||
response, across all namespaces. Prompt guidance asks for at most one call;
|
||
the server enforces the count. Default/true permits multiple calls. These wire
|
||
semantics follow the official [tool-choice and parallel-call documentation](https://developers.openai.com/api/docs/guides/function-calling#tool-choice).
|
||
|
||
`"required"` requires at least one function/custom call at successful completion.
|
||
It needs a nonempty callable catalog (400 otherwise); together with
|
||
`parallel_tool_calls: false` it requires exactly one call. Namespaced calls
|
||
participate in the same count.
|
||
|
||
`{"type":"function","name":"lookup"}` forces exactly one call to the declared
|
||
top-level function `lookup`, regardless of the parallel flag. Missing/unknown
|
||
names, custom tools selected as functions and extra selector fields fail with
|
||
400 before inference. A name is never treated as an internal namespace alias.
|
||
`{"type":"custom","name":"patch"}` likewise forces exactly one declared
|
||
top-level custom tool. Its text input is restored without modification; an
|
||
optional supported regex format is still validated before publication. The
|
||
selector must match the original tool's type, not its internal function lowering.
|
||
This [official custom selector example](https://developers.openai.com/cookbook/examples/partners/aws/openai_models_with_amazon_bedrock#44-use-a-custom-text-tool)
|
||
uses the same type/name shape. Forced namespaced selectors remain unsupported.
|
||
Unsupported choice kinds return 501; no choice is silently replaced with auto.
|
||
|
||
`{"type":"allowed_tools","mode":"auto","tools":[{"type":"function","name":"lookup"}]}`
|
||
restricts new calls to a subset of declared top-level function/custom tools.
|
||
`mode: "required"` also requires at least one allowed call on successful
|
||
completion, as specified in the official [allowed-tools mode schema](https://github.com/openai/openai-python/blob/main/src/openai/types/responses/tool_choice_allowed_param.py).
|
||
The full declarations and historical calls/results remain in the prompt and
|
||
response metadata. Prompt guidance identifies the subset; the server rejects
|
||
disallowed calls before publishing their item or input/argument events.
|
||
This does not guarantee prompt-cache reuse or model compliance.
|
||
|
||
The envelope accepts exactly `type`, `mode`, and `tools`; each selector accepts
|
||
exactly `type` and `name` matching its original declaration. Missing fields,
|
||
unknown names, wrong types, duplicate selectors, namespaced/internal aliases,
|
||
built-in tool selectors and extra fields return 400 before generation.
|
||
An empty auto subset permits text only; an empty required subset is rejected.
|
||
Multiple allowed calls are permitted unless `parallel_tool_calls: false`.
|
||
|
||
These policies add prompt guidance while retaining declarations and history.
|
||
Their minimum count applies only to successful completion: a token-limit
|
||
`incomplete` response may contain no complete call. Wrong names and excessive
|
||
counts remain invalid even for incomplete responses. Initial streaming envelopes
|
||
are not subjected to a completion minimum. Original choice metadata is echoed.
|
||
|
||
Buffered output that violates the policy fails with 502 before any callable
|
||
output is returned. In ordinary live SSE, a first valid call may already have
|
||
been published: a second call is rejected before its item/argument/input events,
|
||
and the stream ends with `response.failed`. Forced choice rejects a wrong first
|
||
call before publishing it; required choice with zero calls fails at completion.
|
||
Under none, no callable item is
|
||
published. Earlier valid text/calls cannot be retracted. Reasoning/structured
|
||
paths keep their existing buffering behavior. The runtime does not truncate
|
||
or retry tool calls and repairs them only as listed under "Tool-call parsing"; these policies do not implement constrained sampling
|
||
or parallel GPU requests.
|
||
|
||
## Tool-call parsing
|
||
|
||
The Qwen model writes a call as `<tool_call>`, `<function=NAME>`, one `<parameter=P>` ... `</parameter>` per argument,
|
||
`</function>`, `</tool_call>`. `crates/gateway-text/src/tool_output.rs` reads it; a call is published only after it is whole, and an
|
||
argument value is the exact text between its tags. The specimens that pin this are listed in
|
||
[tool-call-corpus.md](tool-call-corpus.md). This section is what a client can observe.
|
||
|
||
**Quoted calls inside a string argument stay inside it.** A `write` whose `content` documents or tests the call format
|
||
(a quoted whole call, a heredoc that prints one) is delivered with its `content` exact, in a streamed and a buffered response
|
||
alike. Before this change the argument was cut at the first quoted close and the rest
|
||
was published as plain text without an error. A value ends at the first `</parameter>` that is followed by the next
|
||
`<parameter=` or by `</function>` and that does not belong to a call the value itself quotes (the quoted `<function=NAME>`
|
||
openers before it, each followed by `<parameter=` or `</function>`, must not outnumber the `</function>` closers before it).
|
||
A call whose value opens a quoted call and never closes it is treated as unterminated, and is an error, not cut at the first
|
||
plausible close. Known limits: a value that quotes only the tail of a call (`</parameter></function>` with no opener) still ends there; and a
|
||
value that reopens its own parameter (`</parameter><parameter=content>` inside `content`) is still a parameter written twice,
|
||
which is refused as `duplicate tool parameter` and not merged into one argument.
|
||
|
||
**Accepted although a delimiter is missing.** Each of these used to fail the response (`response.failed` or 502
|
||
`tool_call_parse_failed`) and is now a call. Each is logged on the server's stderr as
|
||
`tool call accepted beyond the template form (closers supplied: N, arguments repaired: M)`; nothing else changes in the response.
|
||
|
||
* `</function>` left out: `</parameter>` followed by `</tool_call>` ends the value and the call, but only when no `</parameter>`
|
||
followed by `<parameter=` or `</function>` ends the value (so a value that quotes `</parameter></tool_call>` and has a real
|
||
close later is read whole). A streamed response delivers such a call when the generation ends, not when its `</tool_call>`
|
||
arrives, because only the end of the generation can tell the two readings apart.
|
||
* `</tool_call>` left out: the call is whole when the next `<tool_call><function=NAME>` follows its `</function>`, or when its
|
||
`</function>` is the end of a generation that stopped by itself (finish `stop`). A generation cut by the token limit (finish
|
||
`length`) never gets this; it stays an error.
|
||
* A call inside the reasoning: a generation that stops by itself without `</think>` and whose text ends on whole calls of declared
|
||
tools is read as reasoning followed by those calls, when the first call stands at the start of a line outside a code fence and
|
||
outside inline code and nothing but whitespace or further calls follows. The reasoning item is the text before the calls
|
||
and is `completed`. The calls' text has already been streamed as `response.reasoning_text.delta` (a stream cannot take it
|
||
back), so the deltas of that response contain the call markup that the final reasoning item and its `done` events do not. Without
|
||
such calls the old failure (`reasoning ended without </think>`) stands; so does a `</think>` that follows the calls.
|
||
* A slightly damaged array or object argument: for a parameter declared `array` or `object` (and not a union with `string`),
|
||
a trailing or doubled comma, single quotes, Python's `True`/`False`/`None`, extra closing brackets at the end, and an
|
||
array or object written as a JSON string of itself are read as written. Nothing is invented or dropped: brackets left open,
|
||
a bare string where a member belongs, a missing colon, an unknown word and a string cut short are not repaired and are
|
||
delivered as before (a string, which the argument schema then rejects). String parameters are never touched.
|
||
|
||
**Not accepted (unchanged): a call for an undeclared tool** is an error, `undeclared function in tool call: NAME`, as a failed
|
||
response; it is never run and never published as text. Upstream Strata returns it as plain text and counts it. The choice here
|
||
is deliberate: text without a call ends an agent's turn as if it were the answer, while a failed response is retried by the client
|
||
(a recorded session survived one such failure that way, `docs/e2e-run.md`). The exception stays that an undeclared `apply_patch` is
|
||
run through the declared shell tool. Also unchanged: a call cut by the token limit, a duplicate parameter, prose that names the
|
||
`<tool_call>` tag, and a call that quotes a code fence are not recovered (they stay failures or are read as before); see the table in
|
||
[tool-call-corpus.md](tool-call-corpus.md).
|
||
|
||
### Tool-call recovery (experimental)
|
||
|
||
`tool_call_recovery` is **off by default and experimental**. It is not part of the default contract above and has not passed a quality
|
||
gate. Turn it on with `"tool_call_recovery": true` in the control-plane config file, or with `STRATA_TOOL_CALL_RECOVERY=1` in the
|
||
environment (`0`/`false` turns it off and wins over the file; any other value stops the start). It is read once at start, so a
|
||
change needs a restart; the start logs `tool_call_recovery is ON (experimental)` when it is on.
|
||
|
||
With it on, a call for a **declared** tool that the model wrote next to the template form is read as that call instead of failing the
|
||
response or being shown as text:
|
||
|
||
* `<parameter=NAME>` where `<function=NAME>` belongs (after `<tool_call>`);
|
||
* `<tool_call>` followed by `<=NAME>`, `<function:NAME>`, `<function =NAME>` or `<NAME>`;
|
||
* a JSON object `{"name": NAME, "arguments": {...}}` inside `<tool_call>` (also in a Markdown fence; `arguments` may be a JSON string);
|
||
* a bare `<function=NAME>` ... `</function>` with no `<tool_call>`, only at the start of a line outside a code fence and outside
|
||
inline code (a stray `</tool_call>` after it is dropped);
|
||
* a second call in the same `<tool_call>` (opened by `<function=` or `<parameter=NAME>` after the first `</function>`);
|
||
* for array/object arguments, also brackets left open at the end (closed) and a bare string where an object member belongs (dropped).
|
||
|
||
An undeclared name is still an error in every form; nothing is run that the request did not declare. Every call read this way is
|
||
logged as `tool call accepted beyond the template form (... drifted forms recovered: N)`. A streamed response delivers a batch when its
|
||
`</tool_call>` arrives and a bare call when the text after it shows it is over (or at the end).
|
||
|
||
Risks, which is why it stays off: a bare `<function=NAME>` that starts a line is run even when the model only meant to show it (outside
|
||
a code fence); closing open brackets can drop elements the model never finished; and these readings were checked only against the
|
||
41 Qwen specimens of the upstream corpus ([tool-call-corpus.md](tool-call-corpus.md): 24 read as upstream expects with it off, 30 with it
|
||
on), not on this model's own sessions. Upstream turned its equivalent on by default in 0.2.8 on a reporter's 1,462-turn corpus
|
||
(98.3 % of turns read as intended with it, 92.9 % without; Qwen3.8 under Claude Code). Before this is made the default here it needs the
|
||
charter's treatment: replay of captured failed outputs (`STRATA_DEBUG_FAILED_OUTPUT=1`) with and without it, and a paired run of a real
|
||
agent workload with a quality result.
|
||
|
||
## Active generation deadline
|
||
|
||
An operator can opt into `engine.generation_timeout_s` /
|
||
`STRATA_GENERATION_TIMEOUT_S` (1–86400 seconds, absent means disabled).
|
||
The deadline covers an active command, including worker pipe and result-channel
|
||
backpressure. It excludes request parsing, tokenization and command queue wait.
|
||
It is an absolute execution budget, not an idle-token timer or client end-to-end
|
||
deadline. Timeout fails the worker, kills/reaps it and uses the existing finite
|
||
restart policy. No active or queued request is replayed.
|
||
|
||
For a connected client consuming its response, buffered requests return 502
|
||
`generation_failed` with `generation exceeded configured execution deadline`;
|
||
SSE ends in `response.failed`, retaining its preceding event sequence. The
|
||
generation counts once as failed/interrupted. Failure delivery after process
|
||
cleanup is bounded to one second; a full streaming channel is then closed,
|
||
and the adapter emits a failure once the consumer drains buffered events.
|
||
Delivery cannot be guaranteed to a disconnected/non-reading client. This setting
|
||
does not replace HTTP/proxy timeouts. The default leaves existing long-context
|
||
generation behavior unchanged.
|
||
|
||
## Admission lifecycle
|
||
|
||
`POST /admin/drain`, `POST /admin/resume` and `GET /admin/lifecycle` expose the
|
||
native [maintenance drain protocol](../deploy/README.md#drain-before-maintenance).
|
||
They use the existing optional bearer gate. During drain, new Responses
|
||
requests fail with 503 `runtime_draining` before request-body validation;
|
||
previously admitted work continues. `/ready` returns 503 and `/status.ready`
|
||
becomes false. Response protocol events and worker output remain unchanged.
|
||
|
||
The configured `max_in_flight_requests` (default 17, range 1–256, overridden by
|
||
`STRATA_MAX_IN_FLIGHT_REQUESTS`) bounds concurrent POST Responses handlers before
|
||
JSON parsing or tokenization. A request holds capacity through response-body
|
||
completion/drop. When full, additional POST requests receive HTTP 429,
|
||
`Retry-After: 1`, and error code `runtime_overloaded`. Authentication runs first;
|
||
drain's 503 takes precedence over overload. Transient overload does not change
|
||
readiness. Health, management and stored-response GET/DELETE remain accessible.
|
||
Lifecycle reports `max_in_flight_requests` and `available_request_slots` (capacity
|
||
minus tracked requests, independent of drain mode); `check-config` reports the
|
||
configured maximum.
|
||
|
||
This bounds HTTP inference handlers, not GPU slots or generation jobs. The
|
||
worker still executes serially. On disconnect the HTTP guard can be released
|
||
while a generation's separate guard waits for STOP cleanup. This is not a cap
|
||
on TCP connections, total process memory, or GPU memory, and does not implement
|
||
batching. Admitted requests retain the existing queue and response semantics.
|
||
|
||
### Signal shutdown grace
|
||
|
||
Top-level `shutdown_grace_s`, overridden by `STRATA_SHUTDOWN_GRACE_S`, accepts
|
||
integer seconds 0–20; default 0 preserves immediate worker interruption.
|
||
`check-config` reports the effective value. With positive grace, SIGTERM/SIGINT
|
||
sets irreversible admission drain, makes readiness false and waits for both
|
||
tracked HTTP requests and generation jobs to reach zero, up to the deadline.
|
||
Already admitted requests can enqueue and finish during this interval. New
|
||
requests receive 503 `runtime_draining` while the listener remains open.
|
||
|
||
Lifecycle adds `shutting_down`. After a signal, `/admin/resume` returns the
|
||
current lifecycle with both `shutting_down` and `draining` true; it cannot reopen
|
||
admission. Ordinary administrative drain/resume remains reversible. The wait
|
||
ends early when both counters clear (checked every 25 ms), or on expiry proceeds
|
||
to existing worker interruption/QUIT and HTTP shutdown. A signal does not imply
|
||
that every request will finish: expiry can produce failed responses.
|
||
|
||
This setting bounds the admission drain phase only. Worker/process and HTTP
|
||
connection cleanup follow it. The rendered systemd unit retains its 45-second
|
||
hard stop; the 20-second grace cap reserves time for worker cleanup. Standalone
|
||
execution has no new overall exit deadline. For longer maintenance, explicitly
|
||
drain and wait before sending the stop signal.
|
||
|
||
## Runtime backend (text-level engine)
|
||
|
||
With a `runtime` block in the configuration (`control-plane/config.runtime.example.json`) the same Responses, Chat and Messages
|
||
routes run in front of a `leleka-inference` process over the `leleka.runtime.v1` gRPC contract instead of a stdio engine child.
|
||
The engine contract is text in, text out, so the surface differs from the stdio engine in these ways (see
|
||
`docs/api-over-rust-engine.md`): the prompt is sent as the rendered template text after a round-trip check against the token ids
|
||
that were counted; text deltas are re-tokenized for the HTTP layer with a byte-equality check, `<|im_end|>` / `<|endoftext|>`
|
||
end the text and cancel the engine generation, `usage.output_tokens` is the engine's own count and `reasoning_tokens` an
|
||
approximation bounded by it; images, `reasoning_budget_tokens`, `strata_tune` and `experimental_speed_projection` are
|
||
refused with an error; a default `max_output_tokens` is clamped to `runtime.max_output_tokens` (4096, the runtime's cap) and a larger
|
||
explicit value is refused; `/unload` is `unsupported` because the runtime's lifecycle belongs to its operator. A terminal event
|
||
(`response.completed`, `response.incomplete` or `response.failed`) ends every stream, including when the engine dies.
|