diff --git a/docs/AGENTS.md b/docs/AGENTS.md index b2df5b5..e0d1840 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -30,3 +30,4 @@ Owned by the root AGENTS.md contract. | `adr/` | ADRs — covered by this doc's contracts | | `agents/` | Agent-skills config — issue-tracker, triage-label, domain conventions (written by `/setup-matt-pocock-skills`) | | `brainstorming-output/` | Transient brainstorming session records — working artifacts, not durable decisions; durable outcomes flow into PRD/ADRs | +| `research/` | Verified research artifacts (provider/API factsheets) feeding ADRs — source-cited and probe-dated, not decisions | diff --git a/docs/research/native-llm-providers.md b/docs/research/native-llm-providers.md new file mode 100644 index 0000000..c9d70c7 --- /dev/null +++ b/docs/research/native-llm-providers.md @@ -0,0 +1,304 @@ +# 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 `. 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 — the coding endpoint does not stream content live (LIVE + bench):** +thinking deltas stream, but *content* deltas arrive in one end-of-turn flush. Measured today: +coding endpoint — 60 reasoning deltas, then 33 content deltas inside a 0.16 s span with +`finish` + `usage` in the same instant; PAAS endpoint — 92 reasoning deltas over 0.58 s, then +34 content deltas with **0.00 s span**. The bench shows the same at scale (pass1: glm-5.3-max +TTFT 159.3 s of 170.7 s wall, 809 tok/s — a buffering signature; real generation is ~60–90 tok/s). +Consequence for Museion: on z.ai, TTFT ≈ thinking time + most of generation; render reasoning as +it streams, but do **not** promise token-by-token content; gate progress UI on reasoning deltas +and wall clock, not on content arrival. + +### 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: ` + `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 `. + +### 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.