diff --git a/changelog.d/glm-openrouter-reasoning-context.md b/changelog.d/glm-openrouter-reasoning-context.md
new file mode 100644
index 0000000000..a84455e024
--- /dev/null
+++ b/changelog.d/glm-openrouter-reasoning-context.md
@@ -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.
diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md
index 789ae97bb6..919d1868c9 100644
--- a/docs/architecture/inference.md
+++ b/docs/architecture/inference.md
@@ -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`
@@ -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
diff --git a/docs/developer/test.md b/docs/developer/test.md
index 4b8df503d5..6d2bd071e6 100644
--- a/docs/developer/test.md
+++ b/docs/developer/test.md
@@ -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.
@@ -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
@@ -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`.
diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md
index dc9de129b9..516262916f 100644
--- a/docs/reference/protocol-messages.md
+++ b/docs/reference/protocol-messages.md
@@ -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
@@ -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 `` to the template's open generation ``, 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
diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift
index b13bce01a7..1a37340f2e 100644
--- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift
+++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift
@@ -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`
@@ -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 = ["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] = [
+ "summary": ["auto", "concise", "detailed"],
+ "generate_summary": ["auto", "concise", "detailed"],
+ "mode": ["standard"],
+ ]
init() {}
init(from decoder: any Decoder) throws { self = Self.capture(from: decoder) }
@@ -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
@@ -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 {
@@ -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
@@ -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
@@ -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
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextOpenRouterCapabilityTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextOpenRouterCapabilityTests.swift
index f38fb7d899..ffa198e375 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextOpenRouterCapabilityTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextOpenRouterCapabilityTests.swift
@@ -338,6 +338,78 @@ struct GLM5NextOpenRouterCapabilityTests {
#expect(ProviderLoop.mapInferenceErrorToStatus(error) == 422)
}
+ // MARK: - reasoning-content-return
+
+ /// OpenRouter's current `reasoning-content-return` prompt. Its earlier
+ /// `get_time` call returns reasoning that holds the secret word, so the
+ /// answer can repeat it only when the returned reasoning renders.
+ static let secretWordPrompt = "Call the get_time tool. While thinking, choose a secret word. After the tool returns, reply with exactly \"SECRET: \" using the secret word from your thinking. If you cannot see your earlier thinking, reply \"SECRET: unknown\"."
+ static let secretWordThought = "I must call get_time first. My secret word is zephyr."
+
+ /// The secret-word turn with the reasoning returned in `carrier`
+ /// (`reasoning`, Darkbloom's streamed `reasoning_details` entry, or both).
+ /// `strict` declares `get_time` in OpenAI's strict form and returns the
+ /// call's arguments as `""`; otherwise as `{}`.
+ static func secretWordBody(carrier: String, strict: Bool, controls: String) throws -> [String: Any] {
+ let detail: [String: Any] = [
+ "type": "reasoning.text", "text": secretWordThought, "id": "reasoning-text-0", "format": "unknown",
+ "index": 0, "signature": NSNull(),
+ ]
+ var assistant: [String: Any] = [
+ "role": "assistant", "content": NSNull(),
+ "tool_calls": [["id": "call_get_time", "type": "function", "index": 0,
+ "function": ["name": "get_time", "arguments": strict ? "" : "{}"]]],
+ ]
+ if carrier != "reasoning_details" { assistant["reasoning"] = secretWordThought }
+ if carrier != "reasoning" { assistant["reasoning_details"] = [detail] }
+ var function: [String: Any] = ["name": "get_time", "description": "Get the current time",
+ "parameters": ["type": "object", "properties": [String: Any]()]]
+ if strict {
+ function["parameters"] = ["type": "object", "properties": [String: Any](), "required": [String](),
+ "additionalProperties": false]
+ function["strict"] = true
+ }
+ var body: [String: Any] = [
+ "model": model, "stream": true, "stream_options": ["include_usage": true],
+ "messages": [
+ ["role": "user", "content": secretWordPrompt], assistant,
+ ["role": "tool", "tool_call_id": "call_get_time", "content": "2026-10-24T05:12:00Z"],
+ ],
+ "tools": [["type": "function", "function": function]],
+ ]
+ let merged = try #require(JSONSerialization.jsonObject(with: Data(controls.utf8)) as? [String: Any])
+ body.merge(merged) { _, added in added }
+ return body
+ }
+
+ /// The secret-word form of `reasoning-content-return` with each reasoning
+ /// carrier, the OpenAI strict declaration and empty-string arguments, and
+ /// OpenRouter's reasoning controls, `reasoning.context` and
+ /// `reasoning.mode` included (both refused with 400 before). The returned
+ /// reasoning renders in the call's thinking block and the answer is served.
+ @Test(arguments: [
+ ("reasoning", false, "{}"),
+ ("reasoning_details", true, #"{"reasoning":{"enabled":true}}"#),
+ ("both", true, #"{"reasoning":{"effort":"high"},"tool_choice":"auto","parallel_tool_calls":true}"#),
+ ("reasoning_details", false, #"{"reasoning":{"max_tokens":2048,"exclude":false},"include_reasoning":true}"#),
+ ("both", true, #"{"reasoning":{"enabled":true,"context":"all_turns"}}"#),
+ ("reasoning", true, #"{"reasoning":{"effort":"medium","context":"current_turn","mode":"standard"}}"#),
+ ])
+ func openRouterSecretWordReasoningReturnIsServed(carrier: String, strict: Bool, controls: String) async throws {
+ let prompts = PromptCapture()
+ let served = try await serve(
+ Self.secretWordBody(carrier: carrier, strict: strict, controls: controls),
+ output: ["The tool returned the time; my word was zephyr.", "", "SECRET: zephyr"],
+ prompts: prompts)
+ #expect(served.error == nil)
+ #expect(served.reasoning == "The tool returned the time; my word was zephyr.")
+ #expect(served.content == "SECRET: zephyr" && served.finishReason == "stop")
+ let prompt = try #require(prompts.prompts.first)
+ #expect(prompt.contains(
+ "<|assistant|>\(Self.secretWordThought)get_time<|observation|>"))
+ #expect(prompt.hasSuffix("2026-10-24T05:12:00Z<|assistant|>"))
+ }
+
// MARK: - Forced tool_choice
/// OpenRouter's captured `orIncidentAuto` request, byte for byte as the
diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextPromptPolicyTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextPromptPolicyTests.swift
index 04fb3939f4..66c0565097 100644
--- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextPromptPolicyTests.swift
+++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/GLM5NextPromptPolicyTests.swift
@@ -144,6 +144,8 @@ struct GLM5NextPromptPolicyTests {
["thinking": true],
["include_reasoning": NSNull(), "thinking": NSNull()],
["reasoning": ["enabled": true, "max_tokens": NSNull(), "exclude": NSNull(), "summary": "auto"]],
+ ["reasoning": ["context": "auto", "mode": "standard"]],
+ ["reasoning": ["enabled": true, "context": NSNull(), "mode": NSNull()]],
["reasoning": ["enabled": true, "exclude": false], "include_reasoning": true,
"enable_thinking": true, "chat_template_kwargs": ["thinking": true, "enable_thinking": true]],
] }
@@ -182,6 +184,73 @@ struct GLM5NextPromptPolicyTests {
}
}
+ /// OpenRouter's `reasoning.context` spells the template's `clear_thinking`:
+ /// `current_turn` keeps only the reasoning returned after the last user
+ /// turn, `all_turns` every turn's. With each golden's `clear_thinking`
+ /// spellings replaced by the equivalent context, every golden, the
+ /// cleared and current-turn ones included, renders byte for byte.
+ @Test func reasoningContextRendersEveryGoldenLikeItsClearThinkingSpelling() throws {
+ let template = try shippedTemplate()
+ for fixture in try goldens().cases {
+ guard case .object(let expected) = fixture.expectedContext else {
+ Issue.record("\(fixture.id) has no expected context object")
+ continue
+ }
+ var body = try #require(
+ JSONSerialization.jsonObject(with: JSONEncoder().encode(fixture.request)) as? [String: Any])
+ body.removeValue(forKey: "clear_thinking")
+ if var kwargs = body["chat_template_kwargs"] as? [String: Any] {
+ kwargs.removeValue(forKey: "clear_thinking")
+ body["chat_template_kwargs"] = kwargs
+ }
+ var reasoning = body["reasoning"] as? [String: Any] ?? [:]
+ reasoning["context"] = expected["clear_thinking"] == .bool(true) ? "current_turn" : "all_turns"
+ body["reasoning"] = reasoning
+ for input in try remoteAndLocalInputs(JSONSerialization.data(withJSONObject: body)) {
+ let context = MLXLMCommon.JSONValue.object(
+ (input.additionalContext ?? [:]).mapValues { .from($0) })
+ #expect(context == fixture.expectedContext, "\(fixture.id)")
+ #expect(try render(input, with: template) == fixture.rendered, "\(fixture.id)")
+ }
+ }
+ }
+
+ /// A `reasoning.context` that disagrees with the effective `clear_thinking`
+ /// is refused on both paths, never reconciled; one that agrees, or `auto`,
+ /// leaves the explicit value in place.
+ @Test func reasoningContextContradictingClearThinkingIsRefused() throws {
+ let contradictions: [[String: Any]] = [
+ ["reasoning": ["context": "current_turn"], "clear_thinking": false],
+ ["reasoning": ["context": "all_turns"], "chat_template_kwargs": ["clear_thinking": true]],
+ ["reasoning": ["context": "all_turns"], "thinking": ["type": "enabled", "clear_thinking": true]],
+ ]
+ for controls in contradictions {
+ let body = try body(controls)
+ let evidence = try JSONDecoder().decode(GLM5NextPromptPolicy.RawControls.self, from: body)
+ #expect(!evidence.invalid, "\(controls)")
+ #expect(throws: (any Error).self) { try evidence.validate() }
+ #expect(throws: (any Error).self) { try ProviderLoop.decodeOpenAIRequest(body, modelType: "glm5_next") }
+ let local = try JSONDecoder().decode(LocalChatRequest.self, from: body)
+ #expect(throws: (any Error).self) {
+ try ProviderPromptContractPipeline.normalizedInput(
+ prepared: ToolChoicePromptPolicy.prepare(local.request, modelType: "glm5_next"),
+ request: local.request, modelType: "glm5_next", templateControls: local.templateControls)
+ }
+ }
+ let consistent: [([String: Any], Bool)] = [
+ (["reasoning": ["context": "current_turn"]], true),
+ (["reasoning": ["context": "current_turn"], "clear_thinking": true], true),
+ (["reasoning": ["context": "all_turns"], "chat_template_kwargs": ["clear_thinking": false]], false),
+ (["reasoning": ["context": "auto"], "clear_thinking": true], true),
+ (["reasoning": ["context": "current_turn", "enabled": false]], true),
+ ]
+ for (controls, clears) in consistent {
+ for input in try remoteAndLocalInputs(body(controls)) {
+ #expect(input.additionalContext?["clear_thinking"] as? Bool == clears, "\(controls)")
+ }
+ }
+ }
+
@Test func reasoningBudgetSelectsTheNearestEffortAndAnyExplicitEffortWins() throws {
func effort(_ controls: [String: Any]) throws -> String? {
var body: [String: Any] = ["model": "m", "messages": [["role": "user", "content": "Hi"]]]
@@ -494,7 +563,9 @@ struct GLM5NextPromptPolicyTests {
["reasoning": ["max_tokens": 0]], ["reasoning": ["max_tokens": -1]],
["reasoning": ["max_tokens": 1.5]], ["reasoning": ["max_tokens": "1024"]],
["reasoning": ["summary": "verbose"]], ["reasoning": ["summary": true]],
- ["reasoning": ["generate_summary": "Auto"]], ["reasoning": ["context": "all_turns"]],
+ ["reasoning": ["generate_summary": "Auto"]], ["reasoning": ["context": "every_turn"]],
+ ["reasoning": ["context": "All_Turns"]], ["reasoning": ["context": true]],
+ ["reasoning": ["mode": "pro"]], ["reasoning": ["mode": true]],
["reasoning": ["effort": "high"], "reasoning_effort": "low "],
["reasoning": ["enabled": false, "unrecognized": true]],
["clear_thinking": false, "chat_template_kwargs": ["clear_thinking": "true"]],
@@ -759,7 +830,8 @@ struct GLM5NextPromptPolicyTests {
/// tool turn with OpenRouter's reasoning fields, GLM's own API spelling of
/// the thinking switch, or OpenRouter's `strict` weather tool. MiMo and
/// Nemotron Super serve each. GLM served only the first and refused the
- /// others with `invalid_request` before rendering.
+ /// others with `invalid_request` before rendering, and refused OpenRouter's
+ /// `reasoning.context` and `reasoning.mode` until they were recognized.
@Test(arguments: [
("{}", false),
(#"{"reasoning":null}"#, false),
@@ -772,8 +844,10 @@ struct GLM5NextPromptPolicyTests {
(#"{"thinking":{"type":"enabled"}}"#, false),
(#"{"thinking":true}"#, false),
(#"{"thinking":null}"#, false),
+ (#"{"reasoning":{"effort":"high","context":"auto","mode":"standard"}}"#, false),
("{}", true),
(#"{"reasoning":{"enabled":true}}"#, true),
+ (#"{"reasoning":{"enabled":true,"context":"all_turns"}}"#, true),
])
func openRouterReasoningContentReturnRequestIsServed(controls: String, strict: Bool) throws {
let template = try shippedTemplate()
@@ -790,6 +864,31 @@ struct GLM5NextPromptPolicyTests {
}
}
+ /// `reasoning.context: current_turn` keeps the reasoning returned on the
+ /// current turn's call and drops it once a later user turn follows,
+ /// exactly as `clear_thinking: true` does; `all_turns` keeps it.
+ @Test func currentTurnReasoningContextRendersLikeClearThinking() throws {
+ let template = try shippedTemplate()
+ let thought = Self.returnedThought
+ func rendered(_ controls: String, laterUserTurn: Bool) throws -> [String] {
+ var body = try #require(JSONSerialization.jsonObject(with: returnedReasoningConversation(
+ assistant: ["reasoning": thought], controls: controls)) as? [String: Any])
+ if laterUserTurn {
+ body["messages"] = (body["messages"] as? [Any] ?? []) + [["role": "user", "content": "Thanks"]]
+ }
+ return try remoteAndLocalInputs(JSONSerialization.data(withJSONObject: body)).map {
+ try render($0, with: template)
+ }
+ }
+ for laterUserTurn in [false, true] {
+ let current = try rendered(#"{"reasoning":{"context":"current_turn"}}"#, laterUserTurn: laterUserTurn)
+ #expect(try current == rendered(#"{"clear_thinking":true}"#, laterUserTurn: laterUserTurn))
+ #expect(current[0].contains("\(thought)") == !laterUserTurn)
+ let all = try rendered(#"{"reasoning":{"context":"all_turns"}}"#, laterUserTurn: laterUserTurn)
+ #expect(all[0].contains("\(thought)"))
+ }
+ }
+
/// A returned call without arguments (`""`) renders like `{}`, as MiMo,
/// Nemotron Super and vLLM read it.
@Test func emptyHistoryArgumentsRenderAsAnEmptyObject() throws {