weirdnet-agent 0.5.8

Weirdnet agent runtime: a model-agnostic agent loop with streaming events and cancellation, tool sources and registry, tiered approval policy with per-site grants and standing allows, research budgets, traces with citation checks, and remote inference (infer/1 and infer/2, catalog, pool with failover and resume).
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
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//! `/weirdnet-agent/infer/2`: remote inference with a queue, jobs, resume and richer frames.
//!
//! ```text
//! asking node                               serving node
//!   Infer(Request) | Embed(EmbedRequest) | Transcribe(TranscribeRequest) ->
//!                                           <- Queued { position } ...   (while waiting for a slot)
//!                                           <- Accepted { model, attempt, resume }
//!                                           <- Delta { offset, text } | Reasoning { offset, text }
//!                                           <- Meta { meta }             (early_meta askers)
//!                                           <- ToolCall { index, call } | Usage | Embedding | Transcript ...
//!   Cancel { id } ->                        (any time)
//!                                           <- Done { finish } | Failed { error } | Cancelled
//! ```
//!
//! Messages are CBOR. Infer/1 stays JSON and is served beside this protocol; the two can't
//! share a stream id because a `/1` server would ignore `assistant_prefix` (and repeat the
//! prefix) and a `/1` client fails on `Queued`.
//!
//! - **Queue:** requests wait in the node's [`Admission`] priority queue. Every change of place,
//!   and every [`QUEUE_KEEPALIVE`] without one, sends `Queued`; each resets the asker's accept
//!   timeout, so a queued request is not mistaken for a dead node.
//! - **Offsets:** every `Delta` carries the number of characters (Unicode scalar values) of the
//!   answer before it, and every `Reasoning` the same for the reasoning text. A receiver appends
//!   a frame only where it continues its buffer, so a resumed stream never repeats text.
//! - **Resume:** a request may carry the `assistant_prefix` already shown. A server whose
//!   backend honours it ([`InferBackend::resumes`]) says `resume: true` and streams only what
//!   comes after it, starting at offset = prefix length. Others say `resume: false` and start
//!   over at 0; askers that need a resume move on.
//! - **Continue:** the same prefix continues an answer the user stopped or that was cut off
//!   (assistant prefill; [`Request::continuing`] makes one from a trailing assistant message).
//!   The wire format is unchanged, so any 0.4 server whose backend resumes can serve it.
//! - **Tool calls** are sent whole, never half-built.
//! - **Raw prompts** ([`Input::Prompt`]) are for completions: the model continues the text, with
//!   no chat template and no tools.
//! - **Early metadata:** an asker that sets [`Request::early_meta`] may get a `Meta` frame before
//!   the answer (a cache hit, say); `Done` carries the same metadata for everyone.
//! - **Raw mode** is for inference node → model node calls: assembled messages only, no context
//!   lookups, caches or stand-ins.
//! - **Answer cache:** [`Request::cache`] ([`CacheMode`]) lets an asker skip a node's answer
//!   cache for one request without raw mode: `bypass` neither reads nor stores, `refresh` skips
//!   the read and stores the fresh answer. The field is left off the wire when it is `use`, so
//!   older nodes read the request as before; they don't know the field and may still answer from
//!   their cache ([`Meta::cache_hit`] says so).
//! - **Embeddings:** one `Embedding` frame per input, the vector as a CBOR byte string of
//!   little-endian `f32`.
//! - **Transcription** (since 0.5.8): a [`TranscribeRequest`] carries one audio clip as a CBOR
//!   byte string with its format (`wav`, `mp3`, ... as in an `input_audio` part), optional
//!   language and prompt hints and whether timed segments are wanted. It queues like any request;
//!   the node answers `Accepted`, `Working` every [`QUEUE_KEEPALIVE`] while the backend runs, one
//!   `Transcript` frame ([`Transcript`]: the text, the language,
//!   the audio's length and timed [`Segment`]s when the backend gives them), then `Done` with
//!   usage and timings. The host serves it through [`InferHost::open_transcribe`] and a
//!   [`TranscribeBackend`]; an inference node routes it with
//!   [`Catalog::route_transcribe`](crate::remote::catalog::Catalog::route_transcribe). Nodes
//!   before 0.5.8 can't read the request and close the stream; the pool reports that as
//!   `Unsupported` and tries the next node. The whole request must fit in one stream message
//!   (32 MiB on Weirdnet), so long soundtracks are sent in pieces.

use std::pin::pin;
use std::sync::Arc;
use std::time::Duration;

use tokio::time::Instant;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::mpsc;

use super::queue::{Admission, Turn};
use super::{InferHost, model_error};
use crate::cancel::CancelToken;
use crate::model::{DeltaSink, Message, Modalities, ModelBackend, Role, ToolCall};
use crate::remote::{Caller, Channel, RemoteError, bytes, request_id};
use crate::session::AgentEvent;
use crate::tool::ToolSpec;

/// Stream protocol id.
pub const PROTOCOL: &str = "/weirdnet-agent/infer/2";

/// How often a waiting request hears its place again when it has not changed.
pub const QUEUE_KEEPALIVE: Duration = Duration::from_secs(3);

/// Scheduling class: `interactive` before `batch` before `background` (prefix warming,
/// re-placement). Classes never preempt a running request.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Priority {
    #[default]
    Interactive,
    Batch,
    Background,
}

/// Whether a node's answer cache may serve or keep this request's answer.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CacheMode {
    /// Read and store as the cache sees fit.
    #[default]
    Use,
    /// Neither read nor store: always run the model (evals, fresh weights).
    Bypass,
    /// Skip the read, run the model and store the fresh answer over the old one.
    Refresh,
}

impl CacheMode {
    pub fn is_use(&self) -> bool {
        *self == CacheMode::Use
    }

    /// A stored answer may stand in for the model.
    pub fn may_read(&self) -> bool {
        *self == CacheMode::Use
    }

    /// The finished answer may be kept.
    pub fn may_store(&self) -> bool {
        matches!(self, CacheMode::Use | CacheMode::Refresh)
    }
}

/// A conversation kept by the inference node (synced context), instead of inline messages.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ContextRef {
    pub conversation: String,
    /// The conversation head the answer follows; `None`: the latest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head: Option<String>,
}

impl ContextRef {
    pub fn new(conversation: impl Into<String>, head: Option<String>) -> Self {
        Self { conversation: conversation.into(), head }
    }
}

/// What the model answers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Input {
    /// Fully assembled messages.
    Messages(Vec<Message>),
    /// A conversation the serving node holds.
    Context(ContextRef),
    /// A raw text prompt the model continues (OpenAI `/v1/completions`); no chat template,
    /// no tools. Servers older than 0.4.1 can't read it and close the stream.
    Prompt(String),
}

impl Default for Input {
    fn default() -> Self {
        Input::Messages(Vec::new())
    }
}

/// The part of the answer already shown, for resume. Lengths are in characters.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Prefix {
    pub text: String,
    pub len: u64,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reasoning: String,
    #[serde(default)]
    pub reasoning_len: u64,
}

impl Prefix {
    pub fn new(text: impl Into<String>, reasoning: impl Into<String>) -> Self {
        let (text, reasoning) = (text.into(), reasoning.into());
        Self { len: chars(&text), reasoning_len: chars(&reasoning), text, reasoning }
    }

    /// The lengths match the texts.
    pub fn is_consistent(&self) -> bool {
        self.len == chars(&self.text) && self.reasoning_len == chars(&self.reasoning)
    }

    pub fn is_empty(&self) -> bool {
        self.text.is_empty() && self.reasoning.is_empty()
    }
}

/// Characters (Unicode scalar values) in `s`, the unit of offsets.
pub fn chars(s: &str) -> u64 {
    s.chars().count() as u64
}

/// Sampling settings; `None` leaves the backend's default.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Sampling {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub top_k: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_p: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stop: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub presence_penalty: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frequency_penalty: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repeat_penalty: Option<f32>,
}

/// The shape of the answer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseFormat {
    Text,
    /// Any JSON object.
    Json,
    /// JSON matching a schema.
    JsonSchema {
        name: String,
        schema: Value,
        #[serde(default)]
        strict: bool,
    },
}

/// One model turn to run on an infer/2 node.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Request {
    /// This attempt's id on the stream.
    pub id: String,
    /// Stable across attempts and nodes (the idempotency key of a job).
    pub job_id: String,
    /// 0 for the first try, then one more per retry or resume.
    #[serde(default)]
    pub attempt: u32,
    /// The model wanted, by the serving app's id (`None`: the node's default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default)]
    pub priority: Priority,
    pub input: Input,
    /// Text already shown, to continue from (see [`Prefix`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assistant_prefix: Option<Prefix>,
    #[serde(default)]
    pub sampling: Sampling,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response_format: Option<ResponseFormat>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tools: Vec<ToolSpec>,
    /// Inference node → model node: assembled messages only, no context lookups, caches or
    /// stand-ins.
    #[serde(default)]
    pub raw: bool,
    /// Wait for the requested model to load rather than take a stand-in.
    #[serde(default)]
    pub wait_for_model: bool,
    /// The certificate the asker presents (for Weirdnet a CBOR `NodeCert`), checked by the host
    /// against the transport peer.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
    pub cert: Option<Vec<u8>>,
    /// The asker reads [`ServerFrame::Meta`] (0.4.1 and later), so the server may send response
    /// metadata it knows before the answer, such as a cache hit. Servers that predate it ignore
    /// the flag; askers that don't set it never get the frame.
    #[serde(default, skip_serializing_if = "is_false")]
    pub early_meta: bool,
    /// Answer cache use (0.5.1 and later; see [`CacheMode`]). Not sent when `use`; nodes that
    /// predate it ignore it.
    #[serde(default, skip_serializing_if = "CacheMode::is_use")]
    pub cache: CacheMode,
    /// How strongly a LoRA adapter applies for this request, when `model` names one on an engine
    /// that scales adapters per request (llama.cpp). `None`: the adapter's configured scale.
    /// Ignored for base models. Not sent when `None`; nodes that predate it (0.5.1 and earlier)
    /// ignore it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub adapter_scale: Option<f32>,
}

fn is_false(b: &bool) -> bool {
    !*b
}

impl Request {
    /// A request over assembled messages, with a fresh id and job id.
    pub fn messages(messages: Vec<Message>) -> Self {
        Self::with_input(Input::Messages(messages))
    }

    /// A request over a conversation the serving node holds.
    pub fn context(context: ContextRef) -> Self {
        Self::with_input(Input::Context(context))
    }

    /// A request over a raw text prompt (see [`Input::Prompt`]).
    pub fn prompt(prompt: impl Into<String>) -> Self {
        Self::with_input(Input::Prompt(prompt.into()))
    }

    fn with_input(input: Input) -> Self {
        let id = request_id();
        Self { job_id: id.clone(), id, input, ..Default::default() }
    }

    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    pub fn with_priority(mut self, priority: Priority) -> Self {
        self.priority = priority;
        self
    }

    pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
        self.tools = tools;
        self
    }

    pub fn with_sampling(mut self, sampling: Sampling) -> Self {
        self.sampling = sampling;
        self
    }

    pub fn with_seed(mut self, seed: u64) -> Self {
        self.seed = Some(seed);
        self
    }

    pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
        self.response_format = Some(format);
        self
    }

    pub fn with_job_id(mut self, job_id: impl Into<String>) -> Self {
        self.job_id = job_id.into();
        self
    }

    pub fn with_prefix(mut self, prefix: Prefix) -> Self {
        self.assistant_prefix = Some(prefix);
        self
    }

    /// Continue the last assistant message: a trailing assistant message with no tool calls
    /// moves into `assistant_prefix` (prefill), so the model carries on from its text. Only
    /// nodes that say `resume: true` take such a request; others answer `Unsupported`. A
    /// request that ends any other way is returned unchanged.
    pub fn continuing(mut self) -> Self {
        if let Input::Messages(m) = &mut self.input
            && m.last().is_some_and(|last| last.role == Role::Assistant && last.tool_calls.is_empty() && last.content.as_text().is_some())
            && let Some(last) = m.pop()
        {
            self.assistant_prefix = Some(Prefix::new(last.content.into_text(), ""));
        }
        self
    }

    pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
        self.cert = Some(cert);
        self
    }

    /// How the serving node's answer cache treats this request (see [`CacheMode`]).
    pub fn with_cache(mut self, cache: CacheMode) -> Self {
        self.cache = cache;
        self
    }

    /// Applies the requested LoRA adapter at `scale` for this request (see
    /// [`Request::adapter_scale`]).
    pub fn with_adapter_scale(mut self, scale: f32) -> Self {
        self.adapter_scale = Some(scale);
        self
    }

    /// Wait for the requested model to load rather than take a stand-in.
    pub fn with_wait_for_model(mut self, wait: bool) -> Self {
        self.wait_for_model = wait;
        self
    }

    /// Raw mode (inference node → model node).
    pub fn raw(mut self) -> Self {
        self.raw = true;
        self
    }

    /// Inline messages, if the input is not a context reference.
    pub fn inline_messages(&self) -> Option<&[Message]> {
        match &self.input {
            Input::Messages(m) => Some(m),
            _ => None,
        }
    }

    /// What a model needs to read the inline messages: [`Modalities::TEXT`] unless some carry
    /// images or audio. Context references and raw prompts are text.
    pub fn needs(&self) -> Modalities {
        self.inline_messages().map(crate::model::needs).unwrap_or(Modalities::TEXT)
    }

    /// The raw prompt, if the input is one.
    pub fn raw_prompt(&self) -> Option<&str> {
        match &self.input {
            Input::Prompt(p) => Some(p),
            _ => None,
        }
    }

    /// The next attempt: same job, a new id, `attempt + 1`.
    pub fn next_attempt(&self) -> Self {
        Self { id: request_id(), attempt: self.attempt + 1, ..self.clone() }
    }
}

/// Embeddings for a list of inputs.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EmbedRequest {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    pub inputs: Vec<String>,
    #[serde(default)]
    pub priority: Priority,
    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
    pub cert: Option<Vec<u8>>,
}

impl EmbedRequest {
    pub fn new(inputs: Vec<String>) -> Self {
        Self { id: request_id(), inputs, ..Default::default() }
    }

    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    pub fn with_priority(mut self, priority: Priority) -> Self {
        self.priority = priority;
        self
    }
}

/// Speech to text for one audio clip (since 0.5.8). The audio travels as raw bytes (a CBOR byte
/// string), not base64.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TranscribeRequest {
    pub id: String,
    /// A speech-to-text model by the serving app's id (`None`: the node picks its transcriber).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// The encoded audio.
    #[serde(with = "bytes")]
    pub audio: Vec<u8>,
    /// Its format, as in an `input_audio` part: `wav`, `mp3`, `flac`, `ogg`, ...
    pub format: String,
    /// The spoken language (ISO 639-1, such as `en`), if the asker knows it; otherwise the model
    /// detects it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// Text to guide the transcript (names, terms, the previous piece's ending), as OpenAI's
    /// `prompt`. Backends that take none ignore it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    /// Ask for timed [`Segment`]s. Backends that can't time the text return none.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub timestamps: bool,
    #[serde(default)]
    pub priority: Priority,
    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
    pub cert: Option<Vec<u8>>,
}

impl TranscribeRequest {
    /// `audio` encoded as `format` (`wav`, `mp3`, ...).
    pub fn new(audio: Vec<u8>, format: impl Into<String>) -> Self {
        Self { id: request_id(), audio, format: format.into(), ..Default::default() }
    }

    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// The spoken language (ISO 639-1, such as `en`).
    pub fn with_language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// Text to guide the transcript.
    pub fn with_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = Some(prompt.into());
        self
    }

    /// Ask for timed segments.
    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
        self.timestamps = timestamps;
        self
    }

    pub fn with_priority(mut self, priority: Priority) -> Self {
        self.priority = priority;
        self
    }

    /// `BadRequest` unless there is audio and a format. The server checks this before the host
    /// opens a backend.
    pub fn check(&self) -> Result<(), RemoteError> {
        if self.audio.is_empty() {
            return Err(RemoteError::BadRequest { message: "a transcription request needs audio".into() });
        }
        if self.format.trim().is_empty() {
            return Err(RemoteError::BadRequest { message: "a transcription request needs the audio format (wav, mp3, ...)".into() });
        }
        Ok(())
    }
}

/// A transcript: the text, and what the backend knows about it.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Transcript {
    /// The whole text.
    pub text: String,
    /// The spoken language (ISO 639-1), when the backend says.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// The audio's length in milliseconds, when the backend says.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
    /// Timed pieces of the text, in order, when asked for and the backend can time them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub segments: Vec<Segment>,
}

impl Transcript {
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into(), ..Default::default() }
    }

    pub fn with_language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    pub fn with_duration_ms(mut self, duration_ms: u64) -> Self {
        self.duration_ms = Some(duration_ms);
        self
    }

    pub fn with_segments(mut self, segments: Vec<Segment>) -> Self {
        self.segments = segments;
        self
    }
}

/// A timed piece of a [`Transcript`], in milliseconds from the start of the audio.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Segment {
    pub start_ms: u64,
    pub end_ms: u64,
    pub text: String,
}

impl Segment {
    pub fn new(start_ms: u64, end_ms: u64, text: impl Into<String>) -> Self {
        Self { start_ms, end_ms, text: text.into() }
    }
}

/// Token counts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Usage {
    pub prompt_tokens: u64,
    pub completion_tokens: u64,
    #[serde(default)]
    pub reasoning_tokens: u64,
    /// Prompt tokens served from a prefix cache.
    #[serde(default)]
    pub cached_tokens: u64,
}

impl Usage {
    pub fn new(prompt_tokens: u64, completion_tokens: u64) -> Self {
        Self { prompt_tokens, completion_tokens, ..Default::default() }
    }
}

/// Where time went, in milliseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Timings {
    /// Waiting in the queue.
    pub queued_ms: u64,
    /// From acceptance to the first text or reasoning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_token_ms: Option<u64>,
    /// From the request to the end.
    pub total_ms: u64,
}

/// An answer that continued elsewhere: from which offset, on which node.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Resume {
    pub offset: u64,
    pub node: String,
}

impl Resume {
    pub fn new(offset: u64, node: impl Into<String>) -> Self {
        Self { offset, node: node.into() }
    }
}

/// Response metadata.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Meta {
    /// The model node (or backend) that produced the answer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub served_by: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
    #[serde(default)]
    pub cache_hit: bool,
    /// Set when a stand-in answered for the requested model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub standin: Option<String>,
    /// The prefix length this attempt continued from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resumed_from: Option<u64>,
    /// Resumes behind this answer (the inference node's, then the pool's).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub resumes: Vec<Resume>,
    #[serde(default)]
    pub timings: Timings,
}

/// How a turn ended.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Finish {
    /// `stop`, `length`, `tool_calls`, ...
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finish_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,
    #[serde(default)]
    pub meta: Meta,
}

impl Finish {
    pub fn new(finish_reason: impl Into<String>) -> Self {
        Self { finish_reason: Some(finish_reason.into()), ..Default::default() }
    }

    pub fn with_usage(mut self, usage: Usage) -> Self {
        self.usage = Some(usage);
        self
    }
}

/// Asking node to serving node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
pub enum ClientFrame {
    Infer(Request),
    Embed(EmbedRequest),
    Cancel {
        id: String,
    },
    /// Speech to text (since 0.5.8).
    Transcribe(TranscribeRequest),
}

/// Serving node to asking node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ServerFrame {
    Queued {
        id: String,
        position: u32,
    },
    Accepted {
        id: String,
        model: String,
        attempt: u32,
        resume: bool,
    },
    Delta {
        id: String,
        offset: u64,
        text: String,
    },
    Reasoning {
        id: String,
        offset: u64,
        text: String,
    },
    ToolCall {
        id: String,
        index: u32,
        call: ToolCall,
    },
    Embedding {
        id: String,
        index: u32,
        #[serde(with = "bytes")]
        vector: Vec<u8>,
    },
    Usage {
        id: String,
        usage: Usage,
    },
    Done {
        id: String,
        finish: Finish,
    },
    Failed {
        id: String,
        error: RemoteError,
    },
    Cancelled {
        id: String,
    },
    /// Response metadata known before the answer (a cache hit, a stand-in, the revision). Sent
    /// only to askers that set [`Request::early_meta`]; `Done` carries it again.
    Meta {
        id: String,
        meta: Meta,
    },
    /// The answer to a [`TranscribeRequest`], before `Done` (since 0.5.8).
    Transcript {
        id: String,
        transcript: Transcript,
    },
    /// Still at work on an accepted request that streams nothing until it is done
    /// (transcription): sent every [`QUEUE_KEEPALIVE`] so the asker doesn't take the quiet for a
    /// stall (since 0.5.8).
    Working {
        id: String,
    },
}

impl ServerFrame {
    /// The request id the frame belongs to.
    pub fn id(&self) -> &str {
        match self {
            ServerFrame::Queued { id, .. }
            | ServerFrame::Accepted { id, .. }
            | ServerFrame::Delta { id, .. }
            | ServerFrame::Reasoning { id, .. }
            | ServerFrame::ToolCall { id, .. }
            | ServerFrame::Embedding { id, .. }
            | ServerFrame::Usage { id, .. }
            | ServerFrame::Meta { id, .. }
            | ServerFrame::Transcript { id, .. }
            | ServerFrame::Working { id }
            | ServerFrame::Done { id, .. }
            | ServerFrame::Failed { id, .. }
            | ServerFrame::Cancelled { id } => id,
        }
    }
}

/// A vector as little-endian `f32` bytes.
pub fn f32_bytes(v: &[f32]) -> Vec<u8> {
    v.iter().flat_map(|x| x.to_le_bytes()).collect()
}

/// Little-endian `f32` bytes back to a vector.
pub fn bytes_f32(b: &[u8]) -> Result<Vec<f32>, RemoteError> {
    if !b.len().is_multiple_of(4) {
        return Err(RemoteError::protocol(format!("an embedding of {} bytes is not whole f32s", b.len())));
    }
    Ok(b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect())
}

/// One piece of a backend's output.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Piece {
    Text(String),
    Reasoning(String),
    ToolCall(ToolCall),
    Usage(Usage),
    Meta(Meta),
}

/// Where an [`InferBackend`] streams its output. The server turns it into frames with offsets.
#[derive(Debug, Clone)]
pub struct Output {
    tx: mpsc::UnboundedSender<Piece>,
}

impl Output {
    pub(crate) fn channel() -> (Self, mpsc::UnboundedReceiver<Piece>) {
        let (tx, rx) = mpsc::unbounded_channel();
        (Self { tx }, rx)
    }

    /// Answer text.
    pub fn text(&self, delta: impl Into<String>) {
        let d = delta.into();
        if !d.is_empty() {
            let _ = self.tx.send(Piece::Text(d));
        }
    }

    /// Reasoning text.
    pub fn reasoning(&self, delta: impl Into<String>) {
        let d = delta.into();
        if !d.is_empty() {
            let _ = self.tx.send(Piece::Reasoning(d));
        }
    }

    /// A complete tool call.
    pub fn tool_call(&self, call: ToolCall) {
        let _ = self.tx.send(Piece::ToolCall(call));
    }

    /// Token counts so far.
    pub fn usage(&self, usage: Usage) {
        let _ = self.tx.send(Piece::Usage(usage));
    }

    /// Response metadata known before the answer, such as [`Meta::cache_hit`] before replaying a
    /// cached answer. Call it before the first text. The server passes it on to askers that read
    /// it and folds it into the final [`Finish::meta`].
    pub fn meta(&self, meta: Meta) {
        let _ = self.tx.send(Piece::Meta(meta));
    }
}

/// What serves an infer/2 request: a model, or an inference node's routing to model nodes.
/// Implementations poll `cancel` and stream through `out`.
#[async_trait]
pub trait InferBackend: Send + Sync {
    fn name(&self) -> String;

    /// Honours `assistant_prefix`, generating only what comes after it (vLLM
    /// `continue_final_message`, llama.cpp assistant prefill). Default: no.
    fn resumes(&self) -> bool {
        false
    }

    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError>;
}

/// What serves embeddings.
#[async_trait]
pub trait EmbedBackend: Send + Sync {
    fn name(&self) -> String;

    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError>;

    /// The vector and the prompt tokens it took, if the backend knows them. The server sums the
    /// counts into the reply's [`Finish::usage`]. Default: [`embed`](Self::embed), no count.
    async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
        Ok((self.embed(input, cancel).await?, None))
    }
}

/// What serves transcription (since 0.5.8): a speech-to-text model on this node, or an inference
/// node's routing to one.
#[async_trait]
pub trait TranscribeBackend: Send + Sync {
    fn name(&self) -> String;

    /// The transcript of `request.audio`. Poll `cancel`.
    async fn transcribe(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcript, RemoteError>;

    /// The transcript and token counts, if the backend knows them; they go into the reply's
    /// [`Finish::usage`]. Default: [`transcribe`](Self::transcribe), no counts.
    async fn transcribe_counted(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<(Transcript, Option<Usage>), RemoteError> {
        Ok((self.transcribe(request, cancel).await?, None))
    }
}

/// An [`InferBackend`] over a [`ModelBackend`]: inline messages and tools only, no resume;
/// sampling settings, seed and response format are left to the model's defaults.
pub struct ModelAdapter {
    backend: Arc<dyn ModelBackend>,
}

impl ModelAdapter {
    pub fn new(backend: Arc<dyn ModelBackend>) -> Self {
        Self { backend }
    }
}

#[async_trait]
impl InferBackend for ModelAdapter {
    fn name(&self) -> String {
        self.backend.name()
    }

    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
        let messages = match &request.input {
            Input::Messages(m) => m,
            Input::Prompt(_) => return Err(RemoteError::Unsupported { message: "this backend takes messages, not a raw prompt".into() }),
            _ => return Err(RemoteError::unavailable("this node keeps no conversations; send the messages")),
        };
        let (tx, mut rx) = mpsc::unbounded_channel();
        let sink = DeltaSink::new(Some(tx));
        let forward = |ev: AgentEvent| match ev {
            AgentEvent::TextDelta(t) => out.text(t),
            AgentEvent::ReasoningDelta(t) => out.reasoning(t),
            _ => {}
        };
        let mut run = pin!(self.backend.complete(messages, &request.tools, &sink, cancel));
        let turn = loop {
            tokio::select! {
                r = &mut run => break r,
                Some(ev) = rx.recv() => forward(ev),
            }
        };
        while let Ok(ev) = rx.try_recv() {
            forward(ev);
        }
        let turn = turn.map_err(model_error)?;
        let calls = !turn.tool_calls.is_empty();
        for call in turn.tool_calls {
            out.tool_call(call);
        }
        Ok(Finish::new(if calls { "tool_calls" } else { "stop" }))
    }
}

fn is_cancel(bytes: &[u8], id: &str) -> bool {
    matches!(crate::remote::from_cbor::<ClientFrame>(bytes), Ok(ClientFrame::Cancel { id: c }) if c == id)
}

fn millis(d: Duration) -> u64 {
    d.as_millis().min(u64::MAX as u128) as u64
}

enum Waited {
    Go(super::queue::Permit),
    /// The asker cancelled or went away while waiting; the reply (if any) has been sent.
    Gone,
}

/// Waits for a slot, telling the asker its place.
async fn wait_turn(ch: &mut Channel, id: &str, admission: &Admission, priority: Priority) -> Result<Waited, RemoteError> {
    let mut ticket = match admission.enter(priority) {
        Ok(t) => t,
        Err(error) => {
            ch.send_cbor(&ServerFrame::Failed { id: id.to_string(), error }).await?;
            return Ok(Waited::Gone);
        }
    };
    let mut last = None;
    loop {
        tokio::select! {
            turn = ticket.turn(last, QUEUE_KEEPALIVE) => match turn {
                Turn::Go(permit) => return Ok(Waited::Go(permit)),
                Turn::Waiting(position) => {
                    last = Some(position);
                    ch.send_cbor(&ServerFrame::Queued { id: id.to_string(), position }).await?;
                }
            },
            m = ch.rx.recv() => match m {
                Ok(Some(bytes)) if is_cancel(&bytes, id) => {
                    ch.send_cbor(&ServerFrame::Cancelled { id: id.to_string() }).await?;
                    return Ok(Waited::Gone);
                }
                Ok(Some(_)) => {}
                Ok(None) | Err(_) => return Ok(Waited::Gone),
            },
        }
    }
}

/// Serve one infer/2 stream. `caller` is the transport-authenticated peer (plus a certificate
/// if the transport carries one; otherwise the one the request presents is attached). The host
/// authorizes the caller before anything else. Returns when the request is done, failed or
/// cancelled; if the asker goes away it is cancelled.
pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission) -> Result<(), RemoteError> {
    match ch.recv_cbor::<ClientFrame>().await? {
        Some(ClientFrame::Infer(request)) => serve_infer(ch, caller, host, admission, request).await,
        Some(ClientFrame::Embed(request)) => serve_embed(ch, caller, host, admission, request).await,
        Some(ClientFrame::Transcribe(request)) => serve_transcribe(ch, caller, host, admission, request).await,
        Some(ClientFrame::Cancel { .. }) | None => Ok(()),
    }
}

async fn serve_infer(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission, mut request: Request) -> Result<(), RemoteError> {
    let started = Instant::now();
    let id = request.id.clone();
    let caller = caller.presenting(request.cert.take());
    let checked = host.authorize(&caller).and_then(|()| {
        if matches!(request.input, Input::Prompt(_)) && !request.tools.is_empty() {
            return Err(RemoteError::BadRequest { message: "a raw prompt takes no tools".into() });
        }
        if request.raw && matches!(request.input, Input::Context(_)) {
            return Err(RemoteError::BadRequest { message: "raw mode takes assembled messages, not a context_ref".into() });
        }
        if request.assistant_prefix.as_ref().is_some_and(|p| !p.is_consistent()) {
            return Err(RemoteError::BadRequest { message: "assistant_prefix lengths do not match its text".into() });
        }
        host.open_request(&caller, &request)
    });
    let backend = match checked {
        Ok(b) => b,
        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
    };
    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
        Waited::Go(p) => p,
        Waited::Gone => return Ok(()),
    };
    let queued = started.elapsed();
    let resume = backend.resumes();
    let prefix = request.assistant_prefix.clone().filter(|_| resume);
    if !resume {
        request.assistant_prefix = None;
    }
    let (text_at, reasoning_at) = prefix.as_ref().map(|p| (p.len, p.reasoning_len)).unwrap_or((0, 0));
    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: request.attempt, resume }).await?;
    let accepted = Instant::now();

    let (out, mut pieces) = Output::channel();
    let cancel = CancelToken::new();
    let mut framer =
        Framer { id: id.clone(), text_at, reasoning_at, calls: 0, accepted, first_token: None, early_meta: request.early_meta, meta: None };
    let mut run = pin!(backend.infer(&request, &out, &cancel));
    let mut asker_open = true;
    let mut send_failed = false;
    let result = loop {
        tokio::select! {
            r = &mut run => break r,
            Some(p) = pieces.recv() => {
                let Some(f) = framer.frame(p) else { continue };
                if !send_failed && ch.send_cbor(&f).await.is_err() {
                    send_failed = true;
                    cancel.cancel();
                }
            }
            m = ch.rx.recv(), if asker_open => match m {
                Ok(Some(bytes)) => {
                    if is_cancel(&bytes, &id) {
                        cancel.cancel();
                    }
                }
                Ok(None) | Err(_) => {
                    asker_open = false;
                    cancel.cancel();
                }
            },
        }
    };
    if send_failed || !asker_open {
        return Ok(());
    }
    while let Ok(p) = pieces.try_recv() {
        if let Some(f) = framer.frame(p) {
            ch.send_cbor(&f).await?;
        }
    }
    let reply = match result {
        Ok(mut finish) => {
            let meta = &mut finish.meta;
            if let Some(early) = framer.meta.take() {
                meta.cache_hit |= early.cache_hit;
                if meta.served_by.is_none() {
                    meta.served_by = early.served_by;
                }
                if meta.revision.is_none() {
                    meta.revision = early.revision;
                }
                if meta.standin.is_none() {
                    meta.standin = early.standin;
                }
            }
            meta.served_by.get_or_insert_with(|| backend.name());
            if let Some(p) = &prefix {
                meta.resumed_from = Some(p.len);
            }
            meta.timings.queued_ms = millis(queued);
            meta.timings.first_token_ms = framer.first_token.map(millis);
            meta.timings.total_ms = millis(started.elapsed());
            ServerFrame::Done { id, finish }
        }
        Err(_) if cancel.is_cancelled() => ServerFrame::Cancelled { id },
        Err(error) => ServerFrame::Failed { id, error },
    };
    ch.send_cbor(&reply).await
}

/// Turns backend output into frames with offsets and tool-call indexes.
struct Framer {
    id: String,
    text_at: u64,
    reasoning_at: u64,
    calls: u32,
    accepted: Instant,
    first_token: Option<Duration>,
    /// The asker reads `Meta` frames.
    early_meta: bool,
    /// Early metadata from the backend, folded into the final `Done`.
    meta: Option<Meta>,
}

impl Framer {
    fn frame(&mut self, p: Piece) -> Option<ServerFrame> {
        let id = self.id.clone();
        Some(match p {
            Piece::Text(text) => {
                self.first_token.get_or_insert_with(|| self.accepted.elapsed());
                let offset = self.text_at;
                self.text_at += chars(&text);
                ServerFrame::Delta { id, offset, text }
            }
            Piece::Reasoning(text) => {
                self.first_token.get_or_insert_with(|| self.accepted.elapsed());
                let offset = self.reasoning_at;
                self.reasoning_at += chars(&text);
                ServerFrame::Reasoning { id, offset, text }
            }
            Piece::ToolCall(call) => {
                self.calls += 1;
                ServerFrame::ToolCall { id, index: self.calls - 1, call }
            }
            Piece::Usage(usage) => ServerFrame::Usage { id, usage },
            Piece::Meta(meta) => {
                self.meta = Some(meta.clone());
                if !self.early_meta {
                    return None;
                }
                ServerFrame::Meta { id, meta }
            }
        })
    }
}

async fn serve_embed(
    mut ch: Channel,
    caller: Caller,
    host: &dyn InferHost,
    admission: &Admission,
    mut request: EmbedRequest,
) -> Result<(), RemoteError> {
    let started = Instant::now();
    let id = request.id.clone();
    let caller = caller.presenting(request.cert.take());
    let backend = match host.authorize(&caller).and_then(|()| host.open_embed(&caller, request.model.as_deref())) {
        Ok(b) => b,
        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
    };
    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
        Waited::Go(p) => p,
        Waited::Gone => return Ok(()),
    };
    let queued = started.elapsed();
    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
    let cancel = CancelToken::new();
    let mut tokens: Option<u64> = None;
    for (index, input) in request.inputs.iter().enumerate() {
        let vector = tokio::select! {
            v = backend.embed_counted(input, &cancel) => v,
            m = async { loop {
                match ch.rx.recv().await {
                    Ok(Some(bytes)) if is_cancel(&bytes, &id) => return true,
                    Ok(Some(_)) => {}
                    Ok(None) | Err(_) => return false,
                }
            } } => {
                cancel.cancel();
                return if m { ch.send_cbor(&ServerFrame::Cancelled { id }).await } else { Ok(()) };
            }
        };
        match vector {
            Ok((v, n)) => {
                if let Some(n) = n {
                    *tokens.get_or_insert(0) += n;
                }
                ch.send_cbor(&ServerFrame::Embedding { id: id.clone(), index: index as u32, vector: f32_bytes(&v) }).await?
            }
            Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
        }
    }
    let mut finish = Finish::new("stop");
    finish.usage = tokens.map(|n| Usage::new(n, 0));
    finish.meta.served_by = Some(backend.name());
    finish.meta.timings.queued_ms = millis(queued);
    finish.meta.timings.total_ms = millis(started.elapsed());
    ch.send_cbor(&ServerFrame::Done { id, finish }).await
}

async fn serve_transcribe(
    mut ch: Channel,
    caller: Caller,
    host: &dyn InferHost,
    admission: &Admission,
    mut request: TranscribeRequest,
) -> Result<(), RemoteError> {
    let started = Instant::now();
    let id = request.id.clone();
    let caller = caller.presenting(request.cert.take());
    let opened = host.authorize(&caller).and_then(|()| request.check()).and_then(|()| host.open_transcribe(&caller, request.model.as_deref()));
    let backend = match opened {
        Ok(b) => b,
        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
    };
    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
        Waited::Go(p) => p,
        Waited::Gone => return Ok(()),
    };
    let queued = started.elapsed();
    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
    let cancel = CancelToken::new();
    let mut run = pin!(backend.transcribe_counted(&request, &cancel));
    let mut keepalive = tokio::time::interval_at(Instant::now() + QUEUE_KEEPALIVE, QUEUE_KEEPALIVE);
    let result = loop {
        tokio::select! {
            r = &mut run => break r,
            _ = keepalive.tick() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
            m = ch.rx.recv() => match m {
                Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
                    cancel.cancel();
                    return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
                }
                Ok(Some(_)) => {}
                Ok(None) | Err(_) => {
                    cancel.cancel();
                    return Ok(());
                }
            },
        }
    };
    let (transcript, usage) = match result {
        Ok(r) => r,
        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
    };
    ch.send_cbor(&ServerFrame::Transcript { id: id.clone(), transcript }).await?;
    let mut finish = Finish::new("stop");
    finish.usage = usage;
    finish.meta.served_by = Some(backend.name());
    finish.meta.timings.queued_ms = millis(queued);
    finish.meta.timings.total_ms = millis(started.elapsed());
    ch.send_cbor(&ServerFrame::Done { id, finish }).await
}