Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions changelog.d/glm-openrouter-reasoning-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### GLM-5.3-Flash accepts OpenRouter's reasoning context and mode

GLM-5.3-Flash refused requests carrying OpenRouter's documented
`reasoning.context` or `reasoning.mode` with 400 `invalid_request`.
`reasoning.context` now chooses which returned reasoning the model sees:
`current_turn` keeps only the reasoning returned after the last user turn, as
`clear_thinking: true` does, while `all_turns` and `auto` keep every turn's.
`reasoning.mode: "standard"`, OpenRouter's default, is accepted. Other values,
`reasoning.mode: "pro"` and a context that contradicts `clear_thinking` are
still refused with 400.
10 changes: 6 additions & 4 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider inference engine

> Last updated: 2026-10-23
> Last updated: 2026-10-24

How a chat-completion request is served inside the `darkbloom` provider
process: one in-process engine (`mlx-swift-lm`
Expand Down Expand Up @@ -888,9 +888,11 @@ The request-local [GLM prompt contract](../reference/protocol-messages.md#glm-na
also preserves original schema values only after a trusted loaded-model check.
It renders reasoning that OpenRouter returns on earlier assistant turns
(`reasoning` or `reasoning_details` text) as the template's `reasoning_content`
(`GLM5NextPromptPolicy.RawControls.returnedReasoning`), and serves `strict`
tools by validating each `auto` call against its schema before exposure
(`ToolConstraintValidation.validate`), not by constraining decoding.
(`GLM5NextPromptPolicy.RawControls.returnedReasoning`); OpenRouter's
`reasoning.context` chooses which of it renders, `current_turn` meaning the
template's `clear_thinking` (`RawControls.contextClearThinking`). It serves
`strict` tools by validating each `auto` call against its schema before
exposure (`ToolConstraintValidation.validate`), not by constraining decoding.
GLM's native engine refuses sampler token constraints, so a JSON
`response_format` is likewise prompt-steered and validated, not constrained:
the service's instruction message renders through the template, reasoning
Expand Down
13 changes: 11 additions & 2 deletions docs/developer/test.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Test Provider And Native Contracts

> Last updated: 2026-10-23
> Last updated: 2026-10-24

Run isolated Swift, native-resource, public-fixture, retained-console and landing tests here.
Backend integration and cross-implementation qualification are platform-owned.
Expand Down Expand Up @@ -198,6 +198,11 @@ only the shipped template is recognized and passes the load-time render check.
`openRouterReasoningContentReturnRequestIsServed` push OpenRouter's
returned-reasoning tool turn through the coordinator and local HTTP paths to the
rendered prompt, with each of its reasoning spellings and controls.
`reasoningContextRendersEveryGoldenLikeItsClearThinkingSpelling` replaces each
golden's `clear_thinking` with OpenRouter's equivalent `reasoning.context` and
must still match it byte for byte; `currentTurnReasoningContextRendersLikeClearThinking`
and `reasoningContextContradictingClearThinkingIsRefused` cover the current
turn and the refused contradictions.
`capturedOpenRouterToolRequestIsServed` and
`capturedOpenRouterToolServesAFiveStepConversation` replay OpenRouter's captured
`strict` weather-tool requests, held byte for byte and hash-checked, with tool
Expand All @@ -219,7 +224,11 @@ protocol v1. Each served JSON or forced submission must carry no token
constraint and no logprobs, so `EngineV2Bridge.nativeOutputControlRefusal`
evaluated as GLM's native-tracked engine admits it. In the control, GLM admits
a logprobs row that the same check refuses for a native engine without logprobs
capture. The scripted completions prove the
capture. `openRouterSecretWordReasoningReturnIsServed` serves OpenRouter's
secret-word `reasoning-content-return` turn (a `get_time` call whose returned
reasoning holds the word) with each reasoning carrier, the strict declaration,
empty-string arguments and `reasoning.context`/`reasoning.mode`; the reasoning
must render in the call's thinking block. The scripted completions prove the
provider's withholding and validation, not the model's compliance; that needs
the real-model run in `GLM5NextRealArtifactQualificationTests`.

Expand Down
10 changes: 7 additions & 3 deletions docs/reference/protocol-messages.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider ↔ coordinator protocol messages

> Last updated: 2026-10-23
> Last updated: 2026-10-24

Every JSON frame on the provider WebSocket (`GET /ws/provider`), with the Go
type, the Swift type, and the presence rule for each field. Go is the canon in
Expand Down Expand Up @@ -1165,16 +1165,20 @@ model names cannot authorize the raw-schema path.

| Request-body control | Native text contract | Provider source |
|---|---|---|
| `reasoning.effort`, `reasoning_effort`, `chat_template_kwargs.reasoning_effort` | Exact `minimal`/`low` render `low`, `medium`/`high` render `high`, `xhigh`/`max` render `max`, matching the platform sidecar; nested, top-level, then template precedence; default `max`. `none` and `off` are thinking-off requests (below); other invalid values reject even when shadowed. `reasoning: null` and null `reasoning` members are unset; `reasoning.summary` and `reasoning.generate_summary` accept `auto`, `concise` or `detailed` as no-ops, because the full reasoning is returned. Other `reasoning` members are refused. | `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`RawControls`, `additionalContext`, `Effort`) |
| `reasoning.effort`, `reasoning_effort`, `chat_template_kwargs.reasoning_effort` | Exact `minimal`/`low` render `low`, `medium`/`high` render `high`, `xhigh`/`max` render `max`, matching the platform sidecar; nested, top-level, then template precedence; default `max`. `none` and `off` are thinking-off requests (below); other invalid values reject even when shadowed. `reasoning: null` and null `reasoning` members are unset; `reasoning.summary` and `reasoning.generate_summary` accept `auto`, `concise` or `detailed` as no-ops, because the full reasoning is returned, and `reasoning.mode` accepts OpenRouter's default `standard` (`pro` names a model variant GLM does not have). Other `reasoning` members and values are refused. | `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`RawControls`, `additionalContext`, `Effort`) |
| `reasoning.max_tokens` | Positive integer. Selects the nearest effort when no effort alias is present: at most 1,024 renders `low`, at most 8,192 `high`, otherwise `max` (the budgets OpenAI-compatible APIs give `low` and `medium`). The template does not enforce a token budget. | Same source (`Effort.init(reasoningBudget:)`) |
| `reasoning.enabled`, `enable_thinking`, `chat_template_kwargs.enable_thinking`, `chat_template_kwargs.thinking`, top-level `thinking` | Boolean only, except top-level `thinking`, which also takes GLM's API object `{"type": "enabled"\|"disabled", "clear_thinking": Boolean}` (both members optional; other members refused); null top-level `thinking` is unset. `true` is a no-op that leaves the rendered prompt unchanged. `false`, like effort `none`/`off`, turns thinking off: the render context adds `enable_thinking: false` (`thinkingOffContextKey`) and the GLM tokenizer appends `</think>` to the template's open generation `<think>`, the empty block the template writes for an assistant turn without reasoning, so the answer is content only. The platform sidecar appends the same text. Thinking-off beside a `true` switch, an effort level or a `reasoning.max_tokens` budget is refused with 400 `invalid_request`. | Same source (`RawControls`, `validate`, `additionalContext`); `provider-swift/Sources/ProviderCore/Inference/Models/GLM5Next/GLM5NextThinkingTokenizer.swift` (`GLM5NextThinkingTokenizer`) |
| `include_reasoning`, `reasoning.exclude` | Boolean or null (unset). `include_reasoning: true` and `reasoning.exclude: false` are no-ops. The opposite value refuses with 400 `MultiModelBatchSchedulerEngineError.reasoningExclusionUnsupported`: the provider has no per-request seam to withhold reasoning it generates. Local HTTP returns the fixed `GLM5NextPromptPolicy.reasoningExclusionUnsupportedMessage` with code `unsupported_value`; the coordinator frame keeps the closed `invalid_request` / `client_error` vocabulary. | Same source (`RawControls`, `validate`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) |
| `clear_thinking`, `chat_template_kwargs.clear_thinking`, `thinking.clear_thinking` | Boolean only; top-level, then template value, then the `thinking` object; default `false`. This clears historical reasoning, not newly generated reasoning. | Same source and symbols |
| `clear_thinking`, `chat_template_kwargs.clear_thinking`, `thinking.clear_thinking`, `reasoning.context` | Boolean only; top-level, then template value, then the `thinking` object; default `false`. `true` clears historical reasoning, not newly generated reasoning: the template then keeps only the reasoning of assistant turns after the last user turn. OpenRouter's `reasoning.context` spells the same switch: `current_turn` is `true`, `all_turns` is `false`, and `auto` or null is unset. Other context values, and a context that contradicts the effective Boolean, are refused with 400 `invalid_request`, never reconciled. | Same source (`RawControls.contextClearThinking`, `validate`, `additionalContext`) |
| Tools and history | Preserve original schema values, nulls and correlated call IDs; reject reserved schema metadata and ambiguous native delimiters. An assistant turn without `reasoning_content` renders the reasoning it returns as OpenRouter's `reasoning` string, else its `reasoning_details` `reasoning.text` entries in order, as `reasoning_content`, in JSON-mode requests too (the service's inserted instruction turn is skipped when aligning); summary and encrypted entries are skipped. A history call with empty-string `arguments` renders as `{}`. `strict` tools are served without constrained decoding: every `auto` call is validated against its declared schema before exposure, so a non-conforming call fails the request. | Same source (`normalizedTextInput`, `validateHistory`, `RawControls.returnedReasoning`); `provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintValidation.swift` (`validate`); `provider-swift/Sources/ProviderCore/ProviderLoop+InboundDecode.swift` (`decodeOpenAIRequest`) |
| `response_format` `json_object` / `json_schema` | Text requests without tools. GLM's native engine refuses sampler constraints, so this is not constrained decoding: the service's instruction message renders as a system turn, reasoning streams as generated, and the answer is withheld until generation ends. The exposed content is the decoded JSON value (markdown fences and surrounding prose removed); `json_object` needs a root object, `json_schema` must compile to the shared fail-closed subset with explicit types and the value must satisfy it. Otherwise the request fails with 422 (`MLXOpenAIServiceError.invalidResponseFormatOutput`, error reason `tool_noncompliance`, retryable on another sample) and no content; a JSON format with tools, an unsupported schema, or image/video input is refused with 400. Withheld output ends the pre-content deadline interval when generated. | `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift` (`GLM5NextResponseFormat`, `GLM5NextResponseFormatOutput`); `provider-swift/Sources/ProviderCore/Inference/Tools/ToolConstraintSchema.swift` (`compileResponseSchema`); `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2RequestUsageSignal.swift` (`recordWithheldOutput`) |
| `tool_choice` `required` / named function | Text requests. Served by structured post-validation, as Qwen 3.5/3.8 and Nemotron are: `ToolChoicePromptPolicy` renders its forcing instruction in the system and last user turns, a named choice offers only that function, reasoning streams on a separate typed channel, and the native GLM parser withholds the call until end of stream. It is exposed only after it parses and passes `ToolConstraintValidation.validate` (declared or named function, compiled schema, cardinality); visible text, a missing, malformed, truncated or schema-invalid call is a 422 `tool_noncompliance` with nothing exposed. Advertised under tool-constraint protocol v1 for the managed GLM identities, so the coordinator routes these requests to such providers. Image or video input with a forced choice is refused with 400. | `provider-swift/Sources/ProviderCore/Inference/Tools/ToolChoiceEnforcementPolicy.swift` (`forcedStrategy`, `validateParser`, `advertisesCapability`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`normalizedTextInput`); `provider-swift/Sources/ProviderCore/Inference/Streaming/NativeToolStreamRouter.swift` (`checkNativeToolFailure`) |
| Unqualified modes | Reject `preserve_thinking`, other `reasoning` or `chat_template_kwargs` keys and media. GLM image and video input use the native causal media path when the slot's engine accepts prepared causal media; otherwise local HTTP refuses with 400 before media decode or vision-tower work. A parser or prompt template is not constrained-decoding or media qualification. | Same policy (`normalizedTextInput`); `provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift`; `provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift` |

The platform prompt sidecar's GLM mirror still refuses `reasoning.context` and
`reasoning.mode`, so such requests get no coordinator cache plan; the provider
serves them.

`LocalResponseRequest` retains request-local raw controls for the same later
loaded-model check; capture alone grants no capability
(`provider-swift/Sources/ProviderCore/Server/LocalResponseRequest.swift`). The
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ enum GLM5NextPromptPolicy {
var excludesReasoning = false
var effort: Effort?
var clearThinking: Bool?
/// `clear_thinking` as OpenRouter's `reasoning.context` spells it:
/// `current_turn` keeps only the reasoning returned after the last
/// user turn (true), `all_turns` every turn's (false); `auto`, the
/// default, is nil.
var contextClearThinking: Bool?
var hasOriginalTools = false
var originalTools: [OpenAITool]?
/// Reasoning returned on assistant turns as OpenRouter's `reasoning`
Expand All @@ -95,8 +100,14 @@ enum GLM5NextPromptPolicy {
init?(intValue: Int) { return nil }
}

/// Responses summary levels. The full reasoning is returned for each.
private static let summaryLevels: Set<String> = ["auto", "concise", "detailed"]
/// `reasoning` members that change nothing: Responses summary levels,
/// because the full reasoning is returned for each, and OpenRouter's
/// standard reasoning mode (`pro` selects a variant GLM does not have).
private static let noOpReasoningMembers: [String: Set<String>] = [
"summary": ["auto", "concise", "detailed"],
"generate_summary": ["auto", "concise", "detailed"],
"mode": ["standard"],
]

init() {}
init(from decoder: any Decoder) throws { self = Self.capture(from: decoder) }
Expand Down Expand Up @@ -197,11 +208,10 @@ enum GLM5NextPromptPolicy {
if try present(root, "reasoning", nullable: true) {
let reasoning = try root.nestedContainer(keyedBy: Key.self, forKey: Key("reasoning"))
for key in reasoning.allKeys
where !["effort", "enabled", "exclude", "max_tokens"].contains(key.stringValue) {
// An unset member or a summary level changes nothing.
where !["effort", "enabled", "exclude", "max_tokens", "context"].contains(key.stringValue) {
guard try !reasoning.decodeNil(forKey: key) else { continue }
guard ["summary", "generate_summary"].contains(key.stringValue),
try summaryLevels.contains(reasoning.decode(String.self, forKey: key))
guard let accepted = noOpReasoningMembers[key.stringValue],
try accepted.contains(reasoning.decode(String.self, forKey: key))
else {
result.invalid = true
break
Expand All @@ -210,6 +220,14 @@ enum GLM5NextPromptPolicy {
nestedEffort = try effort(reasoning, "effort", nullable: true)
try thinkingSwitch(reasoning, "enabled", nullable: true)
try exclusionSwitch(reasoning, "exclude", excludingValue: true, nullable: true)
if try present(reasoning, "context", nullable: true) {
switch try reasoning.decode(String.self, forKey: Key("context")) {
case "auto": break
case "all_turns": result.contextClearThinking = false
case "current_turn": result.contextClearThinking = true
default: throw GLM5NextPromptPolicy.invalid("unsupported reasoning context")
}
}
if try present(reasoning, "max_tokens", nullable: true) {
let budget = try reasoning.decode(Int.self, forKey: Key("max_tokens"))
guard budget > 0 else {
Expand Down Expand Up @@ -244,7 +262,7 @@ enum GLM5NextPromptPolicy {
func validate() throws {
guard !invalid else {
throw GLM5NextPromptPolicy.invalid(
"controls require reasoning_effort none/off/minimal/low/medium/high/xhigh/max, a positive integer reasoning.max_tokens, and Boolean clear_thinking and reasoning switches")
"controls require reasoning_effort none/off/minimal/low/medium/high/xhigh/max, a positive integer reasoning.max_tokens, reasoning.context auto/all_turns/current_turn, reasoning.mode standard, and Boolean clear_thinking and reasoning switches")
}
guard !excludesReasoning else {
throw MultiModelBatchSchedulerEngineError.reasoningExclusionUnsupported
Expand All @@ -253,6 +271,17 @@ enum GLM5NextPromptPolicy {
guard !(disablesThinking && requestsThinking) else {
throw GLM5NextPromptPolicy.invalid(GLM5NextPromptPolicy.contradictoryThinking)
}
_ = try resolvedClearThinking(explicit: clearThinking)
}

/// The template's `clear_thinking`: the explicit Boolean, else the one
/// `reasoning.context` spells, else `false`. A context that contradicts
/// the explicit Boolean is refused.
func resolvedClearThinking(explicit: Bool?) throws -> Bool {
if let explicit, let contextClearThinking, explicit != contextClearThinking {
throw GLM5NextPromptPolicy.invalid("reasoning.context cannot contradict clear_thinking")
}
return explicit ?? contextClearThinking ?? false
}

/// The returned text of one message: its `reasoning` string, else its
Expand Down Expand Up @@ -312,9 +341,10 @@ enum GLM5NextPromptPolicy {
guard !(thinkingOff && thinkingOn) else {
throw invalid(contradictoryThinking)
}
let clearThinking = try raw.resolvedClearThinking(explicit: controls.clearThinking ?? raw.clearThinking)
var context: [String: any Sendable] = [
"reasoning_effort": (nested ?? top ?? raw.effort ?? .max).rawValue,
"clear_thinking": controls.clearThinking ?? raw.clearThinking ?? false,
"clear_thinking": clearThinking,
]
if thinkingOff { context[thinkingOffContextKey] = false }
return context
Expand Down
Loading
Loading