lm15 1.0.0-rc.7

One request and response model for every LLM provider (OpenAI, Anthropic, Gemini, xAI, Groq, Bedrock, Azure, Vertex, local servers), with visible adaptations. Implements the lm15 contract.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! The `POST /messages` body (`lm15/providers/anthropic.py:508-749` is the
//! reference; keys are inserted in its order because a SigV4 door signs
//! the serialized bytes — README-anthropic.md states the dependency).
//!
//! Order: `model`, `messages`, `stream`, `max_tokens`, `system`,
//! `temperature`, `top_p`, `top_k`, `stop_sequences`, `tools`,
//! `tool_choice`, `thinking`, `output_config`, `service_tier`, `metadata`,
//! then `extensions` verbatim (an existing key is replaced in place), then
//! the policy's `system_prefix` placed first in `system`.

use serde_json::{json, Map, Value};

use crate::compat::{
    AnthropicCacheControl, AnthropicThinkingFormat, ResolvedAnthropicCompat, SendReject,
};
use crate::errors::Lm15Error;
use crate::types::{
    CacheConfig, CacheMode, CachePrefix, CacheRetention, Part, Reasoning, ReasoningEffort,
    ReasoningSummary, Request, SystemContent, Tool, ToolChoiceMode,
};
use crate::wire::BuildContext;

use super::parts::{self, text_block, PartContext};
use super::tables::{
    anthropic_adaptive_class, builtin_tool_type, claude_output_ceiling, effort_thinking_budget,
    DEFAULT_VISIBLE_TOKENS,
};
use super::Refuse;

/// `lm15/providers/anthropic.py:735`: the lm15-owned `extensions` keys
/// every reference adapter reserves before forwarding (`prompt_caching`
/// is the pre-`CacheConfig` spelling, kept as a reserved no-op so a
/// request written for the reference does not 400 here).
pub const RESERVED_EXTENSION_KEYS: &[&str] = &["prompt_caching"];

/// The body for `request`.
pub fn payload(
    request: &Request,
    stream: bool,
    cx: &BuildContext<'_>,
    compat: &ResolvedAnthropicCompat,
) -> Result<Map<String, Value>, Lm15Error> {
    let refuse = Refuse {
        provider: cx.provider,
    };
    crate::dialects::content::validate_slots(
        request,
        cx.provider,
        "anthropic",
        compat.tool_result_media,
    )?;
    crate::judgments::note_unmeasurable_probabilities(request, cx.provider)?;
    let prepared = prepare(request, cx.model, compat, cx.provider)?;
    let request = &prepared;
    let model = cx.model;
    let config = &request.config;

    // `model_prefixes` (`lm15/providers/anthropic.py:510-519`): a model id
    // the server would serve as another model is refused before the wire.
    if let Some(prefixes) = compat.model_prefixes {
        if !prefixes.iter().any(|prefix| model.starts_with(prefix)) {
            return Err(refuse.model(format!(
                "model {model:?} is not one this endpoint serves as typed (expected a prefix in \
                 {prefixes:?}); it would be silently substituted by another model. Name the model \
                 you actually want"
            )));
        }
    }

    let cache = cache_plan(config.cache.as_ref(), compat, &refuse)?;
    let thinking = thinking_plan(config.reasoning.as_ref(), model, compat, &refuse)?;

    let part_cx = PartContext {
        refuse: &refuse,
        thinking_replay: compat.thinking_replay,
        tool_result_media: compat.tool_result_media,
    };
    let mut messages: Vec<Value> = request
        .messages
        .iter()
        .map(|m| parts::message(m, &part_cx))
        .collect::<Result<_, _>>()?;
    if let Some(index) = cache.message_mark(messages.len()) {
        mark_last_block(&mut messages[index], cache.marker());
    }

    let mut body = Map::new();
    body.insert("model".into(), Value::String(model.to_string()));
    body.insert("messages".into(), Value::Array(messages));
    body.insert("stream".into(), Value::Bool(stream));
    body.insert(
        "max_tokens".into(),
        Value::from(thinking.max_tokens(config.max_tokens)?),
    );

    if let Some(system) = &request.system {
        body.insert("system".into(), system_value(system, &cache, &part_cx)?);
    }

    if compat.sampling_params == SendReject::Reject {
        for (name, set) in [
            ("temperature", config.temperature.is_some()),
            ("top_p", config.top_p.is_some()),
            ("top_k", config.top_k.is_some()),
        ] {
            if set {
                // The server documents none of these and swallows them
                // (Moonshot, live 2026-09-03: `temperature: 0.5` is 200 here).
                return Err(refuse.feature(format!(
                    "config.{name} is silently ignored by this server (the model's sampling is \
                     fixed); omit it"
                )));
            }
        }
    }
    if let Some(temperature) = config.temperature {
        body.insert("temperature".into(), Value::from(temperature));
    }
    if let Some(top_p) = config.top_p {
        body.insert("top_p".into(), Value::from(top_p));
    }
    if let Some(top_k) = config.top_k {
        body.insert("top_k".into(), Value::from(top_k));
    }
    if !config.stop.is_empty() {
        body.insert("stop_sequences".into(), json!(config.stop));
    }
    if !request.tools.is_empty() {
        body.insert(
            "tools".into(),
            Value::Array(request.tools.iter().map(tool_value).collect()),
        );
    }
    if let Some(tool_choice) = tool_choice_value(request, compat, &refuse)? {
        body.insert("tool_choice".into(), tool_choice);
    }

    let mut output_config = Map::new();
    if let Some(thinking_value) = thinking.wire(config.reasoning.as_ref()) {
        body.insert("thinking".into(), thinking_value);
    }
    if let Some(effort) = thinking.effort(config.reasoning.as_ref()) {
        output_config.insert("effort".into(), Value::String(effort.as_str().into()));
    }
    if let Some(format) = &config.response_format {
        if compat.structured_output == SendReject::Reject {
            // The server accepts output_config.format and ignores the
            // schema (DeepSeek, live 2026-09-03) — refuse before the wire.
            return Err(refuse.feature(
                "response_format is silently ignored by this server (output_config.format is \
                 accepted and not applied); describe the shape in the prompt",
            ));
        }
        output_config.insert("format".into(), output_format(format, &refuse)?);
    }
    if !output_config.is_empty() {
        body.insert("output_config".into(), Value::Object(output_config));
    }

    if let Some(tier) = &config.service_tier {
        body.insert("service_tier".into(), Value::String(tier.clone()));
    }
    if let Some(user_id) = &config.user_id {
        body.insert("metadata".into(), json!({"user_id": user_id}));
    }
    if config.store.is_some() {
        return Err(refuse.feature(
            "config.store is not supported — the Messages API has no response-storage opt-out \
             field (OpenAI and Gemini carry it)",
        ));
    }
    if config.logprobs.is_some() {
        return Err(refuse.feature(
            "config.logprobs is not supported — the Messages API does not expose token log \
             probabilities (OpenAI and Gemini carry them)",
        ));
    }

    // INV-049: `extensions` is provider syntax, verbatim; an existing key
    // is replaced in place (the MAP-7 rule 10 `thinking` override). The
    // reserved lm15 keys never reach the wire (`lm15/providers/anthropic.py:735`;
    // docs/cookbooks/18-provider-passthrough.md § Reserved keys).
    if let Some(extensions) = &config.extensions {
        for (key, value) in extensions {
            if RESERVED_EXTENSION_KEYS.contains(&key.as_str()) {
                continue;
            }
            body.insert(key.clone(), value.clone());
        }
    }

    if let Some(prefix) = cx.policy.system_prefix {
        // The access path requires this text first in the system prompt
        // (Claude Code); the caller's system follows, cache marks and all.
        let mut blocks = vec![text_block(prefix)];
        match body.get("system") {
            None => {}
            Some(Value::Array(existing)) => blocks.extend(existing.iter().cloned()),
            Some(Value::String(existing)) => blocks.push(text_block(existing)),
            Some(other) => blocks.push(text_block(&other.to_string())),
        }
        body.insert("system".into(), Value::Array(blocks));
    }
    Ok(body)
}

fn prepare(
    request: &Request,
    model: &str,
    compat: &ResolvedAnthropicCompat,
    provider: &str,
) -> Result<Request, Lm15Error> {
    use crate::adaptation::{
        adapt, clamp_effort, drop_value, prepare_cache, summary_auto, AdaptationAction::*,
    };
    let mut out = request.clone();
    prepare_cache(&mut out, false, provider)?;
    let c = &mut out.config;
    if compat.sampling_params == SendReject::Reject {
        drop_value(
            "config.temperature",
            &mut c.temperature,
            "this server ignores sampling parameters",
        )?;
        drop_value(
            "config.top_p",
            &mut c.top_p,
            "this server ignores sampling parameters",
        )?;
        drop_value(
            "config.top_k",
            &mut c.top_k,
            "this server ignores sampling parameters",
        )?;
    }
    drop_value(
        "config.seed",
        &mut c.seed,
        "the Messages API has no seed field",
    )?;
    drop_value(
        "config.frequency_penalty",
        &mut c.frequency_penalty,
        "the Messages API has no frequency_penalty field",
    )?;
    drop_value(
        "config.presence_penalty",
        &mut c.presence_penalty,
        "the Messages API has no presence_penalty field",
    )?;
    if let Some(t) = c.temperature.filter(|t| *t > 1.0) {
        adapt(
            "config.temperature",
            Clamped,
            Some(json!(t)),
            Some(json!(1.0)),
            "the Messages API accepts temperature in [0, 1]; the canonical range is [0, 2]",
        )?;
        c.temperature = Some(1.0);
    }
    if let Some(r) = &mut c.reasoning {
        if !r.is_off() {
            if let Some(levels) = compat.reasoning_efforts {
                clamp_effort(r, levels)?;
            }
            summary_auto(r)?;
            let adaptive = compat.thinking_format != AnthropicThinkingFormat::Anthropic
                || anthropic_adaptive_class(model);
            if adaptive {
                drop_value(
                    "config.reasoning.thinking_budget",
                    &mut r.thinking_budget,
                    "this model class has no thinking budget; effort carries the intent. Thinking is \
                     bounded only by max_tokens, which covers thinking and answer together: lower \
                     the effort or raise max_tokens",
                )?;
                if compat.thinking_format == AnthropicThinkingFormat::Anthropic
                    && r.effort == ReasoningEffort::Minimal
                {
                    clamp_effort(
                        r,
                        &[
                            ReasoningEffort::Low,
                            ReasoningEffort::Medium,
                            ReasoningEffort::High,
                            ReasoningEffort::Xhigh,
                            ReasoningEffort::Max,
                        ],
                    )?;
                }
            }
        }
    }
    if c.max_tokens.is_none() {
        // MAP-13 `defaulted`; MAP-7 rule 6 (amended 2026-09-30): a Claude
        // model is sent its own output ceiling as the WIRE value — on the
        // manual class the visible part is what the thinking budget leaves
        // (a budget at or above the ceiling keeps 16384 visible, and the
        // server's 400 names the limit); any other model 16384 visible.
        let manual_budget = c
            .reasoning
            .as_ref()
            .filter(|r| !r.is_off())
            .filter(|_| {
                compat.thinking_format == AnthropicThinkingFormat::Anthropic
                    && !anthropic_adaptive_class(model)
            })
            .and_then(|r| {
                r.thinking_budget
                    .or_else(|| effort_thinking_budget(r.effort))
            });
        let ceiling = claude_output_ceiling(model);
        let visible = match (ceiling, manual_budget) {
            (None, _) => DEFAULT_VISIBLE_TOKENS,
            (Some(ceiling), None) => ceiling,
            (Some(ceiling), Some(budget)) if budget < ceiling => ceiling - budget,
            (Some(_), Some(_)) => DEFAULT_VISIBLE_TOKENS,
        };
        adapt(
            "config.max_tokens",
            Defaulted,
            None,
            Some(json!(visible)),
            if ceiling.is_some() {
                "the Messages API requires max_tokens and none was set; the model's output ceiling was used"
            } else {
                "the Messages API requires max_tokens and none was set; 16384 was used (this server's ceiling is its own)"
            },
        )?;
        c.max_tokens = Some(visible);
    }
    if let Some(cache) = &mut c.cache {
        drop_value(
            "config.cache.key",
            &mut cache.key,
            "the Messages API has no cache affinity key; marks are its mechanism",
        )?;
        if compat.cache_control != AnthropicCacheControl::Anthropic
            && cache.retention == Some(CacheRetention::Long)
        {
            adapt(
                "config.cache.retention",
                Dropped,
                Some(json!("long")),
                None,
                "this server caches implicitly and has no cache-control TTL",
            )?;
            cache.retention = None;
        }
    }
    if let Some(choice) = &mut c.tool_choice {
        if choice.mode != ToolChoiceMode::None
            && !choice.allowed.is_empty()
            && !(choice.allowed.len() == 1 && choice.mode == ToolChoiceMode::Required)
            && out
                .tools
                .iter()
                .any(|t| !choice.allowed.iter().any(|n| n == t.name()))
        {
            adapt(
                "config.tool_choice.allowed",
                ClientSide,
                Some(json!(choice.allowed)),
                Some(json!(choice.allowed)),
                "only allowed tools were sent; the wire cannot express a proper subset",
            )?;
            out.tools
                .retain(|t| choice.allowed.iter().any(|n| n == t.name()));
        }
        if compat.parallel_tool_calls == SendReject::Reject {
            drop_value(
                "config.tool_choice.parallel",
                &mut choice.parallel,
                "this server ignores disable_parallel_tool_use",
            )?;
        }
    }
    if compat.structured_output == SendReject::Reject {
        drop_value(
            "config.response_format",
            &mut c.response_format,
            "this server accepts output_config.format without applying the schema",
        )?;
    }
    if let Some(store) = c.store.take() {
        adapt(
            "config.store",
            if store { Dropped } else { Satisfied },
            Some(json!(store)),
            None,
            "the Messages API has no retrievable stored-response object",
        )?;
    }
    drop_value(
        "config.logprobs",
        &mut c.logprobs,
        "the Messages API does not expose token log probabilities",
    )?;
    Ok(out)
}

// ─── Caching (MAP-6) ────────────────────────────────────────────────

/// The marks this request places (`lm15/providers/anthropic.py:520-560`).
struct CachePlan {
    /// Marks are placed at all: `config.cache` present, not `off`, and
    /// the compat says the server reads `cache_control`.
    active: bool,
    /// `ttl: "1h"` on every mark (`retention="long"`).
    long: bool,
    /// The message whose last block carries a mark, before clamping.
    prefix_until_index: Option<u64>,
    /// `prefix="history"`: the last message.
    history: bool,
}

impl CachePlan {
    fn marker(&self) -> Value {
        if self.long {
            json!({"type": "ephemeral", "ttl": "1h"})
        } else {
            json!({"type": "ephemeral"})
        }
    }

    /// The index of the message to mark, clamped to the last one.
    fn message_mark(&self, count: usize) -> Option<usize> {
        if !self.active || count == 0 {
            return None;
        }
        let last = count - 1;
        if let Some(index) = self.prefix_until_index {
            return Some(usize::try_from(index).map_or(last, |i| i.min(last)));
        }
        self.history.then_some(last)
    }
}

fn cache_plan(
    cache: Option<&CacheConfig>,
    compat: &ResolvedAnthropicCompat,
    refuse: &Refuse<'_>,
) -> Result<CachePlan, Lm15Error> {
    let Some(cache) = cache else {
        return Ok(CachePlan {
            active: false,
            long: false,
            prefix_until_index: None,
            history: false,
        });
    };
    let marks = compat.cache_control == AnthropicCacheControl::Anthropic;
    // MAP-6 rule 7: no server on this wire has the resource tier.
    if cache.resource.is_some() {
        return Err(refuse.feature(
            "cache.resource is not supported — the Messages API has no stored-cache tier; it \
             caches by marks on blocks",
        ));
    }
    let active = cache.mode != CacheMode::Off && marks;
    if active && cache.key.is_some() {
        // MAP-6 rule 6: no affinity key; marks are the mechanism. A server
        // that ignores marks (`cache_control="none"`) caches implicitly
        // and the hint has nothing to attach to (the chat-dialect rule).
        return Err(refuse.feature(
            "cache.key is not supported — the Messages API has no cache affinity key (OpenAI's \
             prompt_cache_key); marks on blocks are the mechanism (prefix / prefix_until_index)",
        ));
    }
    let long = cache.retention == Some(CacheRetention::Long);
    if long && !marks {
        // MAP-6 rule 5 names a mechanism (`ttl: "1h"`, 2x write); a server
        // without marks cannot apply it, and the caller would believe it did.
        return Err(refuse.feature(
            "cache.retention='long' is not supported on this server — it caches implicitly and \
             has no cache_control ttl",
        ));
    }
    Ok(CachePlan {
        active,
        long: long && active,
        prefix_until_index: cache.prefix_until_index,
        history: cache.prefix == Some(CachePrefix::History),
    })
}

/// `cache_control` on the last content block of a rendered message.
fn mark_last_block(message: &mut Value, marker: Value) {
    if let Some(Value::Object(block)) = message
        .get_mut("content")
        .and_then(Value::as_array_mut)
        .and_then(|blocks| blocks.last_mut())
    {
        block.entry("cache_control").or_insert(marker);
    }
}

/// `system`: a string stays a string; with marks active it becomes one
/// marked text block (`lm15/providers/anthropic.py:619-627`, MAP-6 rule
/// 3). Parts become one block each (no lossy join); the last one carries
/// the mark. Only text has a system block on this wire.
fn system_value(
    system: &SystemContent,
    cache: &CachePlan,
    cx: &PartContext<'_>,
) -> Result<Value, Lm15Error> {
    let mut blocks = match system {
        SystemContent::Text(text) => {
            if !cache.active {
                return Ok(Value::String(text.clone()));
            }
            vec![text_block(text)]
        }
        SystemContent::Parts(parts) => parts
            .iter()
            .map(|part| match part {
                Part::Text(t) => Ok(text_block(&t.text)),
                Part::Data(d) => Ok(text_block(&d.value.to_string())),
                other => Err(cx.refuse.feature(format!(
                    "system accepts text blocks only on the Messages API; a {} part has no \
                     system block (put it in the first user message)",
                    other.type_name()
                ))),
            })
            .collect::<Result<Vec<_>, _>>()?,
    };
    if cache.active {
        if let Some(Value::Object(last)) = blocks.last_mut() {
            last.insert("cache_control".into(), cache.marker());
        }
    }
    Ok(Value::Array(blocks))
}

// ─── Reasoning (MAP-5, MAP-7) ───────────────────────────────────────

/// How `config.reasoning` reaches the wire under the compat's
/// `thinking_format` (`lm15/providers/anthropic.py:562-611`, `:667-701`).
struct ThinkingPlan {
    format: AnthropicThinkingFormat,
    /// Reasoning is present and not off, and the adaptive shape applies
    /// (every compat format but `anthropic`, or the adaptive model class).
    adaptive: bool,
    /// Manual class: the `budget_tokens` on the wire.
    budget: Option<u64>,
}

impl ThinkingPlan {
    /// `lm15/providers/anthropic.py:161-169`: the manual class adds the
    /// budget to the visible cap (the wire's `max_tokens` includes thinking,
    /// MAP-7 rule 6); otherwise `Config.max_tokens` is the total.
    fn max_tokens(&self, configured: Option<u64>) -> Result<u64, Lm15Error> {
        let visible = configured.unwrap_or(DEFAULT_VISIBLE_TOKENS);
        visible
            .checked_add(self.budget.unwrap_or(0))
            .ok_or_else(|| {
                Lm15Error::InvalidRequestError(crate::errors::ErrorMeta::new(
                    "max_tokens plus thinking_budget overflows; a bounded output cap is required",
                ))
            })
    }

    /// The `thinking` object, if any.
    fn wire(&self, reasoning: Option<&Reasoning>) -> Option<Value> {
        let off = reasoning.is_some_and(Reasoning::is_off);
        match self.format {
            // DeepSeek (thinking on by default: off MUST be sent) and Moonshot
            // (`disabled` is honoured, live 2026-09-03).
            AnthropicThinkingFormat::Deepseek | AnthropicThinkingFormat::Effort if off => {
                Some(json!({"type": "disabled"}))
            }
            AnthropicThinkingFormat::Deepseek if self.adaptive => Some(json!({"type": "enabled"})),
            AnthropicThinkingFormat::Effort => None,
            // Meta: the server reasons by default and cannot stop; an
            // explicit off reaches the wire so the server refuses it loudly.
            AnthropicThinkingFormat::Adaptive if off => Some(json!({"type": "disabled"})),
            _ if self.adaptive => Some(json!({"type": "adaptive"})),
            _ => self
                .budget
                .map(|budget| json!({"type": "enabled", "budget_tokens": budget})),
        }
    }

    /// `output_config.effort`: the word verbatim on every adaptive shape.
    fn effort(&self, reasoning: Option<&Reasoning>) -> Option<ReasoningEffort> {
        if !self.adaptive {
            return None;
        }
        reasoning
            .map(|r| r.effort)
            .filter(|e| *e != ReasoningEffort::Off)
    }
}

fn thinking_plan(
    reasoning: Option<&Reasoning>,
    model: &str,
    compat: &ResolvedAnthropicCompat,
    refuse: &Refuse<'_>,
) -> Result<ThinkingPlan, Lm15Error> {
    let format = compat.thinking_format;
    let mut plan = ThinkingPlan {
        format,
        adaptive: false,
        budget: None,
    };
    let Some(reasoning) = reasoning.filter(|r| !r.is_off()) else {
        // MAP-5: absent sends nothing; off is the native disable (absence
        // on api.anthropic.com; `disabled` where the compat says so).
        return Ok(plan);
    };
    if let Some(levels) = compat.reasoning_efforts {
        if !levels.contains(&reasoning.effort) {
            // MAP-7 rule 2: a word with no native level raises here when
            // the server would not refuse it (Moonshot answered 200 to
            // `medium` and to `bogus`, live 2026-09-03).
            let accepted: Vec<&str> = levels.iter().map(|e| e.as_str()).collect();
            return Err(refuse.feature(format!(
                "reasoning.effort={:?} has no level on this server (it accepts {}) and would be \
                 accepted silently",
                reasoning.effort.as_str(),
                accepted.join(", ")
            )));
        }
    }
    if matches!(
        reasoning.summary,
        Some(ReasoningSummary::Concise) | Some(ReasoningSummary::Detailed)
    ) {
        // MAP-7 rule 7: OpenAI detail levels; `auto` is satisfied silently
        // (thinking blocks come back whenever thinking runs).
        return Err(refuse.feature(format!(
            "reasoning.summary={:?} is an OpenAI detail level; the Messages API returns thinking \
             blocks whenever thinking runs (use 'auto' or none)",
            reasoning.summary.map(|s| s.as_str()).unwrap_or_default()
        )));
    }
    let model_table = format == AnthropicThinkingFormat::Anthropic;
    plan.adaptive = !model_table || anthropic_adaptive_class(model);
    if plan.adaptive {
        if reasoning.thinking_budget.is_some() {
            // MAP-7 rule 5: no budget on the adaptive shapes.
            let why = match format {
                AnthropicThinkingFormat::Deepseek => {
                    "this server ignores budget_tokens (a silent no-op); effort is the dial"
                }
                AnthropicThinkingFormat::Adaptive | AnthropicThinkingFormat::Effort => {
                    "this server accepts budget_tokens without translating it (a silent no-op); \
                     effort is the dial"
                }
                AnthropicThinkingFormat::Anthropic => {
                    "this model class takes thinking.type 'adaptive' with output_config.effort; \
                     budget_tokens is rejected by the API (live 2026-09-02)"
                }
            };
            return Err(refuse.feature(format!(
                "reasoning.thinking_budget is not supported on {model} — {why}"
            )));
        }
        if model_table && reasoning.effort == ReasoningEffort::Minimal {
            // MAP-7 rule 2: no `minimal` level on the adaptive class. The
            // compat servers judge the word themselves (400 or allowlist).
            return Err(refuse.feature(
                "reasoning.effort='minimal' has no level on this model class \
                 (output_config.effort is low|medium|high|xhigh|max); 'low' is the floor",
            ));
        }
        return Ok(plan);
    }
    // Manual class (MAP-7 rules 3 and 5): the budget is the spelling.
    plan.budget = reasoning
        .thinking_budget
        .or_else(|| effort_thinking_budget(reasoning.effort));
    Ok(plan)
}

// ─── Tools, tool choice, structured output (MAP-8) ──────────────────

/// A function tool is `{name, description?, input_schema}`: the
/// description key is left off when the tool has none (MAP-17; Anthropic
/// refuses `null`); a builtin is its versioned type with the canonical
/// name and its config merged in.
fn tool_value(tool: &Tool) -> Value {
    match tool {
        Tool::Function(function) => {
            let mut out = Map::new();
            out.insert("name".into(), Value::String(function.name.clone()));
            function.insert_wire_description(&mut out);
            out.insert(
                "input_schema".into(),
                Value::Object(function.parameters.clone()),
            );
            Value::Object(out)
        }
        Tool::Builtin(builtin) => {
            let mut out = Map::new();
            out.insert("type".into(), builtin_tool_type(&builtin.name).into());
            out.insert("name".into(), Value::String(builtin.name.clone()));
            if let Some(config) = &builtin.config {
                for (key, value) in config {
                    out.insert(key.clone(), value.clone());
                }
            }
            Value::Object(out)
        }
    }
}

/// `lm15/providers/anthropic.py:467-506` and types.md § ToolChoice
/// (anthropic): `none`; one name + `required` → `{type: tool, name}` (server
/// tools too, live 2026-09-01); an allowlist naming every declared tool →
/// plain `any`/`auto`; a proper subset RAISES (the wire cannot express it
/// and widening would let the model call excluded tools); `parallel=false`
/// → `disable_parallel_tool_use` where the server applies it.
fn tool_choice_value(
    request: &Request,
    compat: &ResolvedAnthropicCompat,
    refuse: &Refuse<'_>,
) -> Result<Option<Value>, Lm15Error> {
    let Some(choice) = &request.config.tool_choice else {
        return Ok(None);
    };
    let mut payload = Map::new();
    if choice.mode == ToolChoiceMode::None {
        payload.insert("type".into(), "none".into());
    } else if !choice.allowed.is_empty() {
        let required = choice.mode == ToolChoiceMode::Required;
        let every_declared = request
            .tools
            .iter()
            .all(|tool| choice.allowed.iter().any(|name| name == tool.name()));
        if choice.allowed.len() == 1 && required {
            payload.insert("type".into(), "tool".into());
            payload.insert("name".into(), Value::String(choice.allowed[0].clone()));
        } else if every_declared {
            payload.insert("type".into(), if required { "any" } else { "auto" }.into());
        } else {
            return Err(refuse.feature(
                "tool_choice.allowed subsets are not supported — the Messages API can force one \
                 named tool or allow all declared tools, but cannot restrict to a subset. Send \
                 only the allowed tools in Request.tools instead",
            ));
        }
    } else if choice.mode == ToolChoiceMode::Required {
        payload.insert("type".into(), "any".into());
    } else {
        payload.insert("type".into(), "auto".into());
    }
    if compat.parallel_tool_calls == SendReject::Reject && choice.parallel.is_some() {
        // `disable_parallel_tool_use` is documented as ignored on these
        // servers; a silent no-op is refused (MAP-8 §2).
        return Err(refuse.feature(
            "tool_choice.parallel is silently ignored by this server (disable_parallel_tool_use \
             is not applied); omit it",
        ));
    }
    if choice.parallel == Some(false) && choice.mode != ToolChoiceMode::None {
        payload.insert("disable_parallel_tool_use".into(), Value::Bool(true));
    }
    Ok(Some(Value::Object(payload)))
}

/// `lm15/providers/anthropic.py:109-123`, MAP-8 rules 5 and 6:
/// `output_config.format = {type: json_schema, schema}`; `json_object`
/// RAISES (no any-JSON mode); `strict` is satisfied (always constrained);
/// `name` is a label with no slot.
fn output_format(
    format: &crate::types::JsonObject,
    refuse: &Refuse<'_>,
) -> Result<Value, Lm15Error> {
    let kind = format
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if kind == "json_object" {
        return Err(crate::adaptation::refusal(refuse.provider,"config.response_format","no sensible adaptation exists: the Messages API has no any-JSON mode; give a json_schema (objects need additionalProperties: false)"));
    }
    let mut schema = format.get("schema").cloned().unwrap_or(Value::Null);
    let found = crate::judgments::judgments_in_schema(&schema);
    if let Some(obj) = schema.as_object() {
        schema = Value::Object(crate::judgments::anthropic_schema(obj, &found));
    }
    Ok(json!({"type": "json_schema", "schema": schema}))
}