car-inference 0.32.0

Local model inference for CAR — Candle backend with Qwen3 models
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
//! Apple FoundationModels backend — on-device inference through the
//! macOS 26+ system LLM. Bridges to a small Swift shim
//! (`swift/CarFoundationModels.swift`) compiled by `build.rs`.
//!
//! Four paths are exposed:
//! - [`generate`]: blocking text generation (single round-trip).
//! - [`stream`]: callback-based incremental streaming.
//! - [`generate_with_tools`]: blocking generation with a JSON tool
//!   catalog; captured tool calls come back as standard
//!   [`crate::tasks::generate::ToolCall`]s.
//! - [`generate_structured`]: schema-guided generation — a JSON Schema
//!   is enforced by Foundation Models' constrained decoding
//!   (`DynamicGenerationSchema` → `respond(to:schema:)`).
//!
//! # Tool calling — capture-and-return bridge
//!
//! CAR's contract is "models propose; the runtime validates and
//! executes": backends return the tool *call*, never its result.
//! Foundation Models inverts that — the framework invokes the Swift
//! `Tool.call` itself mid-turn. The shim bridges the two by
//! registering capture-only tools built from each JSON-Schema tool
//! definition via `DynamicGenerationSchema` (so the model sees real
//! per-tool schemas): the first invocation records `(name, arguments)`
//! and throws a sentinel to end the turn, and the captured call is
//! returned to Rust as a standard `ToolCall`. The engine executes it
//! and drives the follow-up turn exactly as it does for remote
//! backends. Consequence: at most **one** tool call per turn (a valid
//! sequential tool-use trace; no parallel tool calls). The catalog
//! entry accordingly claims `tool_use` but NOT `multi_tool_call` —
//! the router-readable "no parallel calls" signal.
//!
//! # Boundaries (honest, not aspirational)
//!
//! - **Multimodal input** (image/video/audio) is rejected upstream with
//!   [`InferenceError::UnsupportedMode`]: the public Foundation Models
//!   API in macOS 26 is text-only.
//! - **Schema fidelity**: the JSON-Schema→`DynamicGenerationSchema`
//!   conversion natively covers `object` (declared, or typeless with
//!   `properties`), `string` (+ string enums), `integer`, `number`,
//!   `boolean`, and `array`. Everything else — typeless nodes
//!   (`oneOf`/`anyOf`/`$ref`), union types (`"type":
//!   ["number","null"]`), unrecognized types, non-string enums —
//!   degrades to a **permissive string field** (never to an empty
//!   object, which would force `{}` under constrained decoding), and
//!   numeric enums keep the base numeric type but lose the value
//!   constraint. Every such degradation is detected on the Rust side
//!   before crossing the FFI and reported via `tracing::warn!`
//!   ([`schema_degradations`]).
//! - **Pre-call assistant text is discarded on captured-call turns**:
//!   ending the turn on the capture sentinel means `respond()` throws
//!   before yielding content, so `generate_with_tools` returns
//!   `text == ""` whenever a tool call was captured. Any prose the
//!   model produced before deciding to call the tool is lost — same
//!   information the engine acts on (the call), but consumers must not
//!   expect Anthropic-style "text + tool_use in one turn".
//! - **Runtime verification** requires Apple Intelligence to be
//!   provisioned; unit tests exercise the wiring up to the
//!   `is_available()` gate only.
//!
//! Cfg-gated to `aarch64-apple-darwin`; everything below that line is
//! invisible on Linux/Intel-Mac builds. On those platforms the upstream
//! schema check (`is_foundation_models()`) still works (so registries
//! can describe the model) but dispatch errors out before calling here.

use std::ffi::{c_char, c_int, c_void, CStr, CString};
use std::ptr;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::InferenceError;

/// How long [`is_available`] caches the framework probe before re-checking.
/// Apple Intelligence can be toggled on/off in System Settings and the
/// model can finish provisioning after process start, so a permanent
/// cache would strand long-running daemons. Five seconds is enough to
/// cover a tight router loop without staling against settings changes.
const AVAILABILITY_CACHE_TTL: Duration = Duration::from_secs(5);

// ---------------------------------------------------------------------
// extern "C" surface emitted by the Swift shim.
//
// Gated by `car_fm_swift_built`, set by `build.rs` only when `swiftc`
// successfully compiled the shim into a static library. On hosts
// without full Xcode (Command Line Tools only) the cfg is absent and
// we provide stubs that report unavailable — keeps the crate buildable
// and lets the runtime path return a clean UnsupportedMode instead of
// failing at link time.
// ---------------------------------------------------------------------

#[cfg(car_fm_swift_built)]
extern "C" {
    fn car_fm_is_available() -> c_int;
    fn car_fm_free_string(ptr: *mut c_char);
    fn car_fm_generate(
        prompt: *const c_char,
        instructions: *const c_char,
        max_tokens: i32,
        temperature: f64,
        out_text: *mut *mut c_char,
        out_err: *mut *mut c_char,
    ) -> c_int;
    fn car_fm_generate_stream(
        prompt: *const c_char,
        instructions: *const c_char,
        max_tokens: i32,
        temperature: f64,
        callback: extern "C" fn(token: *const c_char, state: *mut c_void) -> c_int,
        state: *mut c_void,
        out_err: *mut *mut c_char,
    ) -> c_int;
    fn car_fm_generate_with_tools(
        prompt: *const c_char,
        instructions: *const c_char,
        tools_json: *const c_char,
        max_tokens: i32,
        temperature: f64,
        out_text: *mut *mut c_char,
        out_tool_calls_json: *mut *mut c_char,
        out_err: *mut *mut c_char,
    ) -> c_int;
    fn car_fm_generate_structured(
        prompt: *const c_char,
        instructions: *const c_char,
        schema_json: *const c_char,
        max_tokens: i32,
        temperature: f64,
        out_json: *mut *mut c_char,
        out_err: *mut *mut c_char,
    ) -> c_int;
}

#[cfg(not(car_fm_swift_built))]
mod swift_stubs {
    use super::{c_char, c_int, c_void};
    /// Always returns 0 (unavailable). The runtime check in
    /// [`super::is_available`] catches this and prevents any of the
    /// other extern paths from being called.
    pub(super) unsafe fn car_fm_is_available() -> c_int {
        0
    }
    /// No allocation crossed the boundary, so nothing to free.
    pub(super) unsafe fn car_fm_free_string(_ptr: *mut c_char) {}
    /// Unreachable: gated upstream by [`super::is_available`].
    pub(super) unsafe fn car_fm_generate(
        _prompt: *const c_char,
        _instructions: *const c_char,
        _max_tokens: i32,
        _temperature: f64,
        _out_text: *mut *mut c_char,
        _out_err: *mut *mut c_char,
    ) -> c_int {
        unreachable!("car_fm_generate called without the Swift bridge")
    }
    /// Unreachable: gated upstream by [`super::is_available`].
    pub(super) unsafe fn car_fm_generate_stream(
        _prompt: *const c_char,
        _instructions: *const c_char,
        _max_tokens: i32,
        _temperature: f64,
        _callback: extern "C" fn(token: *const c_char, state: *mut c_void) -> c_int,
        _state: *mut c_void,
        _out_err: *mut *mut c_char,
    ) -> c_int {
        unreachable!("car_fm_generate_stream called without the Swift bridge")
    }
    /// Unreachable: gated upstream by [`super::is_available`].
    pub(super) unsafe fn car_fm_generate_with_tools(
        _prompt: *const c_char,
        _instructions: *const c_char,
        _tools_json: *const c_char,
        _max_tokens: i32,
        _temperature: f64,
        _out_text: *mut *mut c_char,
        _out_tool_calls_json: *mut *mut c_char,
        _out_err: *mut *mut c_char,
    ) -> c_int {
        unreachable!("car_fm_generate_with_tools called without the Swift bridge")
    }
    /// Unreachable: gated upstream by [`super::is_available`].
    pub(super) unsafe fn car_fm_generate_structured(
        _prompt: *const c_char,
        _instructions: *const c_char,
        _schema_json: *const c_char,
        _max_tokens: i32,
        _temperature: f64,
        _out_json: *mut *mut c_char,
        _out_err: *mut *mut c_char,
    ) -> c_int {
        unreachable!("car_fm_generate_structured called without the Swift bridge")
    }
}

#[cfg(not(car_fm_swift_built))]
use swift_stubs::{
    car_fm_free_string, car_fm_generate, car_fm_generate_stream, car_fm_generate_structured,
    car_fm_generate_with_tools, car_fm_is_available,
};

// ---------------------------------------------------------------------
// Public API.
// ---------------------------------------------------------------------

/// Returns true when the FoundationModels framework is available **and**
/// the on-device model is provisioned. Cached for [`AVAILABILITY_CACHE_TTL`]
/// so a tight router loop doesn't repeatedly cross the FFI boundary,
/// while still allowing recovery from "framework unavailable at startup,
/// available later" — which is the common case for long-running
/// daemons whose host machine finishes Apple Intelligence provisioning
/// minutes after launch.
pub fn is_available() -> bool {
    // (Instant, value) pair under a Mutex. The probe itself is cheap; the
    // Mutex overhead is negligible vs the FFI call we're avoiding.
    static CACHE: Mutex<Option<(Instant, bool)>> = Mutex::new(None);

    let now = Instant::now();
    let mut guard = match CACHE.lock() {
        Ok(g) => g,
        Err(poisoned) => poisoned.into_inner(),
    };
    if let Some((stamped, value)) = *guard {
        if now.duration_since(stamped) < AVAILABILITY_CACHE_TTL {
            return value;
        }
    }
    let value = unsafe { car_fm_is_available() != 0 };
    *guard = Some((now, value));
    value
}

/// Blocking single-shot generation. The caller is responsible for
/// running this on a blocking-friendly executor (the Swift bridge uses
/// a `DispatchSemaphore` to wait on the underlying async task).
pub fn generate(
    prompt: &str,
    instructions: Option<&str>,
    max_tokens: u32,
    temperature: f32,
) -> Result<String, InferenceError> {
    if !is_available() {
        return Err(unavailable_error());
    }

    let prompt_c = CString::new(prompt)
        .map_err(|e| InferenceError::InferenceFailed(format!("prompt has interior NUL: {e}")))?;
    let instr_c = match instructions {
        Some(s) if !s.is_empty() => Some(CString::new(s).map_err(|e| {
            InferenceError::InferenceFailed(format!("instructions have interior NUL: {e}"))
        })?),
        _ => None,
    };

    let mut out_text: *mut c_char = ptr::null_mut();
    let mut out_err: *mut c_char = ptr::null_mut();

    let rc = unsafe {
        car_fm_generate(
            prompt_c.as_ptr(),
            instr_c.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
            max_tokens.min(i32::MAX as u32) as i32,
            temperature as f64,
            &mut out_text as *mut *mut c_char,
            &mut out_err as *mut *mut c_char,
        )
    };

    if rc != 0 {
        return Err(InferenceError::InferenceFailed(consume_swift_string(
            out_err,
        )));
    }
    Ok(consume_swift_string(out_text))
}

/// Detect JSON-Schema constructs the Swift `DynamicGenerationSchema`
/// conversion degrades, so constrained decoding never weakens its
/// contract silently. Mirrors the converter's rules exactly:
///
/// * typeless node without `properties` (`oneOf`/`anyOf`/`allOf`/
///   `$ref`/`not`, or nothing at all) → permissive string
/// * union type (`"type": ["number","null"]`) → permissive string
/// * unrecognized `type` value → permissive string
/// * `enum` on a non-`string` type → base type kept, values ignored
/// * `enum` with non-string members on a `string` type → constraint
///   dropped (Swift's `as? [String]` cast fails)
///
/// Returns one human-readable finding per degradation with a JSON-path
/// prefix. Callers `tracing::warn!` the list before crossing the FFI.
pub fn schema_degradations(schema: &serde_json::Value) -> Vec<String> {
    let mut findings = Vec::new();
    walk_schema(schema, "$", &mut findings);
    findings
}

fn walk_schema(node: &serde_json::Value, path: &str, findings: &mut Vec<String>) {
    let Some(obj) = node.as_object() else {
        findings.push(format!(
            "{path}: schema node is not a JSON object — degraded to permissive string"
        ));
        return;
    };

    for combinator in ["oneOf", "anyOf", "allOf", "not", "$ref"] {
        if obj.contains_key(combinator) {
            findings.push(format!(
                "{path}: `{combinator}` is not representable — flattened to permissive string"
            ));
        }
    }

    let type_str = match obj.get("type") {
        None => {
            if !obj.contains_key("properties") {
                // Only flag when no combinator already explained the
                // typeless-ness — one finding per cause, not two.
                if !["oneOf", "anyOf", "allOf", "not", "$ref"]
                    .iter()
                    .any(|c| obj.contains_key(*c))
                {
                    findings.push(format!(
                        "{path}: typeless node without `properties` — degraded to permissive \
                         string"
                    ));
                }
                return;
            }
            // Typeless with `properties` — inferred object, no loss.
            "object"
        }
        Some(serde_json::Value::String(t)) => t.as_str(),
        Some(other) => {
            findings.push(format!(
                "{path}: union/non-string `type` ({other}) — degraded to permissive string"
            ));
            return;
        }
    };

    match type_str {
        "object" => {
            if let Some(props) = obj.get("properties").and_then(|p| p.as_object()) {
                for (key, sub) in props {
                    walk_schema(sub, &format!("{path}.{key}"), findings);
                }
            }
        }
        "array" => {
            if let Some(items) = obj.get("items") {
                walk_schema(items, &format!("{path}[]"), findings);
            }
        }
        "string" => {
            if let Some(choices) = obj.get("enum").and_then(|e| e.as_array()) {
                if choices.iter().any(|c| !c.is_string()) {
                    findings.push(format!(
                        "{path}: `enum` contains non-string members — enum constraint dropped, \
                         degraded to permissive string"
                    ));
                }
            }
        }
        "integer" | "number" | "boolean" => {
            if obj.contains_key("enum") {
                findings.push(format!(
                    "{path}: `enum` on `{type_str}` is not representable — values ignored, \
                     plain `{type_str}` kept"
                ));
            }
        }
        other => {
            findings.push(format!(
                "{path}: unrecognized `type` \"{other}\" — degraded to permissive string"
            ));
        }
    }
}

/// Warn once per degradation the Swift converter will apply to
/// `schema`. `what` names the schema's role in the log line (e.g.
/// `tool 'get_weather' parameters`, `response_format JsonSchema`).
fn warn_schema_degradations(what: &str, schema: &serde_json::Value) {
    for finding in schema_degradations(schema) {
        tracing::warn!(
            "FoundationModels constrained decoding: {what}: {finding} — the generated value is \
             preserved but this part of the schema contract is not enforced"
        );
    }
}

/// Blocking generation with a tool catalog. `tools` is the same
/// JSON-Schema tool array `GenerateRequest.tools` carries
/// (`[{name, description, parameters}]`). Returns the final text plus
/// any captured tool calls in the standard [`ToolCall`] shape the
/// remote backends emit — the runtime executes them, this backend
/// never does (see the module docs for the capture-and-return bridge).
///
/// At most one tool call is returned per turn. When a call was
/// captured, `text` is **always empty** — ending the turn on the
/// capture sentinel discards any prose the model produced before
/// deciding to call the tool (see the module-level Boundaries).
pub fn generate_with_tools(
    prompt: &str,
    instructions: Option<&str>,
    tools: &[serde_json::Value],
    max_tokens: u32,
    temperature: f32,
) -> Result<(String, Vec<crate::tasks::generate::ToolCall>), InferenceError> {
    if !is_available() {
        return Err(unavailable_error());
    }

    let prompt_c = CString::new(prompt)
        .map_err(|e| InferenceError::InferenceFailed(format!("prompt has interior NUL: {e}")))?;
    let instr_c = match instructions {
        Some(s) if !s.is_empty() => Some(CString::new(s).map_err(|e| {
            InferenceError::InferenceFailed(format!("instructions have interior NUL: {e}"))
        })?),
        _ => None,
    };
    for tool in tools {
        let name = tool
            .get("name")
            .and_then(|n| n.as_str())
            .unwrap_or("<unnamed>");
        if let Some(params) = tool.get("parameters") {
            warn_schema_degradations(&format!("tool '{name}' parameters"), params);
        }
    }
    let tools_json = serde_json::to_string(tools)
        .map_err(|e| InferenceError::InferenceFailed(format!("tools serialization: {e}")))?;
    let tools_c = CString::new(tools_json)
        .map_err(|e| InferenceError::InferenceFailed(format!("tools have interior NUL: {e}")))?;

    let mut out_text: *mut c_char = ptr::null_mut();
    let mut out_calls: *mut c_char = ptr::null_mut();
    let mut out_err: *mut c_char = ptr::null_mut();

    let rc = unsafe {
        car_fm_generate_with_tools(
            prompt_c.as_ptr(),
            instr_c.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
            tools_c.as_ptr(),
            max_tokens.min(i32::MAX as u32) as i32,
            temperature as f64,
            &mut out_text as *mut *mut c_char,
            &mut out_calls as *mut *mut c_char,
            &mut out_err as *mut *mut c_char,
        )
    };

    if rc != 0 {
        return Err(InferenceError::InferenceFailed(consume_swift_string(
            out_err,
        )));
    }
    let text = consume_swift_string(out_text);
    let calls_json = consume_swift_string(out_calls);
    let tool_calls = parse_bridge_tool_calls(&calls_json)?;
    Ok((text, tool_calls))
}

/// Parse the shim's `[{"name": ..., "arguments": {...}}]` wire shape
/// into the standard [`ToolCall`] list. `id` is `None` — Foundation
/// Models has no provider call IDs; consumers synthesize positional
/// ones exactly as they do for other id-less backends.
fn parse_bridge_tool_calls(
    calls_json: &str,
) -> Result<Vec<crate::tasks::generate::ToolCall>, InferenceError> {
    if calls_json.trim().is_empty() {
        return Ok(vec![]);
    }
    #[derive(serde::Deserialize)]
    struct BridgeCall {
        name: String,
        #[serde(default)]
        arguments: std::collections::HashMap<String, serde_json::Value>,
    }
    let calls: Vec<BridgeCall> = serde_json::from_str(calls_json).map_err(|e| {
        InferenceError::InferenceFailed(format!(
            "FoundationModels bridge returned malformed tool-call JSON: {e}"
        ))
    })?;
    Ok(calls
        .into_iter()
        .map(|c| crate::tasks::generate::ToolCall {
            id: None,
            name: c.name,
            arguments: c.arguments,
        })
        .collect())
}

/// Blocking schema-guided generation (`ResponseFormat::JsonSchema`).
/// The JSON Schema is converted to a `DynamicGenerationSchema` and
/// enforced by Foundation Models' constrained decoding; the returned
/// string is the generated JSON document.
pub fn generate_structured(
    prompt: &str,
    instructions: Option<&str>,
    schema: &serde_json::Value,
    max_tokens: u32,
    temperature: f32,
) -> Result<String, InferenceError> {
    if !is_available() {
        return Err(unavailable_error());
    }

    let prompt_c = CString::new(prompt)
        .map_err(|e| InferenceError::InferenceFailed(format!("prompt has interior NUL: {e}")))?;
    let instr_c = match instructions {
        Some(s) if !s.is_empty() => Some(CString::new(s).map_err(|e| {
            InferenceError::InferenceFailed(format!("instructions have interior NUL: {e}"))
        })?),
        _ => None,
    };
    warn_schema_degradations("response_format JsonSchema", schema);
    let schema_json = serde_json::to_string(schema)
        .map_err(|e| InferenceError::InferenceFailed(format!("schema serialization: {e}")))?;
    let schema_c = CString::new(schema_json)
        .map_err(|e| InferenceError::InferenceFailed(format!("schema has interior NUL: {e}")))?;

    let mut out_json: *mut c_char = ptr::null_mut();
    let mut out_err: *mut c_char = ptr::null_mut();

    let rc = unsafe {
        car_fm_generate_structured(
            prompt_c.as_ptr(),
            instr_c.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
            schema_c.as_ptr(),
            max_tokens.min(i32::MAX as u32) as i32,
            temperature as f64,
            &mut out_json as *mut *mut c_char,
            &mut out_err as *mut *mut c_char,
        )
    };

    if rc != 0 {
        return Err(InferenceError::InferenceFailed(consume_swift_string(
            out_err,
        )));
    }
    Ok(consume_swift_string(out_json))
}

/// Token shape used by the streaming callback. The Swift side already
/// performs prefix-diffing on the cumulative snapshots Foundation
/// Models emits, so each delta is the newly-appended slice — no
/// further work needed on the consumer.
pub struct StreamCallback<'a> {
    on_delta: Box<dyn FnMut(&str) -> bool + Send + 'a>,
}

impl<'a> StreamCallback<'a> {
    /// `on_delta` is invoked for each incremental text fragment.
    /// Returning `false` cancels the stream.
    pub fn new<F>(on_delta: F) -> Self
    where
        F: FnMut(&str) -> bool + Send + 'a,
    {
        Self {
            on_delta: Box::new(on_delta),
        }
    }
}

extern "C" fn stream_trampoline(token: *const c_char, state: *mut c_void) -> c_int {
    // SAFETY: this function runs on a thread Swift owns; an unwinding
    // panic crossing back into Swift is undefined behavior. Wrap the
    // body in catch_unwind and translate panics into "cancel" so the
    // model turn aborts cleanly instead of taking the process down.
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        if state.is_null() {
            return 1;
        }
        let cb = unsafe { &mut *(state as *mut StreamCallback) };
        let s = if token.is_null() {
            ""
        } else {
            match unsafe { CStr::from_ptr(token) }.to_str() {
                Ok(s) => s,
                Err(_) => return 1,
            }
        };
        if (cb.on_delta)(s) {
            0 // continue
        } else {
            1 // cancel
        }
    }));
    match result {
        Ok(rc) => rc,
        Err(_) => 1, // cancel on panic
    }
}

/// Blocking streaming generation. Each delta is forwarded to the
/// callback as a string slice owned by Swift — copy if it needs to
/// outlive the call.
pub fn stream(
    prompt: &str,
    instructions: Option<&str>,
    max_tokens: u32,
    temperature: f32,
    mut callback: StreamCallback<'_>,
) -> Result<(), InferenceError> {
    if !is_available() {
        return Err(unavailable_error());
    }

    let prompt_c = CString::new(prompt)
        .map_err(|e| InferenceError::InferenceFailed(format!("prompt has interior NUL: {e}")))?;
    let instr_c = match instructions {
        Some(s) if !s.is_empty() => Some(CString::new(s).map_err(|e| {
            InferenceError::InferenceFailed(format!("instructions have interior NUL: {e}"))
        })?),
        _ => None,
    };

    let mut out_err: *mut c_char = ptr::null_mut();
    let state: *mut c_void = &mut callback as *mut StreamCallback as *mut c_void;

    let rc = unsafe {
        car_fm_generate_stream(
            prompt_c.as_ptr(),
            instr_c.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
            max_tokens.min(i32::MAX as u32) as i32,
            temperature as f64,
            stream_trampoline,
            state,
            &mut out_err as *mut *mut c_char,
        )
    };

    if rc != 0 {
        return Err(InferenceError::InferenceFailed(consume_swift_string(
            out_err,
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------
// Helpers.
// ---------------------------------------------------------------------

fn consume_swift_string(ptr: *mut c_char) -> String {
    if ptr.is_null() {
        return String::new();
    }
    let s = unsafe { CStr::from_ptr(ptr) }
        .to_string_lossy()
        .into_owned();
    unsafe { car_fm_free_string(ptr) };
    s
}

fn unavailable_error() -> InferenceError {
    InferenceError::UnsupportedMode {
        mode: "apple-foundation-models",
        backend: "foundation-models",
        reason: "FoundationModels framework reports unavailable on this host. Requires macOS 26+ \
             on Apple Silicon with Apple Intelligence enabled. Falling through to the next \
             router candidate.",
    }
}

#[cfg(test)]
mod tests {
    use super::{parse_bridge_tool_calls, schema_degradations};

    #[test]
    fn parses_bridge_tool_call_wire_shape() {
        let calls = parse_bridge_tool_calls(
            r#"[{"name":"get_weather","arguments":{"city":"Austin","days":3}}]"#,
        )
        .unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name, "get_weather");
        assert_eq!(calls[0].id, None);
        assert_eq!(
            calls[0].arguments.get("city"),
            Some(&serde_json::json!("Austin"))
        );
        assert_eq!(calls[0].arguments.get("days"), Some(&serde_json::json!(3)));
    }

    #[test]
    fn empty_or_missing_calls_parse_to_empty() {
        assert!(parse_bridge_tool_calls("").unwrap().is_empty());
        assert!(parse_bridge_tool_calls("[]").unwrap().is_empty());
    }

    #[test]
    fn malformed_calls_json_is_an_error_not_a_silent_drop() {
        assert!(parse_bridge_tool_calls("{not json").is_err());
    }

    #[test]
    fn clean_schema_has_no_degradations() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "city": {"type": "string", "enum": ["Austin", "Boston"]},
                "days": {"type": "integer"},
                "tags": {"type": "array", "items": {"type": "string"}},
                "nested": {"properties": {"ok": {"type": "boolean"}}}
            },
            "required": ["city"]
        });
        assert!(schema_degradations(&schema).is_empty());
    }

    #[test]
    fn union_type_is_flagged_as_string_degradation() {
        // The review's failure case: nullable union must degrade to a
        // permissive string (and be reported), never to an empty object.
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "amount": {"type": ["number", "null"]}
            }
        });
        let findings = schema_degradations(&schema);
        assert_eq!(findings.len(), 1);
        assert!(findings[0].contains("$.amount"), "{findings:?}");
        assert!(findings[0].contains("union"), "{findings:?}");
        assert!(findings[0].contains("permissive string"), "{findings:?}");
    }

    #[test]
    fn typeless_oneof_and_ref_are_flagged() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "choice": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
                "linked": {"$ref": "#/definitions/thing"},
                "mystery": {"description": "no type at all"}
            }
        });
        let findings = schema_degradations(&schema);
        let all = findings.join("\n");
        assert!(all.contains("$.choice") && all.contains("oneOf"), "{all}");
        assert!(all.contains("$.linked") && all.contains("$ref"), "{all}");
        assert!(all.contains("$.mystery") && all.contains("typeless"), "{all}");
    }

    #[test]
    fn numeric_enum_and_unrecognized_type_are_flagged() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "level": {"type": "integer", "enum": [1, 2, 3]},
                "weird": {"type": "null"},
                "mixed": {"type": "string", "enum": ["a", 1]}
            }
        });
        let findings = schema_degradations(&schema);
        let all = findings.join("\n");
        assert!(all.contains("$.level") && all.contains("values ignored"), "{all}");
        assert!(all.contains("$.weird") && all.contains("unrecognized"), "{all}");
        assert!(all.contains("$.mixed") && all.contains("non-string members"), "{all}");
        assert_eq!(findings.len(), 3);
    }

    #[test]
    fn array_items_are_walked() {
        let schema = serde_json::json!({
            "type": "array",
            "items": {"anyOf": [{"type": "string"}]}
        });
        let findings = schema_degradations(&schema);
        assert_eq!(findings.len(), 1);
        assert!(findings[0].contains("$[]") && findings[0].contains("anyOf"));
    }
}