zc2 0.0.46

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! `zc infer` / `zc chat` — consumer side of native model inference
//! (Task 6, phase 1).
//!
//! Talks to the broker's `POST {broker}/infer` route (Task 4):
//! request `{ "model": "zc://{uuid}", "messages": [...], "max_tokens": <int?> }`
//! response `{ "content", "usage": {"prompt_tokens","completion_tokens","total_tokens"},
//!             "provider", "charged" }`.
//!
//! Request building and response formatting are kept as pure functions so
//! they're unit-testable without a live broker; the HTTP call itself lives
//! in `main.rs` alongside the other subcommands' `ureq::Agent` usage.

use serde_json::{json, Value};

/// Parsed `zc infer` invocation.
#[derive(Debug, Clone, PartialEq)]
pub struct InferArgs {
    /// The `zc://` address as typed, validated but NOT yet resolved. A
    /// two-segment `zc://owner/name` needs a marketplace lookup, and arg
    /// parsing stays free of I/O -- `main` resolves it before dispatch.
    pub model: crate::model_uri::ModelAddress,
    /// `-m`/`--prompt <text>` — the user prompt.
    pub prompt: String,
    /// `--system <text>`, optional system message prepended to the conversation.
    pub system: Option<String>,
    /// `--max-tokens <n>`, optional generation cap forwarded to the broker.
    pub max_tokens: Option<u64>,
    /// `--broker <url>`, overrides the credential-resolved default broker.
    pub broker: Option<String>,
    /// `--file <path>`: transcribe this audio file with a speech model
    /// instead of prompting a chat model. Exclusive with `-m`; `prompt` is
    /// empty in this mode.
    pub file: Option<String>,
    /// `--language xx`, optional ISO-639 hint for transcription.
    pub language: Option<String>,
}

/// Parsed `zc chat` invocation. No prompt (read interactively from stdin).
#[derive(Debug, Clone, PartialEq)]
pub struct ChatArgs {
    /// See `InferArgs::model` -- unresolved address, resolved by `main`.
    pub model: crate::model_uri::ModelAddress,
    pub system: Option<String>,
    pub broker: Option<String>,
}

/// Parse `zc infer <args...>` (the slice after `infer` itself). Expects
/// exactly one bare `zc://{uuid}`/`{uuid}` model address, plus `-m`/`--prompt`,
/// `--max-tokens`, `--system`, `--broker`.
pub fn parse_infer_args(args: &[String]) -> Result<InferArgs, String> {
    let mut model: Option<crate::model_uri::ModelAddress> = None;
    let mut prompt: Option<String> = None;
    let mut system: Option<String> = None;
    let mut max_tokens: Option<u64> = None;
    let mut broker: Option<String> = None;
    let mut file: Option<String> = None;
    let mut language: Option<String> = None;

    let mut it = args.iter().peekable();
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--file" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--file requires a value".to_string())?;
                file = Some(v.clone());
            }
            "--language" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--language requires a value".to_string())?;
                if !is_valid_language(v) {
                    return Err(format!(
                        "invalid --language '{v}': expected a 2-3 letter lowercase code such as 'en' or 'sn'"
                    ));
                }
                language = Some(v.clone());
            }
            "-m" | "--prompt" => {
                let v = it.next().ok_or_else(|| format!("{arg} requires a value"))?;
                prompt = Some(v.clone());
            }
            "--max-tokens" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--max-tokens requires a value".to_string())?;
                max_tokens = Some(
                    v.parse::<u64>()
                        .map_err(|_| format!("invalid --max-tokens value '{v}'"))?,
                );
            }
            "--system" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--system requires a value".to_string())?;
                system = Some(v.clone());
            }
            "--broker" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--broker requires a value".to_string())?;
                broker = Some(v.clone());
            }
            other => {
                if model.is_some() {
                    return Err(format!("unexpected argument '{other}'"));
                }
                let addr = crate::model_uri::parse_model_address(other)
                    .ok_or_else(|| format!("not a model address: '{other}'"))?;
                model = Some(addr);
            }
        }
    }

    let model = model.ok_or_else(|| {
        "zc infer requires a zc://<owner>/<name> or zc://<uuid> argument".to_string()
    })?;
    if file.is_some() && prompt.is_some() {
        return Err("-m/--prompt and --file are mutually exclusive".to_string());
    }
    if file.is_none() && language.is_some() {
        return Err("--language only applies with --file".to_string());
    }
    let prompt = match (&file, prompt) {
        (Some(_), _) => String::new(),
        (None, Some(p)) => p,
        (None, None) => {
            return Err("zc infer requires either -m/--prompt <text> or --file <audio>".to_string())
        }
    };

    Ok(InferArgs {
        model,
        prompt,
        system,
        max_tokens,
        broker,
        file,
        language,
    })
}

/// Parse `zc chat <args...>` (the slice after `chat` itself). Expects
/// exactly one bare `zc://{uuid}`/`{uuid}` model address, plus `--system`,
/// `--broker`.
pub fn parse_chat_args(args: &[String]) -> Result<ChatArgs, String> {
    let mut model: Option<crate::model_uri::ModelAddress> = None;
    let mut system: Option<String> = None;
    let mut broker: Option<String> = None;

    let mut it = args.iter().peekable();
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "--system" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--system requires a value".to_string())?;
                system = Some(v.clone());
            }
            "--broker" => {
                let v = it
                    .next()
                    .ok_or_else(|| "--broker requires a value".to_string())?;
                broker = Some(v.clone());
            }
            other => {
                if model.is_some() {
                    return Err(format!("unexpected argument '{other}'"));
                }
                let addr = crate::model_uri::parse_model_address(other)
                    .ok_or_else(|| format!("not a model address: '{other}'"))?;
                model = Some(addr);
            }
        }
    }

    let model = model.ok_or_else(|| {
        "zc chat requires a zc://<owner>/<name> or zc://<uuid> argument".to_string()
    })?;

    Ok(ChatArgs {
        model,
        system,
        broker,
    })
}

/// Build the `messages` array: an optional system message followed by the
/// user's prompt.
pub fn build_messages(prompt: &str, system: Option<&str>) -> Vec<Value> {
    let mut messages = Vec::new();
    if let Some(sys) = system {
        messages.push(json!({"role": "system", "content": sys}));
    }
    messages.push(json!({"role": "user", "content": prompt}));
    messages
}

/// Build the `POST {broker}/infer` request body for a one-shot `zc infer`
/// call: `{model, messages, max_tokens?}`. `model_uuid` is the bare canonical
/// UUID (already validated); it's addressed as `zc://{uuid}` on the wire.
pub fn build_infer_body(
    model_uuid: &str,
    prompt: &str,
    system: Option<&str>,
    max_tokens: Option<u64>,
) -> Value {
    build_chat_body(model_uuid, &build_messages(prompt, system), max_tokens)
}

/// Build the `POST {broker}/infer` request body from an already-accumulated
/// message list (used by `zc chat`, which grows the conversation turn by
/// turn).
pub fn build_chat_body(model_uuid: &str, messages: &[Value], max_tokens: Option<u64>) -> Value {
    let mut body = json!({
        "model": format!("zc://{model_uuid}"),
        "messages": messages,
    });
    if let Some(mt) = max_tokens {
        body["max_tokens"] = json!(mt);
    }
    body
}

/// Render a successful `/infer` response body: the assistant content,
/// followed by a usage/cost summary line.
pub fn format_infer_output(resp: &Value) -> String {
    let content = resp.get("content").and_then(|v| v.as_str()).unwrap_or("");
    let total_tokens = resp
        .get("usage")
        .and_then(|u| u.get("total_tokens"))
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let charged = resp.get("charged").and_then(|v| v.as_f64()).unwrap_or(0.0);
    let provider = resp
        .get("provider")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");

    format!("{content}\n\n{total_tokens} tokens -> ¥{charged}  (provider: {provider})")
}

/// The receipt lines `zc infer` prints under the reply, in the order a
/// reader wants them: who served it, what it cost, what it left. Built from
/// the `X-Zakuro-*` response headers, matched without regard to case because
/// HTTP header names have none. `None` when the broker sent no receipt — a
/// broker older than the headers — so the caller can fall back to the body.
pub fn format_infer_receipt(headers: &[(String, String)]) -> Option<String> {
    let get = |name: &str| {
        headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.trim().to_string())
    };
    let cost = get("X-Zakuro-Cost")?;
    let mut lines = Vec::new();
    if let Some(w) = get("X-Zakuro-Worker").filter(|w| !w.is_empty()) {
        lines.push(("X-Zakuro-Worker", w));
    }
    let cost = match cost.parse::<f64>() {
        Ok(c) => format!("¥{}", trim_decimal(c, 6)),
        Err(_) => cost,
    };
    lines.push(("X-Zakuro-Cost", cost));
    if let Some(left) = get("X-Zakuro-Balance") {
        let left = match left.parse::<f64>() {
            Ok(b) => crate::broker::balance::yen(b),
            Err(_) => left,
        };
        lines.push(("X-Zakuro-Balance", left));
    }
    let w = lines.iter().map(|(k, _)| k.len()).max().unwrap_or(0) + 2;
    Some(
        lines
            .iter()
            .map(|(k, v)| format!("→ {k:<w$}{v}"))
            .collect::<Vec<_>>()
            .join("\n"),
    )
}

/// `c` to at most `places` decimals, without the trailing zeros: `0.0124`,
/// not `0.012400`; `0`, not `0.000000`.
fn trim_decimal(c: f64, places: usize) -> String {
    let s = format!("{c:.places$}");
    match s.contains('.') {
        true => s.trim_end_matches('0').trim_end_matches('.').to_string(),
        false => s,
    }
}

/// What `zc infer` prints: the reply, then the receipt from the response
/// headers, or the body's own usage line when the broker sent none.
pub fn format_infer_reply(resp: &Value, headers: &[(String, String)]) -> String {
    match format_infer_receipt(headers) {
        Some(receipt) => {
            let content = resp.get("content").and_then(|v| v.as_str()).unwrap_or("");
            format!("{content}\n\n{receipt}")
        }
        None => format_infer_output(resp),
    }
}

/// Extract a broker error message from a non-2xx `/infer` response body,
/// e.g. `{"error": "..."}`. Falls back to the raw body if it isn't the
/// expected shape.
pub fn format_infer_error(body: &str) -> String {
    match serde_json::from_str::<Value>(body) {
        Ok(v) => v
            .get("error")
            .and_then(|e| e.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| body.to_string()),
        Err(_) => body.to_string(),
    }
}

/// Default `max_tokens` for the hub route, which requires one.
pub const HUB_DEFAULT_MAX_TOKENS: u64 = 256;

/// Whether a failed broker call should be retried on the hub runtime: only
/// when the broker said no worker serves the model, and the user did not pin
/// a broker with `--broker` (an explicit broker means "use this one").
pub fn should_fall_back_to_hub(broker_explicit: bool, broker_error: &str) -> bool {
    !broker_explicit && format_infer_error(broker_error).contains("no provider serving")
}

/// Body for `POST {api}/api/models/{uuid}/infer`: `{messages, max_tokens}`.
/// The hub requires `max_tokens`, so it defaults when the user gave none.
pub fn build_hub_body(messages: &[Value], max_tokens: Option<u64>) -> Value {
    json!({
        "messages": messages,
        "max_tokens": max_tokens.unwrap_or(HUB_DEFAULT_MAX_TOKENS),
    })
}

/// Parse a hub `/infer` reply into the broker reply shape (so the existing
/// formatters apply) plus synthetic receipt headers naming the provider `hub`.
/// The hub sends `charged` and `balance` as decimal strings.
pub fn parse_hub_reply(body: &str) -> Result<(Value, Vec<(String, String)>), String> {
    let v: Value = serde_json::from_str(body)
        .map_err(|e| format!("parsing hub response: {e} (body: {body})"))?;
    let content = v
        .get("content")
        .and_then(|c| c.as_str())
        .ok_or_else(|| format!("hub response has no content (body: {body})"))?;
    let decimal = |key: &str| match v.get(key) {
        Some(Value::String(s)) => Some(s.trim().to_string()),
        Some(Value::Number(n)) => Some(n.to_string()),
        _ => None,
    };
    let charged = decimal("charged");
    let mut resp = json!({
        "content": content,
        "usage": v.get("usage").cloned().unwrap_or_else(|| json!({})),
        "provider": "hub",
    });
    if let Some(c) = charged.as_deref().and_then(|c| c.parse::<f64>().ok()) {
        resp["charged"] = json!(c);
    }
    let mut headers = vec![("X-Zakuro-Worker".to_string(), "hub".to_string())];
    if let Some(c) = charged {
        headers.push(("X-Zakuro-Cost".to_string(), c));
    }
    if let Some(b) = decimal("balance") {
        headers.push(("X-Zakuro-Balance".to_string(), b));
    }
    Ok((resp, headers))
}

/// Hub error text, verbatim from `{"detail": {"errors": [...]}}`, tagged
/// `(hub)` so it is not mistaken for a broker error. Falls back to a string
/// `detail`, then to the raw body.
pub fn format_hub_error(body: &str) -> String {
    let msg = serde_json::from_str::<Value>(body)
        .ok()
        .and_then(|v| {
            let d = v.get("detail")?;
            if let Some(errs) = d.get("errors").and_then(|e| e.as_array()) {
                let joined: Vec<&str> = errs.iter().filter_map(|e| e.as_str()).collect();
                if !joined.is_empty() {
                    return Some(joined.join("; "));
                }
            }
            d.as_str().map(|s| s.to_string())
        })
        .unwrap_or_else(|| body.trim().to_string());
    format!("{msg} (hub)")
}

/// `^[a-z]{2,3}$`, the hub's `language` field.
pub fn is_valid_language(s: &str) -> bool {
    (2..=3).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_lowercase())
}

/// Largest audio file `zc infer --file` will read into memory. The hub caps
/// duration, not size, so this only guards against pointing the CLI at
/// something absurd (a disk image) before any bytes are buffered.
pub const MAX_AUDIO_BYTES: u64 = 512 * 1024 * 1024;

/// MIME type for the `file` part, from the extension; unknown extensions are
/// sent as `application/octet-stream` and left for the hub to sniff.
pub fn audio_content_type(path: &str) -> &'static str {
    let ext = path.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
    match ext.as_str() {
        "wav" | "wave" => "audio/wav",
        "mp3" => "audio/mpeg",
        "flac" => "audio/flac",
        "m4a" => "audio/mp4",
        "ogg" | "oga" | "opus" => "audio/ogg",
        "webm" => "audio/webm",
        _ => "application/octet-stream",
    }
}

/// Build a `multipart/form-data` body with a `file` part and an optional
/// `language` part. Returns `(content_type_header_value, body)`.
pub fn build_multipart(
    boundary: &str,
    filename: &str,
    content_type: &str,
    audio: &[u8],
    language: Option<&str>,
) -> (String, Vec<u8>) {
    // Header-injection guard: a filename may not carry quotes or line breaks.
    let safe: String = filename
        .chars()
        .map(|c| {
            if matches!(c, '"' | '\r' | '\n' | '\\') {
                '_'
            } else {
                c
            }
        })
        .collect();
    let mut body = Vec::with_capacity(audio.len() + 512);
    if let Some(l) = language {
        body.extend_from_slice(
            format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\n{l}\r\n"
            )
            .as_bytes(),
        );
    }
    body.extend_from_slice(
        format!(
            "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{safe}\"\r\nContent-Type: {content_type}\r\n\r\n"
        )
        .as_bytes(),
    );
    body.extend_from_slice(audio);
    body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
    (format!("multipart/form-data; boundary={boundary}"), body)
}

/// A hub `/transcribe` reply.
#[derive(Debug, Clone, PartialEq)]
pub struct TranscribeReply {
    pub text: String,
    pub language: Option<String>,
    pub duration_s: Option<f64>,
    pub billed_seconds: Option<f64>,
    pub truncated: bool,
    pub charged: Option<String>,
}

/// Parse the hub's transcribe reply. `charged` is a decimal string but a
/// bare number is tolerated.
pub fn parse_transcribe_reply(body: &str) -> Result<TranscribeReply, String> {
    let v: Value = serde_json::from_str(body)
        .map_err(|e| format!("parsing hub transcribe reply: {e} (body: {body}) (hub)"))?;
    let text = v
        .get("text")
        .and_then(|t| t.as_str())
        .ok_or_else(|| format!("hub transcribe reply has no text (body: {body}) (hub)"))?
        .to_string();
    Ok(TranscribeReply {
        text,
        language: v.get("language").and_then(|x| x.as_str()).map(String::from),
        duration_s: v.get("duration_s").and_then(|x| x.as_f64()),
        billed_seconds: v.get("billed_seconds").and_then(|x| x.as_f64()),
        truncated: v
            .get("truncated")
            .and_then(|x| x.as_bool())
            .unwrap_or(false),
        charged: match v.get("charged") {
            Some(Value::String(s)) => Some(s.trim().to_string()),
            Some(Value::Number(n)) => Some(n.to_string()),
            _ => None,
        },
    })
}

/// Transcript, then a receipt in the style of the chat receipt, then a
/// warning when the hub cut the audio at its duration cap.
pub fn format_transcribe_reply(r: &TranscribeReply) -> String {
    let mut lines: Vec<(&str, String)> = Vec::new();
    if let Some(l) = &r.language {
        lines.push(("Language", l.clone()));
    }
    if let Some(d) = r.duration_s {
        lines.push(("Duration", format!("{} s", trim_decimal(d, 2))));
    }
    if let Some(b) = r.billed_seconds {
        lines.push(("Billed", format!("{} s", trim_decimal(b, 2))));
    }
    if let Some(c) = &r.charged {
        let cost = match c.parse::<f64>() {
            Ok(f) => trim_decimal(f, 6),
            Err(_) => c.clone(),
        };
        lines.push(("Cost", format!("¥{cost}")));
    }
    let w = lines.iter().map(|(k, _)| k.len()).max().unwrap_or(0) + 2;
    let mut out = r.text.trim().to_string();
    if !lines.is_empty() {
        out.push_str("\n\n");
        out.push_str(
            &lines
                .iter()
                .map(|(k, v)| format!("→ {k:<w$}{v}"))
                .collect::<Vec<_>>()
                .join("\n"),
        );
    }
    if r.truncated {
        out.push_str(
            "\n\nWarning: the audio exceeds the 10-minute limit; only the first 10 minutes were transcribed.",
        );
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model_uri::ModelAddress;

    const UUID: &str = "ae5f3db4-437a-40d1-93ec-c8258315d69a";

    #[test]
    fn parses_minimal_infer_args() {
        let args = vec![
            format!("zc://{UUID}"),
            "-m".to_string(),
            "hello".to_string(),
        ];
        let parsed = parse_infer_args(&args).unwrap();
        assert_eq!(parsed.model, ModelAddress::Uuid(UUID.to_string()));
        assert_eq!(parsed.prompt, "hello");
        assert_eq!(parsed.system, None);
        assert_eq!(parsed.max_tokens, None);
        assert_eq!(parsed.broker, None);
    }

    #[test]
    fn parses_full_infer_args() {
        let args = vec![
            format!("zc://model-{UUID}"),
            "--prompt".to_string(),
            "hi there".to_string(),
            "--max-tokens".to_string(),
            "256".to_string(),
            "--system".to_string(),
            "be terse".to_string(),
            "--broker".to_string(),
            "http://localhost:9000".to_string(),
        ];
        let parsed = parse_infer_args(&args).unwrap();
        assert_eq!(parsed.model, ModelAddress::Uuid(UUID.to_string()));
        assert_eq!(parsed.prompt, "hi there");
        assert_eq!(parsed.system.as_deref(), Some("be terse"));
        assert_eq!(parsed.max_tokens, Some(256));
        assert_eq!(parsed.broker.as_deref(), Some("http://localhost:9000"));
    }

    #[test]
    fn rejects_invalid_model_uri() {
        let args = vec![
            "zc://node-abc123".to_string(),
            "-m".to_string(),
            "hi".to_string(),
        ];
        let err = parse_infer_args(&args).unwrap_err();
        assert!(err.contains("not a model address"));
    }

    #[test]
    fn rejects_missing_prompt() {
        let args = vec![format!("zc://{UUID}")];
        let err = parse_infer_args(&args).unwrap_err();
        assert!(err.contains("--prompt"));
    }

    #[test]
    fn rejects_missing_model() {
        let args = vec!["-m".to_string(), "hi".to_string()];
        let err = parse_infer_args(&args).unwrap_err();
        // Names both accepted forms: someone who typed neither needs to be
        // told the readable one exists, not just the uuid.
        assert!(err.contains("<owner>/<name>"), "{err}");
        assert!(err.contains("zc://"), "{err}");
    }

    #[test]
    fn parses_chat_args() {
        let args = vec![
            format!("zc://{UUID}"),
            "--system".to_string(),
            "be terse".to_string(),
        ];
        let parsed = parse_chat_args(&args).unwrap();
        assert_eq!(parsed.model, ModelAddress::Uuid(UUID.to_string()));
        assert_eq!(parsed.system.as_deref(), Some("be terse"));
        assert_eq!(parsed.broker, None);
    }

    #[test]
    fn build_infer_body_without_system_or_max_tokens() {
        let body = build_infer_body(UUID, "hello", None, None);
        assert_eq!(body["model"], json!(format!("zc://{UUID}")));
        assert_eq!(
            body["messages"],
            json!([{"role": "user", "content": "hello"}])
        );
        assert!(body.get("max_tokens").is_none());
    }

    #[test]
    fn build_infer_body_with_system_and_max_tokens() {
        let body = build_infer_body(UUID, "hello", Some("be terse"), Some(64));
        assert_eq!(
            body["messages"],
            json!([
                {"role": "system", "content": "be terse"},
                {"role": "user", "content": "hello"}
            ])
        );
        assert_eq!(body["max_tokens"], json!(64));
    }

    #[test]
    fn format_infer_output_renders_content_and_usage() {
        let resp = json!({
            "content": "Paris is the capital of France.",
            "usage": {"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18},
            "provider": "specialized",
            "charged": 0.0042
        });
        let out = format_infer_output(&resp);
        assert!(out.starts_with("Paris is the capital of France."));
        assert!(out.contains("18 tokens -> ¥0.0042  (provider: specialized)"));
    }

    #[test]
    fn format_infer_output_defaults_on_missing_fields() {
        let resp = json!({});
        let out = format_infer_output(&resp);
        assert!(out.contains("0 tokens -> ¥0  (provider: unknown)"));
    }

    fn hdr(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    /// The receipt reads the way zakuro-ai.com shows it: worker, cost in
    /// yen, balance left, the values in one column.
    #[test]
    fn the_receipt_prints_worker_cost_and_balance_in_one_column() {
        let headers = hdr(&[
            ("x-zakuro-request-id", "r1"),
            ("x-zakuro-worker", "gpu-04"),
            ("x-zakuro-cost", "0.012400"),
            ("x-zakuro-balance", "98.674900"),
        ]);
        assert_eq!(
            format_infer_receipt(&headers).unwrap(),
            "→ X-Zakuro-Worker   gpu-04\n\
             → X-Zakuro-Cost     ¥0.0124\n\
             → X-Zakuro-Balance  ¥98.6749"
        );
    }

    #[test]
    fn a_free_call_costs_zero_not_six_zeros() {
        let headers = hdr(&[("X-Zakuro-Worker", "w"), ("X-Zakuro-Cost", "0.000000")]);
        let r = format_infer_receipt(&headers).unwrap();
        assert!(r.ends_with(" ¥0"), "{r}");
        assert!(!r.contains("Balance"), "no balance, no line: {r}");
    }

    /// A broker that predates the receipt still prints something useful.
    #[test]
    fn without_receipt_headers_the_reply_falls_back_to_the_body() {
        let resp =
            json!({"content": "hi", "usage": {"total_tokens": 3}, "provider": "p", "charged": 0.0});
        let out = format_infer_reply(&resp, &[]);
        assert!(out.contains("3 tokens -> ¥0  (provider: p)"), "{out}");
        let out = format_infer_reply(&resp, &hdr(&[("X-Zakuro-Cost", "0.5")]));
        assert!(out.starts_with("hi\n\n→ X-Zakuro-Cost"), "{out}");
    }

    #[test]
    fn format_infer_error_extracts_error_field() {
        let body = r#"{"error": "model not found"}"#;
        assert_eq!(format_infer_error(body), "model not found");
    }

    #[test]
    fn format_infer_error_falls_back_to_raw_body() {
        let body = "not json";
        assert_eq!(format_infer_error(body), "not json");
    }

    #[test]
    fn hub_body_defaults_max_tokens() {
        let msgs = build_messages("hi", Some("sys"));
        let b = build_hub_body(&msgs, None);
        assert_eq!(b["max_tokens"], 256);
        assert_eq!(b["messages"].as_array().unwrap().len(), 2);
        assert!(b.get("model").is_none());
        assert_eq!(build_hub_body(&msgs, Some(32))["max_tokens"], 32);
    }

    #[test]
    fn hub_reply_parses_string_decimals() {
        let body = r#"{"content":"hello","usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5},"charged":"0.001200","balance":"9.5"}"#;
        let (resp, headers) = parse_hub_reply(body).unwrap();
        assert_eq!(resp["content"], "hello");
        assert_eq!(resp["provider"], "hub");
        let out = format_infer_reply(&resp, &headers);
        assert!(out.starts_with("hello\n\n"));
        assert!(out.contains("X-Zakuro-Worker") && out.contains("hub"));
        assert!(out.contains("¥0.0012"));
        assert!(out.contains("¥9.5"));
        assert!(format_infer_output(&resp).contains("5 tokens -> ¥0.0012  (provider: hub)"));
    }

    #[test]
    fn hub_reply_rejects_garbage() {
        assert!(parse_hub_reply("nope").is_err());
        assert!(parse_hub_reply("{}").is_err());
    }

    #[test]
    fn hub_errors_are_verbatim() {
        assert_eq!(
            format_hub_error(r#"{"detail":{"errors":["no committed runner for this model"]}}"#),
            "no committed runner for this model (hub)"
        );
        assert_eq!(
            format_hub_error(r#"{"detail":{"errors":["a","b"]}}"#),
            "a; b (hub)"
        );
        assert_eq!(
            format_hub_error(r#"{"detail":"Not found"}"#),
            "Not found (hub)"
        );
        assert_eq!(format_hub_error("boom"), "boom (hub)");
    }

    #[test]
    fn falls_back_only_on_no_provider_without_explicit_broker() {
        let np = r#"{"error":"no provider serving zc://abc"}"#;
        assert!(should_fall_back_to_hub(false, np));
        assert!(!should_fall_back_to_hub(true, np));
        assert!(!should_fall_back_to_hub(
            false,
            r#"{"error":"insufficient balance"}"#
        ));
        assert!(!should_fall_back_to_hub(
            false,
            "broker request failed: timeout"
        ));
    }

    fn sv(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn file_and_prompt_are_exclusive() {
        let a = sv(&[&format!("zc://{UUID}"), "-m", "hi", "--file", "a.wav"]);
        assert!(parse_infer_args(&a)
            .unwrap_err()
            .contains("mutually exclusive"));
        let a = sv(&[&format!("zc://{UUID}"), "--file", "a.wav", "-m", "hi"]);
        assert!(parse_infer_args(&a)
            .unwrap_err()
            .contains("mutually exclusive"));
    }

    #[test]
    fn neither_prompt_nor_file_is_a_usage_error() {
        let a = sv(&[&format!("zc://{UUID}")]);
        assert!(parse_infer_args(&a).unwrap_err().contains("--file"));
    }

    #[test]
    fn parses_file_and_language() {
        let a = sv(&[
            &format!("zc://{UUID}"),
            "--file",
            "a.wav",
            "--language",
            "sn",
        ]);
        let p = parse_infer_args(&a).unwrap();
        assert_eq!(p.file.as_deref(), Some("a.wav"));
        assert_eq!(p.language.as_deref(), Some("sn"));
        assert_eq!(p.prompt, "");
    }

    #[test]
    fn validates_language() {
        for bad in ["S", "english", "EN", "e1", "", "sn-"] {
            let a = sv(&[
                &format!("zc://{UUID}"),
                "--file",
                "a.wav",
                "--language",
                bad,
            ]);
            assert!(parse_infer_args(&a).is_err(), "{bad} should be rejected");
        }
        for ok in ["en", "sn", "lozi".get(..3).unwrap()] {
            assert!(is_valid_language(ok));
        }
        let a = sv(&[&format!("zc://{UUID}"), "-m", "x", "--language", "en"]);
        assert!(parse_infer_args(&a).unwrap_err().contains("--file"));
    }

    #[test]
    fn content_type_from_extension() {
        assert_eq!(audio_content_type("a.WAV"), "audio/wav");
        assert_eq!(audio_content_type("/x/y.mp3"), "audio/mpeg");
        assert_eq!(audio_content_type("a.flac"), "audio/flac");
        assert_eq!(audio_content_type("a.m4a"), "audio/mp4");
        assert_eq!(audio_content_type("a.ogg"), "audio/ogg");
        assert_eq!(audio_content_type("a.webm"), "audio/webm");
        assert_eq!(audio_content_type("a.bin"), "application/octet-stream");
        assert_eq!(audio_content_type("noext"), "application/octet-stream");
    }

    #[test]
    fn multipart_body_is_well_formed() {
        let (ct, body) =
            build_multipart("BND", "a\"b.wav", "audio/wav", &[0, 1, 2, 255], Some("sn"));
        assert_eq!(ct, "multipart/form-data; boundary=BND");
        let mut want = Vec::new();
        want.extend_from_slice(
            b"--BND\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\nsn\r\n",
        );
        want.extend_from_slice(b"--BND\r\nContent-Disposition: form-data; name=\"file\"; filename=\"a_b.wav\"\r\nContent-Type: audio/wav\r\n\r\n");
        want.extend_from_slice(&[0, 1, 2, 255]);
        want.extend_from_slice(b"\r\n--BND--\r\n");
        assert_eq!(body, want);
        let (_, no_lang) = build_multipart("BND", "a.wav", "audio/wav", b"x", None);
        assert!(!String::from_utf8_lossy(&no_lang).contains("language"));
    }

    #[test]
    fn parses_transcribe_reply() {
        let r = parse_transcribe_reply(
            r#"{"text":" hello ","language":"en","duration_s":12.5,"billed_seconds":13,"truncated":true,"charged":"0.0130"}"#,
        )
        .unwrap();
        assert_eq!(r.charged.as_deref(), Some("0.0130"));
        assert!(r.truncated);
        assert_eq!(r.billed_seconds, Some(13.0));
        let out = format_transcribe_reply(&r);
        assert!(out.starts_with("hello\n\n→ Language"));
        assert!(out.contains("Duration  12.5 s"));
        assert!(out.contains("Cost      ¥0.013"));
        assert!(out.contains("Warning: the audio exceeds the 10-minute limit"));
        let r = parse_transcribe_reply(r#"{"text":"x"}"#).unwrap();
        assert!(!r.truncated);
        assert!(!format_transcribe_reply(&r).contains("Warning"));
        assert!(parse_transcribe_reply("{}").is_err());
        assert!(parse_transcribe_reply("nope").is_err());
    }

    #[test]
    fn maps_transcribe_errors_verbatim() {
        let e = format_hub_error(
            r#"{"detail":{"errors":["This model transcribes audio. Use /transcribe."]}}"#,
        );
        assert_eq!(e, "This model transcribes audio. Use /transcribe. (hub)");
        let e = format_hub_error(r#"{"detail":{"errors":["insufficient balance"]}}"#);
        assert_eq!(e, "insufficient balance (hub)");
    }
}