wiremux 0.11.5

Wiremux maps Chat Completions, Messages, Responses, Gemini, and Converse through one IR.
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
//! Namespace flatten, restore, and tool-type policy.

use serde_json::{Value, json};
use wiremux_auth::{ResolvedProfile, ToolNameCase, ToolTypePolicy, Wire};

use super::{MapError, apply_tool_name_case};
use crate::ir::{IrRequest, IrTool, LossAction, LossReport};

const HOSTED_KINDS: &[&str] = &[
    "web_search",
    "web_search_preview",
    "file_search",
    "code_interpreter",
    "computer",
    "image_generation",
    "mcp",
    "local_shell",
    "shell",
    "tool_search",
];

/// Tool ready for a dialect encoder.
#[derive(Clone, Debug)]
pub(super) enum PreparedTool {
    Function {
        name: String,
        description: String,
        parameters: Value,
        strict: Option<bool>,
    },
    Raw(Value),
}

pub(super) fn decode_tool(value: &Value) -> IrTool {
    let type_name = value.get("type").and_then(Value::as_str).unwrap_or("");
    match type_name {
        "namespace" => IrTool::Namespace {
            name: value
                .get("name")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            raw: value.clone(),
        },
        "function" | "" => decode_function_or_messages(value, type_name),
        other if is_hosted(other) => IrTool::Hosted {
            kind: other.to_string(),
            raw: value.clone(),
        },
        // name+parameters must not relabel an unknown type as Function.
        other => IrTool::Unknown {
            type_name: other.to_string(),
            raw: value.clone(),
        },
    }
}

fn decode_function_or_messages(value: &Value, type_name: &str) -> IrTool {
    if let Some(func) = value.get("function") {
        return function_from(func);
    }
    if looks_like_function(value) {
        return function_from(value);
    }
    IrTool::Unknown {
        type_name: type_name.to_string(),
        raw: value.clone(),
    }
}

fn looks_like_function(value: &Value) -> bool {
    value.get("name").and_then(Value::as_str).is_some()
        && (value.get("parameters").is_some()
            || value.get("input_schema").is_some()
            || value.get("description").is_some()
            || value.get("type").and_then(Value::as_str) == Some("function"))
}

fn function_from(src: &Value) -> IrTool {
    IrTool::Function {
        name: src
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        description: src
            .get("description")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        parameters: src
            .get("parameters")
            .or_else(|| src.get("input_schema"))
            .cloned()
            .unwrap_or_else(|| json!({"type": "object", "properties": {}})),
        strict: super::bool_field(src, "strict"),
    }
}

fn wire_keeps_strict(wire: Wire) -> bool {
    matches!(
        wire,
        Wire::ChatCompletions | Wire::Responses | Wire::Converse
    )
}

fn is_hosted(type_name: &str) -> bool {
    HOSTED_KINDS.contains(&type_name)
}

pub(super) fn prepare_tools(
    wire: Wire,
    ir: &IrRequest,
    profile: &ResolvedProfile,
    report: &mut LossReport,
) -> Result<Vec<PreparedTool>, MapError> {
    let policy = profile.dialect.tool_type_policy;
    let case = profile
        .fingerprint
        .as_ref()
        .and_then(|fp| fp.tool_name_case);
    let mut out = Vec::new();
    for (idx, tool) in ir.tools.iter().enumerate() {
        let path = format!("tools[{idx}]");
        match tool {
            IrTool::Function {
                name,
                description,
                parameters,
                strict,
            } => {
                if name.trim().is_empty() {
                    return Err(MapError::hard(path, "function tool name is empty"));
                }
                if strict.is_some() && !wire_keeps_strict(wire) {
                    report.record(format!("{path}.strict"), LossAction::Drop, "no slot");
                }
                out.push(PreparedTool::Function {
                    name: apply_tool_name_case(name, case),
                    description: description.clone(),
                    parameters: parameters.clone(),
                    strict: *strict,
                });
            }
            IrTool::Namespace { name, raw } => {
                push_namespace(
                    &mut out,
                    NsPush {
                        name,
                        raw,
                        path: &path,
                        policy,
                        wire,
                        case,
                        report,
                    },
                )?;
            }
            IrTool::Hosted { kind, raw } => {
                push_hosted(&mut out, kind, raw, &path, policy, wire, report)?;
            }
            IrTool::CachePoint { raw } => {
                if wire == Wire::Converse {
                    out.push(PreparedTool::Raw(json!({ "cachePoint": raw })));
                } else {
                    report.record(path, LossAction::Drop, "tool cache point has no slot");
                }
            }
            IrTool::Unknown { type_name, raw } if type_name == "systemTool" => {
                if wire == Wire::Converse && raw.is_object() {
                    out.push(PreparedTool::Raw(json!({ "systemTool": raw })));
                } else {
                    report.record(path, LossAction::Drop, "system tool has no slot");
                }
            }
            IrTool::Unknown { type_name, raw } if type_name == "custom" => {
                push_custom_tool(&mut out, raw, &path, wire, case, report)?;
            }
            IrTool::Unknown { type_name, raw } => match policy {
                ToolTypePolicy::Passthrough => {
                    report.record(&path, LossAction::Preserve, "unknown tool passthrough");
                    out.push(PreparedTool::Raw(raw.clone()));
                }
                ToolTypePolicy::HardError | ToolTypePolicy::FlattenNamespace => {
                    return Err(MapError::hard(
                        path,
                        format!(
                            "unknown tool type `{type_name}` (tool_type_policy = passthrough|flatten-namespace|hard-error)"
                        ),
                    ));
                }
            },
        }
    }
    Ok(out)
}

struct NsPush<'a> {
    name: &'a str,
    raw: &'a Value,
    path: &'a str,
    policy: ToolTypePolicy,
    wire: Wire,
    case: Option<ToolNameCase>,
    report: &'a mut LossReport,
}

fn push_namespace(out: &mut Vec<PreparedTool>, args: NsPush<'_>) -> Result<(), MapError> {
    let NsPush {
        name,
        raw,
        path,
        policy,
        wire,
        case,
        report,
    } = args;
    // Policy is the switch. flatten-namespace flattens on every wire,
    // including Responses (OpenRouter). hard-error keeps a native
    // namespace only on Responses (Codex); elsewhere it fails closed.
    match policy {
        ToolTypePolicy::Passthrough => {
            report.record(path, LossAction::Preserve, "namespace passthrough");
            out.push(PreparedTool::Raw(raw.clone()));
            Ok(())
        }
        ToolTypePolicy::FlattenNamespace => {
            let flat = flatten_namespace(name, raw, path)?;
            report.record(
                path,
                LossAction::Degrade,
                "flatten namespace to dotted function tools",
            );
            for tool in flat {
                if let IrTool::Function {
                    name,
                    description,
                    parameters,
                    strict,
                } = tool
                {
                    if strict.is_some() && !wire_keeps_strict(wire) {
                        report.record(format!("{path}.strict"), LossAction::Drop, "no slot");
                    }
                    out.push(PreparedTool::Function {
                        name: apply_tool_name_case(&name, case),
                        description,
                        parameters,
                        strict,
                    });
                }
            }
            Ok(())
        }
        ToolTypePolicy::HardError => {
            if matches!(wire, Wire::Responses) {
                report.record(path, LossAction::Preserve, "namespace tool");
                out.push(PreparedTool::Raw(namespace_raw(name, raw)));
                return Ok(());
            }
            Err(MapError::hard(
                path,
                "type=namespace is not silent-stripped; hard-error (set tool_type_policy = flatten-namespace to flatten)",
            ))
        }
    }
}

fn push_custom_tool(
    out: &mut Vec<PreparedTool>,
    raw: &Value,
    path: &str,
    wire: Wire,
    case: Option<ToolNameCase>,
    report: &mut LossReport,
) -> Result<(), MapError> {
    let name = raw.get("name").and_then(Value::as_str).unwrap_or("");
    if name.trim().is_empty() {
        return Err(MapError::hard(path, "custom tool name is empty"));
    }
    if matches!(wire, Wire::ChatCompletions | Wire::Responses) {
        report.record(path, LossAction::Preserve, "custom tool");
        out.push(PreparedTool::Raw(raw.clone()));
        return Ok(());
    }
    report.record(
        path,
        LossAction::Degrade,
        "custom tool became a function tool",
    );
    out.push(PreparedTool::Function {
        name: apply_tool_name_case(name, case),
        description: raw
            .get("description")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        parameters: json!({"type": "object", "properties": {}}),
        strict: None,
    });
    Ok(())
}

fn push_hosted(
    out: &mut Vec<PreparedTool>,
    kind: &str,
    raw: &Value,
    path: &str,
    policy: ToolTypePolicy,
    wire: Wire,
    report: &mut LossReport,
) -> Result<(), MapError> {
    let has_hosted_slot = matches!(wire, Wire::Responses);
    match policy {
        ToolTypePolicy::Passthrough => {
            report.record(path, LossAction::Preserve, "hosted passthrough");
            out.push(PreparedTool::Raw(raw.clone()));
            Ok(())
        }
        ToolTypePolicy::HardError | ToolTypePolicy::FlattenNamespace => {
            if has_hosted_slot {
                report.record(path, LossAction::Preserve, format!("hosted {kind}"));
                out.push(PreparedTool::Raw(raw.clone()));
                Ok(())
            } else {
                Err(MapError::hard(
                    path,
                    format!("hosted tool `{kind}` has no slot on `{}`", wire.as_str()),
                ))
            }
        }
    }
}

fn namespace_raw(name: &str, raw: &Value) -> Value {
    let mut obj = match raw {
        Value::Object(map) => map.clone(),
        _ => serde_json::Map::new(),
    };
    obj.insert("type".into(), json!("namespace"));
    if !name.is_empty() {
        obj.insert("name".into(), json!(name));
    }
    Value::Object(obj)
}

fn flatten_namespace(name: &str, raw: &Value, path: &str) -> Result<Vec<IrTool>, MapError> {
    let Some(tools) = raw.get("tools").and_then(Value::as_array) else {
        return Err(MapError::hard(
            path,
            "namespace has no flatten table (tools[])",
        ));
    };
    let mut out = Vec::new();
    for child in tools {
        let child_name = child
            .get("name")
            .and_then(Value::as_str)
            .ok_or_else(|| MapError::hard(path, "namespace child missing name"))?;
        let dotted = format!("{name}.{child_name}");
        let description = child
            .get("description")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let parameters = child
            .get("parameters")
            .or_else(|| child.get("input_schema"))
            .cloned()
            .unwrap_or_else(|| json!({"type": "object", "properties": {}}));
        out.push(IrTool::Function {
            name: dotted,
            description,
            parameters,
            strict: super::bool_field(child, "strict"),
        });
    }
    if out.is_empty() {
        return Err(MapError::hard(path, "namespace flatten table is empty"));
    }
    Ok(out)
}

pub(super) fn split_namespace_name(name: &str) -> Option<(&str, &str)> {
    let (ns, leaf) = name.split_once('.')?;
    if ns.is_empty() || leaf.is_empty() {
        return None;
    }
    Some((ns, leaf))
}

pub(super) fn qualify_call_name(item: &Value) -> String {
    let name = item
        .get("name")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    match item.get("namespace").and_then(Value::as_str) {
        Some(ns) if !ns.is_empty() && !name.starts_with(&format!("{ns}.")) => {
            format!("{ns}.{name}")
        }
        _ => name,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::IrSampling;
    use wiremux_auth::parse_profile_str;

    fn profile(policy: &str) -> ResolvedProfile {
        parse_profile_str(&format!(
            r#"
schema_version = 1
id = "policy-test"
wire = "messages"
tool_type_policy = "{policy}"
"#
        ))
        .expect("profile")
    }

    fn ns_ir() -> IrRequest {
        IrRequest {
            model: "m".into(),
            items: Vec::new(),
            tools: vec![IrTool::Namespace {
                name: "crm".into(),
                raw: json!({
                    "type": "namespace",
                    "name": "crm",
                    "tools": [{
                        "type": "function",
                        "name": "lookup",
                        "description": "Lookup",
                        "parameters": {"type": "object", "properties": {}}
                    }]
                }),
            }],
            sampling: IrSampling::default(),
        }
    }

    #[test]
    fn hard_error_does_not_strip_namespace_on_messages() {
        let ir = ns_ir();
        let mut report = LossReport::default();
        let err = prepare_tools(Wire::Messages, &ir, &profile("hard-error"), &mut report)
            .expect_err("must hard-error");
        assert!(matches!(err, MapError::HardError { .. }));
        assert_eq!(ir.tools.len(), 1);
    }

    #[test]
    fn flatten_emits_dotted_function() {
        let ir = ns_ir();
        let mut report = LossReport::default();
        let tools = prepare_tools(
            Wire::Messages,
            &ir,
            &profile("flatten-namespace"),
            &mut report,
        )
        .expect("flatten");
        match &tools[0] {
            PreparedTool::Function {
                name, description, ..
            } => {
                assert_eq!(name, "crm.lookup");
                assert_eq!(description, "Lookup");
            }
            other => panic!("expected function, got {other:?}"),
        }
    }

    #[test]
    fn flatten_namespace_on_responses_emits_function_not_namespace() {
        let ir = ns_ir();
        let mut report = LossReport::default();
        let tools = prepare_tools(
            Wire::Responses,
            &ir,
            &profile("flatten-namespace"),
            &mut report,
        )
        .expect("flatten on Responses");
        match &tools[0] {
            PreparedTool::Function { name, .. } => assert_eq!(name, "crm.lookup"),
            other => panic!("OpenRouter-style flatten must not emit namespace, got {other:?}"),
        }
    }

    #[test]
    fn unknown_type_errors_under_hard_error() {
        let ir = IrRequest {
            model: "m".into(),
            items: Vec::new(),
            tools: vec![IrTool::Unknown {
                type_name: "weird".into(),
                raw: json!({"type": "weird"}),
            }],
            sampling: IrSampling::default(),
        };
        let mut report = LossReport::default();
        let err = prepare_tools(Wire::Responses, &ir, &profile("hard-error"), &mut report)
            .expect_err("unknown type");
        match err {
            MapError::HardError { detail, .. } => {
                assert!(detail.contains("weird"), "detail={detail}");
                assert!(
                    detail.contains("tool_type_policy"),
                    "must name tool_type_policy, got {detail}"
                );
                assert!(
                    detail.contains("passthrough")
                        && detail.contains("flatten-namespace")
                        && detail.contains("hard-error"),
                    "must list tool_type_policy values, got {detail}"
                );
            }
            other => panic!("expected HardError, got {other}"),
        }
    }

    #[test]
    fn hosted_tool_without_slot_names_wire() {
        let ir = IrRequest {
            model: "m".into(),
            items: Vec::new(),
            tools: vec![IrTool::Hosted {
                kind: "web_search".into(),
                raw: json!({"type": "web_search"}),
            }],
            sampling: IrSampling::default(),
        };
        let mut report = LossReport::default();
        let err = prepare_tools(
            Wire::ChatCompletions,
            &ir,
            &profile("hard-error"),
            &mut report,
        )
        .expect_err("hosted tool has no slot");
        match err {
            MapError::HardError { detail, .. } => {
                assert!(detail.contains("web_search"), "detail={detail}");
                assert!(detail.contains("chat-completions"), "detail={detail}");
            }
            other => panic!("expected HardError, got {other}"),
        }
    }

    #[test]
    fn unknown_type_with_name_stays_unknown() {
        let tool = decode_tool(&json!({
            "type": "weird",
            "name": "do_thing",
            "description": "A thing",
            "parameters": {"type": "object", "properties": {}}
        }));
        match &tool {
            IrTool::Unknown { type_name, raw } => {
                assert_eq!(type_name, "weird");
                assert_eq!(raw["name"], "do_thing");
            }
            other => panic!("must stay Unknown, not relabel as Function: {other:?}"),
        }

        let ir = IrRequest {
            model: "m".into(),
            items: Vec::new(),
            tools: vec![tool],
            sampling: IrSampling::default(),
        };
        let mut report = LossReport::default();
        let err = prepare_tools(Wire::Responses, &ir, &profile("hard-error"), &mut report)
            .expect_err("unknown type with name must hard-error");
        match err {
            MapError::HardError { detail, .. } => {
                assert!(
                    detail.contains("tool_type_policy"),
                    "must name tool_type_policy, got {detail}"
                );
            }
            other => panic!("expected HardError, got {other}"),
        }
        let mut report = LossReport::default();
        prepare_tools(
            Wire::Responses,
            &ir,
            &profile("flatten-namespace"),
            &mut report,
        )
        .expect_err("flatten-namespace still errors on unknown type");
        let mut report = LossReport::default();
        let out = prepare_tools(Wire::Responses, &ir, &profile("passthrough"), &mut report)
            .expect("passthrough");
        match &out[0] {
            PreparedTool::Raw(raw) => assert_eq!(raw["type"], "weird"),
            other => panic!("passthrough should forward raw, got {other:?}"),
        }
    }
}