Files
museion/docs/research/native-llm-providers.md
T
AlexKucera 5ad605eb3c feat(settings): profiles write path + Test Connection (#136)
Profiles S3 over the S2 shell: every Settings change now persists.

Model/effort writes ride the engine's own CLI — `hermes -p <profile>
config set/unset` for model.provider / model.default /
model.reasoning_effort / model.base_url (zai endpoint family written
LAST: setting model.provider clears a stale base_url, live-probed;
unset-when-absent is idempotent success). Provider keys upsert
VAR=value into ALL THREE profiles' .env — a key entered before any
surface is on its provider still persists and pre-lands for any later
switch (maintainer ruling 2026-10-28; no switch re-fire). 0600,
foreign lines preserved byte-for-byte, line-broken values refused at
the shared sink (env-file injection guard), NSLock serializes the
read-upsert-write across concurrent provider writes.

Hydration reads model blocks and keys back at pane open — a restart
neither blanks the key fields nor refuses Test Connection; an edit
made mid-read owns the truth (no stomp), and a custom z.ai base_url
seeds the endpoint field instead of being clobbered to a family
default. Per-target writes coalesce AND chain past the debounce
guard: cancellation can't stop a past-the-guard CLI write, so the
newer write queues — the last edit is always the last write to land
(finish-audit race fix, pinned).

Test Connection = two-step probe (GET /models, then a minimal
streaming chat) with honest decode per the factsheet: zai 1113 →
wrong key type, 401s → auth failed (Anthropic request_id),
finish=length → starved, empty 200 → request failed, errors riding a
2xx decoded as the provider error.

Live-probed wire corrections (dogfood, 2026-10-28): Content-Type
application/json on every request — URLSession defaults to
form-urlencoded and providers diverge (zai 200+envelope, OpenAI 400,
Anthropic tolerates); OpenAI speaks the Responses API (/responses,
input + max_output_tokens, flagship gpt-6.1-sol); probe token cap 512
(64 starved reasoning models into "no content"); OpenAI's
"error": null event snapshots don't decode as failures.

Finish-audit (ponytail + security + general reviewers): write-ordering
race + .env lost update + hydrate stomp + custom-endpoint clobber
fixed and pinned (one-shot hold / latched read knobs in the test
double); ~30 lines of dead flexibility cut (keyType protocol param,
works(reply:) payload, unused timeout knob, double JSON round trips).

Suite 468/468 xcresult-verified; swiftlint clean; factsheet §6
correction logged. Closes #136
2026-10-27 18:32:30 +01:00

327 lines
19 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Native LLM provider factsheet — z.ai / Anthropic / OpenAI
Research artifact for #127, feeding ADR-0014 (native direct-HTTP mentor engine, #128/#125).
Method: official docs **and** live probes run 2026-10-23 against the real endpoints (keys from
`.secrets`, read at runtime, never printed; probe scripts in `~/.hermes/cache/scratch/probe_*.py`,
shapes reused from `prototypes/model-bench/bench.py`). Every "LIVE" claim below was reproduced on
the wire today. Where docs and the wire disagree, both are recorded and the wire is called out.
---
## 1. z.ai (GLM) — two endpoint families
### 1.1 Endpoints & auth
| Surface | Base URL | Protocol |
| --- | --- | --- |
| Coding Plan, OpenAI-compatible (what Museion would use) | `https://api.z.ai/api/coding/paas/v4` | OpenAI chat-completions |
| Coding Plan, Anthropic-compatible (Claude Code) | `https://api.z.ai/api/anthropic` | Anthropic messages |
| Coding Plan, OpenAI Responses (Codex) | `https://api.z.ai/api/v1` | OpenAI Responses |
| Standard pay-as-you-go | `https://api.z.ai/api/paas/v4` | OpenAI chat-completions |
- Auth everywhere: `Authorization: Bearer <key>`. No extra headers, no version header.
- The endpoint family is keyed by **key type/subscription** (coding-plan vs standard), not by model.
- **Compliance (first-party):** "The GLM Coding Plan is limited to use within the following
officially supported tools and product environments; users may not use their subscription
benefits for tools or scenarios outside of this scope" — `docs.z.ai/devpack/tool/others`. A
coding-plan key embedded in shipped Museion is outside that scope; standard PAAS keys are the
distribution-clean path. Coding plan is fine for maintainer dogfooding.
### 1.2 `/models` listing
`GET {base}/models` — LIVE, HTTP 200 on **both** families, identical payload:
```json
{"object": "list", "data": [
{"id": "glm-4.5", "object": "model", "created": 1753632000, "owned_by": "z-ai"}, ...
]}
```
- 11 entries: `glm-4.5, glm-4.5-air, glm-4.6, glm-4.7, glm-5, glm-5-turbo, glm-5.1, glm-5.2,
glm-5.3, glm-5.3-flash, glm-5.3-flashx`. No paging, no capability metadata, no reasoning
variants — the GLM-5.x line is *always-thinking*, so there is no `-thinking` model id to select.
- **Trap (verified): the coding key lists models on BOTH `/coding/paas/v4/models` and
`/paas/v4/models`.** A green `/models` response therefore proves nothing about key-type ↔
endpoint pairing. (For the full mismatch story see §1.6.)
### 1.3 Chat + streaming wire format
OpenAI chat-completions dialect. Reasoning rides a **side-channel field**, not the content:
- Non-stream: `choices[0].message.reasoning_content` (str, may be absent/empty) plus `.content`.
- Stream: `choices[0].delta.reasoning_content` chunks precede content chunks; `usage` arrives in a
late chunk (`prompt_tokens`, `completion_tokens`, `completion_tokens_details.reasoning_tokens`);
final `data: [DONE]`.
- Required/meaningful params for GLM-5.x: `thinking: {"type": "enabled"}` +
`reasoning_effort` (see §1.5); examples in docs pin `temperature: 1.0`.
- Context/output: GLM-5.3 = 1M context, 128K max output, text-only (`glm-5.3-flash` adds vision).
**Streaming cadence — content streams live; the earlier "flush" reading was a benchmark artifact (CORRECTED 2026-10-23):**
an initial probe + bench read content as one end-of-turn flush; a chunk-timing re-probe (3 request shapes,
incl. the exact bench shape) falsifies that. z.ai streams BOTH channels live in small chunks (≤15 chars):
reasoning_content deltas during thinking, then content deltas from the moment thinking ends —
489–512 content chunks spread over 4.3–13.3 s per ~550-token essay, first content chunk exactly at
last-reasoning timestamp (probe B: reasoning 1358 chunks over 29.5 s, content first@31.9 s = reasoning last@31.9 s).
The "flush" had two sources: (1) arithmetic — `completion_tokens` INCLUDES reasoning tokens, so
`out_tok / (wall − content_ttft)` divides thinking tokens by the content window and inflates tps ~8×
(bench "809 tok/s" → real ~100 tok/s content); (2) micro-probes with tiny outputs — a few dozen tokens
generated in <0.5 s legitimately look like a burst. Consequence for Museion: both channels render live;
the only silent window is thinking itself (content-TTFT = thinking duration), which is real latency, not buffering.
### 1.4 Function calling (submit_fix_cards-style typed tool)
OpenAI tools dialect; `tool_choice` supports **`auto` only** (z.ai function-calling docs).
```json
{"model": "glm-5.3", "thinking": {"type": "enabled"}, "reasoning_effort": "low", "max_tokens": 24000,
"messages": [...],
"tools": [{"type": "function", "function": {
"name": "submit_fix_cards",
"description": "Submit ranked fix cards from a critique pass.",
"parameters": {"type": "object",
"properties": {"cards": {"type": "array", "items": {"type": "object",
"properties": {"title": {"type": "string"}, "problem": {"type": "string"},
"fix": {"type": "string"}, "anchor": {"type": "string"}},
"required": ["title", "problem", "fix"]}},
"verdict": {"type": "string"}},
"required": ["cards", "verdict"]}}]}
```
LIVE (coding endpoint, streamed): the tool call arrived as a **single delta** — `delta.tool_calls[0]`
with complete `id` (`call_…`), `index: 0`, `type: "function"`, `function.name` and the **entire
arguments JSON in one fragment** (not OpenAI-style incremental fragments), then
`finish_reason: "tool_calls"`. The client must still tolerate fragmented arguments (the wire
shape allows it); don't rely on either cadence.
### 1.5 Parameter quirks + budget rules
- **GLM-5.3 cannot meaningfully disable thinking.** Docs: `thinking.type` supports `enabled` only;
"Disabling reasoning is no longer supported"; migration notice claims `disabled` *fails* the
request (`docs.z.ai/guides/llm/glm-5.3`). **LIVE divergence:** `thinking.type: "disabled"` is
*accepted* today on **both** families (HTTP 200, `reasoning_tokens: 0`) — the devpack docs
describe the compat layer converting `disabled`→`low` ("still performs lightweight thinking").
Treat `enabled` + explicit `reasoning_effort` as the only stable wire format; never send
`disabled` because docs say it may fail and it doesn't do what it looks like it does.
- **`reasoning_effort` accepted enum is wider on the wire than in the model docs.** LIVE invalid
value → HTTP 400 `{"error":{"code":"1210","message":"reasoning_effort must be one of: none,
minimal, low, medium, high, xhigh, max"}}`. GLM-5.3 docs define the three real levels
`low`/`high`/`max` (Lightweight/Enhanced/Deep, **default `max`**); the coding plan maps the wide
enum down: `none|minimal|low → low`, `medium|high → high`, `xhigh|max → max` (devpack docs;
unknown strings → 400 on the chat wire, not the documented "fallback to max" which lives in the
Claude-Code compat layer). Omitting the params entirely = default `max` (LIVE: request with no
thinking params still emitted reasoning tokens).
- **Reasoning tokens count inside `max_tokens`; small caps starve output silently (LIVE,
reproduced):** `max_tokens: 1024` + `reasoning_effort: "max"` + a demanding prompt → **HTTP 200**,
`finish_reason: "length"`, `content: ""`, `completion_tokens: 1024` of which
`reasoning_tokens: 1007`. No error anywhere. Bench confirms at scale: pass1/pass2 with 24k caps
burned 8.1k–12.9k tokens on reasoning before any prose. Rules for the native client: cap
reasoning-heavy passes at ≥ 24k (or omit the cap); gate success on `finish_reason` + content
length, never on status code; treat `finish=length` + empty content as "budget starved", not
"model broke".
### 1.6 Error shapes (Test Connection decoding)
| Signal | Shape | Meaning |
| --- | --- | --- |
| Bad key (LIVE) | 401 `{"error":{"code":"401","message":"token expired or incorrect"}}` | auth failed |
| Bad enum (LIVE) | 400 `{"error":{"code":"1210","message":"reasoning_effort must be one of: …"}}` | param dialect |
| Key/endpoint mismatch | 1113 `Insufficient balance` (skill lore; **not reproducible today** — see below) | misleading: wrong family, not empty account |
| Starved budget | 200 + `finish_reason:"length"` + empty content | not an HTTP error at all |
**LIVE correction to the seed trap list:** with today's coding-plan key, both `/models` *and* a
minimal chat call succeeded on the **standard PAAS** base URL (200 both). The "mismatch = 1113"
behavior did not reproduce in any direction available to us, and no 1113 appears anywhere in
`prototypes/model-bench/results/`. Keep 1113 in the decoder (it's cheap), but a Test Connection
must not use `/models` alone as the pairing check — issue a real (tiny) chat call per configured
endpoint.
---
## 2. Anthropic
### 2.1 Endpoints & auth
- `POST https://api.anthropic.com/v1/messages`, `GET https://api.anthropic.com/v1/models`.
- Headers: `x-api-key: <key>` + `anthropic-version: 2023-06-01` (worked live; docs examples now
show `2026-10-21` — pin a version, don't send none). No Bearer.
### 2.2 `/models` listing (LIVE)
```json
{"data": [{"type": "model", "id": "claude-haiku-5-5", "display_name": "Claude Haiku 5.5",
"created_at": "2026-10-07T18:00:00Z", "line": "haiku",
"max_input_tokens": 1000000, "max_tokens": 128000,
"capabilities": {"batch": {"supported": true}, "citations": {"supported": true}, ...}}],
"has_more": false, "first_id": "...", "last_id": "..."}
```
- 14 models today (`claude-haiku-5-5` … `claude-sonnet-4-5-20250929`); richest listing of the three
(per-model token ceilings + capability flags) — harvest it for client-side model metadata.
- Cursor paging: `limit` (1–1000, default 20), `after_id`/`before_id`, `has_more`/`first_id`/
`last_id`; `lifecycle` filter (`active`/`deprecated`/`retired`; default = active+deprecated).
### 2.3 Chat + streaming wire format
Native messages API: `messages`, top-level `system`, **required** `max_tokens`. SSE is a typed
event stream, not OpenAI chunks. LIVE event order with thinking on (claude-sonnet-5-5):
```
message_start (usage.input_tokens)
→ content_block_start (type=thinking)
→ content_block_delta:thinking_delta … → content_block_delta:signature_delta
→ content_block_stop
→ content_block_start (type=text) → content_block_delta:text_delta … → content_block_stop
→ message_delta (stop_reason + usage.output_tokens) → message_stop (+ ping keepalives)
```
**Reasoning surface changed for the 5.x line (LIVE + docs):**
- `thinking: {"type": "adaptive"}` is the only accepted shape on claude-*-5-5 *and* claude-opus-5
(LIVE both): classic `{"type": "enabled", "budget_tokens": …}` → 400
`"thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and
"output_config.effort"`. Errors doc: "Claude 4.7 and later models have removed extended thinking."
- Effort now rides `output_config.effort` ∈ **`low | medium | high | xhigh | max`** (LIVE: invalid
value → 400 `output_config.effort: Input should be 'low', 'medium', 'high', 'xhigh' or 'max'`).
`adaptive` alone (no effort) is valid; the model decides when to think.
- Legacy budget validation still exists below the type check: `budget_tokens` floor is 1024
(LIVE 400: "Input should be greater than or equal to 1024").
- Thinking output streams as `thinking_delta` + `signature_delta` blocks; earlier `message_stop`
semantics (multi-block content array with `{"type":"thinking", "thinking": …, "signature": …}`
blocks in the non-stream response) still apply.
- Thinking tokens bill as output tokens inside `max_tokens` — same starvation math as GLM; keep
`max_tokens` comfortably above expected thinking.
- No OpenAI-compat layer on api.anthropic.com; ignore it for the native client.
### 2.4 Function calling (typed tool)
```json
{"model": "claude-sonnet-5-5", "max_tokens": 2048, "messages": [...],
"tools": [{"name": "submit_fix_cards",
"description": "Submit ranked fix cards from a critique pass.",
"input_schema": { …same JSON Schema as §1.4… } }]}
```
Streaming shape (LIVE): `content_block_start` with `content_block.type == "tool_use"` carrying
`id` + `name`, then a run of `content_block_delta` with `delta.type == "input_json_delta"` and
`delta.partial_json` string fragments (LIVE: 20 incremental fragments — genuinely streamed, unlike
z.ai's single flush), then `content_block_stop`, `message_delta` with `stop_reason: "tool_use"`.
Non-stream: `content[]` block `{"type": "tool_use", "id": "toolu_…", "name": …, "input": {…}}`
(already-parsed object — no JSON.parse needed).
**Forced tool choice is gone on 5.5 (LIVE):** `tool_choice: {"type": "tool", "name": …}` (and
`"any"`) → 400 `"tool_choice: type 'tool' and 'any' are not supported for this model."` — only
`auto` (and `none`). Museion's "must emit fix cards" contract has to be prompt-enforced on
Anthropic, not wire-enforced.
### 2.5 Error shapes
Envelope: `{"type": "error", "error": {"type": …, "message": …}, "request_id": "req_…"}` — always
surface `request_id` in diagnostics. Map: 400 `invalid_request_error`, 401
`authentication_error` (LIVE bad key: `"invalid x-api-key"`), 402 `billing_error`, 403
`permission_error`, 404 `not_found_error`, 429 `rate_limit_error` (spend-cap 429 has **no**
`retry-after` and persists until the cap resets), 500 `api_error`, 529 `overloaded_error`.
---
## 3. OpenAI
### 3.1 Endpoints & auth
- `POST https://api.openai.com/v1/chat/completions`, `GET https://api.openai.com/v1/models`;
`Authorization: Bearer <key>`.
### 3.2 `/models` listing (LIVE)
`{"object": "list", "data": [{"id": "gpt-6-sol", "object": "model", "created": …, "owned_by": …,
"shutdown_date": null}, …]}` — **135 entries**, no paging, no capability metadata, and it lists
everything (whisper, tts, sora, embeddings, moderation, deprecated gpt-3.5/gpt-4). The client must
curate a chat-model allowlist; the listing only proves the key works.
### 3.3 Chat + streaming wire format
OpenAI chat-completions: `choices[0].delta.content`, `finish_reason: "stop"`, usage chunk when
`stream_options: {"include_usage": true}` (accepted here; z.ai may reject `stream_options` — the
bench's param-fix ladder drops it first on 400). Reasoning surfaces only in usage
(`completion_tokens_details.reasoning_tokens`); there is **no reasoning content channel** on
chat-completions (no z.ai-style side-channel, no Anthropic thinking blocks) — reasoning is a
silent latency hole; TTFT fires on first content.
### 3.4 Reasoning/parameter surface + the function-tools clash (LIVE, decision-critical)
- `max_tokens` is **rejected** on current models: 400
`"Unsupported parameter: 'max_tokens' is not supported with this model. Use
'max_completion_tokens' instead."` (`code: "unsupported_parameter"`). Send
`max_completion_tokens` on OpenAI, `max_tokens` on z.ai/Anthropic.
- `reasoning_effort` on gpt-6-sol ∈ **`none | low | medium | high | xhigh`** (LIVE: invalid value →
400 lists exactly these).
- **Function tools × reasoning clash (LIVE):** sending `tools` with `reasoning_effort` ≠ `none`
(including the default when the param is omitted) → 400
`"Function tools with reasoning_effort are not supported for gpt-6-sol in /v1/chat/completions.
To use function tools, use /v1/responses or set reasoning_effort to 'none'."`
With `reasoning_effort: "none"` + tools the call succeeds and tool arguments stream in genuine
fragments (LIVE: 28 incremental fragments, `finish_reason: "tool_calls"`). So on
chat-completions, Museion's typed-tool passes get a **non-reasoning** gpt-6-sol; reasoning +
tools together requires the Responses API (`/v1/responses`, different wire format). This is an
ADR-0014 decision point, not an implementation detail.
- Tool wire format: identical OpenAI dialect as z.ai §1.4 (`tools[].type=function`,
`function.parameters`); `tool_choice: "auto" | "required" | {"type": "function", "name": …}`
(forced **is** allowed here); `"strict": true` per-tool exists for schema-constrained outputs —
default non-strict on chat-completions (strict is the default on Responses). Strict mode would
fit `submit_fix_cards` well: it constrains the arguments JSON to the schema.
### 3.5 Budget rules + error shapes
- Reasoning counts inside `max_completion_tokens` (bench: gpt-6-sol spent 505–725 reasoning tokens
under 2k–24k caps). Same rule as the others: generous cap, gate on finish reason + content.
- Error envelope: `{"error": {"message", "type": "invalid_request_error", "param", "code"}}`
(LIVE bad key: 401, `code: "invalid_api_key"`, message echoes a masked key — fine to show).
400s carry `param` + `code` (`unsupported_parameter`, `unsupported_value`) — map those in
Test Connection.
---
## 4. What a settings 'Test Connection' probe should do (cross-provider)
1. One `GET /models` per provider = key-validity + reachability only (z.ai: proves nothing about
key-type/endpoint pairing — §1.2).
2. One **minimal streaming chat call** per configured endpoint (`max_tokens`/`max_completion_tokens`
≈ 64, "hi"): proves key×endpoint×model actually generates. Decode: HTTP status, provider error
envelope (z.ai `error.code`, Anthropic `error.type` + `request_id`, OpenAI `error.code`),
z.ai 1113 → "wrong key type for this endpoint", `finish=length` + empty → "raise the token cap".
3. On z.ai, warn when a coding-plan key is configured for a shipped build (devpack scope rule §1.1).
4. Never gate on status 200 alone (§1.5 starvation is a 200).
## 5. Sources
- Official: `docs.z.ai/guides/llm/glm-5.3`, `docs.z.ai/devpack/latest-model`,
`docs.z.ai/devpack/tool/others`, `docs.z.ai/guides/capabilities/function-calling`,
`docs.anthropic.com/en/api/models`, `docs.anthropic.com/en/docs/agents-and-tools/tool-use`,
`docs.anthropic.com/en/docs/build-with-claude/extended-thinking`,
`docs.anthropic.com/en/api/errors`,
`platform.openai.com/docs/guides/function-calling` (all fetched 2026-10-23).
- Local: `prototypes/model-bench/bench.py`, `prototypes/model-bench/results/final/REPORT.md`
(bench of 2026-10-23), `llm-api-benchmarking` skill (secondary seed; its 1113 and
cannot-disable claims are corrected in §1.5/§1.6).
- Live probes 2026-10-23: /models ×4, cross-family chat calls, thinking-disable, effort enum,
budget starvation, stream cadence ×2 families, typed-tool streaming ×3 providers, bad-key
errors ×4 endpoints, Anthropic adaptive/effort/forced-tool probes, OpenAI tools×effort clash.
## 6. Correction 2026-10-28 (Museion #136 dogfood, live-probed)
- **Content-Type is load-bearing.** Without `Content-Type: application/json`,
URLSession defaults the request to `x-www-form-urlencoded` — z.ai answers
**HTTP 200** with `{"error":{"code":"500","message":"Content type
'application/x-www-form-urlencoded;charset=UTF-8' not supported"}}` (an error
envelope riding a 200), OpenAI can't parse the body ("you must provide a
model parameter"). The original curl probes worked because they passed the
header explicitly; the app (URLSession) did not. Anthropic tolerated the
omission.
- **OpenAI chat probes must speak the RESPONSES API** (`POST /v1/responses`,
`{"model","input"}`, `max_output_tokens`; flagship `gpt-6.1-sol`) —
chat-completions is the retired path for current models (maintainer
correction; §3.1/§3.3 above describe the older wire).
- **§4's "max_tokens ≈ 64" starves reasoning models.** Live tail on
glm-5.3 + `reasoning_effort:"low"` + `max_tokens:64`: all 64 tokens burned
as reasoning (`reasoning_tokens:64/64`), `finish_reason:"length"`, empty
content — the probe can never produce text at that cap. Museion's probe
uses 512.