tilo-model-client 0.5.1

Authenticated, host-scoped model capabilities for Tilo applications.
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
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Model RPC over capabilities supplied by an authenticated host.

#[cfg(unix)]
use std::io::Write;
#[cfg(unix)]
use std::os::fd::{FromRawFd, RawFd};
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use thiserror::Error;
#[cfg(unix)]
use zeroize::Zeroizing;

#[cfg(test)]
mod error_tests;
pub mod failure;
#[cfg(feature = "runtime-client")]
pub mod runtime_client;
pub mod transport;
pub mod validation;

// Launcher and runtime-portal uppercase the service name without replacing '-'.
pub const SERVICE_FD_ENV: &str = "TILO_SVC_MODEL-GATEWAY_FD";
/// Stable ownership namespace used by origin-bound provider credentials.
pub const SERVICE_NAME: &str = "model-gateway";
pub const RPC_VERSION: u16 = 3;
/// Every gateway request and response: a little-endian `u32` length, then
/// JSON.
pub const FRAMING: wire_frame::Framing = wire_frame::Framing::little_endian(2 * 1024 * 1024);

pub use agent_provider_config::is_supervised_loopback;

/// Whether `revision` names an immutable model revision: a full lowercase
/// SHA-1 or SHA-256 commit id, never a branch or tag.
#[must_use]
pub fn is_pinned_revision(revision: &str) -> bool {
    matches!(revision.len(), 40 | 64)
        && revision
            .bytes()
            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
}

/// The only encoded-preview media types accepted by the local vision RPC.
/// Keeping this vocabulary closed means a caller cannot ask the trusted
/// gateway to fetch a URL or interpret an arbitrary document as an image.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct VisionImage {
    /// `image/jpeg`, `image/png`, or `image/webp`.
    pub media_type: String,
    /// Standard base64 of a caller-decoded, downscaled preview.
    pub data_base64: String,
    /// SHA-256 of the original photo bytes, not of `data_base64`.
    pub source_content_hash: String,
}

/// One deliberately small photograph reference supplied to the dedicated
/// local face runtime.  `photo_id` is an app address, not a pathname; the
/// runtime never receives an identity label or an instruction from Photos.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct FaceImage {
    pub photo_id: String,
    pub media_type: String,
    pub data_base64: String,
    pub source_content_hash: String,
}

/// A request that can cross the sandbox boundary. A server also authenticates
/// the launcher-provided app preamble. No request carries a provider key:
/// this computer keeps none.
#[derive(Deserialize, Serialize)]
#[serde(tag = "verb", rename_all = "snake_case")]
pub enum Request {
    /// Negotiate reusable, per-operation cancellation before starting work.
    /// Older gateways reject this verb; clients must not start paid work then.
    CancellationSupported,
    /// Native connection-local operation identity. Not an authentication claim.
    Cancellable { id: u64, request: Box<Request> },
    /// Cancel only the matching operation on this authenticated connection.
    /// The acknowledgement is a synchronization barrier, even after completion.
    Cancel { id: u64 },
    /// Provider-neutral completion, asked of the person's own model on their
    /// workspace's server. The provider and model it names are this
    /// computer's description of the caller's choice; the server answers with
    /// the model the person chose there.
    Complete {
        profile_id: String,
        model_id: String,
        request: agent_provider_config::protocol::ModelRequest,
        timeout_ms: u64,
        #[serde(default)]
        stream: bool,
    },
    /// Provider-neutral completion with the person's default model, asked on
    /// their workspace's server.
    CompleteDefault {
        request: agent_provider_config::protocol::ModelRequest,
        timeout_ms: u64,
        #[serde(default)]
        stream: bool,
    },
    /// A content-free timing mark from the agent (whose own stderr a managed
    /// launch discards), written to the gateway's timing log. Older RPC3
    /// servers reject this additive verb; callers ignore the refusal.
    Trace {
        trace: PlanTrace,
        event: TraceEvent,
        /// When the mark happened (Unix ms), if the caller had to hold it
        /// while a streamed turn owned the channel. Absent: now.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        at_unix_ms: Option<u64>,
    },
    /// Fixed-shape, device-local visual analysis for Photos. The gateway
    /// owns the prompt and refuses hosted, unpinned, or non-vision profiles;
    /// a sandboxed caller never obtains direct network access.
    AnalyzeImage {
        profile_id: String,
        model_id: String,
        image: VisionImage,
    },
    /// Fixed, consent-guarded face detection and clustering.  The gateway owns
    /// the request schema and admits it only for the signed local face model.
    /// It returns opaque cluster/photo membership; no embedding, crop, face
    /// rectangle, identity name, or raw path can cross this boundary.
    ClusterFaces {
        profile_id: String,
        model_id: String,
        images: Vec<FaceImage>,
    },
    /// Find the subject of one bounded picture with the on-device
    /// segmentation model the person installed (Settings › Models). The
    /// gateway runs the model itself, on the CPU; no model file, path or
    /// network reaches the caller, and nothing leaves the device. Answers a
    /// [`SubjectMatte`] as JSON. Older servers reject this verb; callers
    /// treat that as no model.
    SegmentSubject { image: VisionImage },
    /// The models a provider offers, asked with its stored key or sign-in:
    /// Settings' model list and connection test. Answers the models as JSON
    /// (`ModelDescriptor`s); a failure names its kind, never what the
    /// provider wrote. Older gateways reject this verb.
    ListModels { profile_id: String },
}

/// How much of each pixel of a [`Request::SegmentSubject`] picture is its
/// subject, and what found it.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct SubjectMatte {
    /// The matte's size: the picture's.
    pub width: u32,
    pub height: u32,
    /// Standard base64 of a greyscale PNG, white where the subject is.
    pub matte_png_base64: String,
    /// The catalogue model and its pinned revision, for provenance.
    pub model_id: String,
    pub revision: String,
    /// Milliseconds spent loading the model (0 when it was loaded already)
    /// and running it.
    pub load_ms: u64,
    pub infer_ms: u64,
}

/// The message the gateway refuses [`Request::SegmentSubject`] with when no
/// segmentation model is installed, so a caller can offer to set one up.
pub const NO_SEGMENTATION_MODEL: &str = "no on-device subject model is installed";

/// Correlates the model turns of one agent decision.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct PlanTrace {
    /// Random per decision; carries no content.
    pub id: u64,
    /// Zero-based model turn within the decision, or a step index for marks.
    pub turn: u32,
}

/// The closed vocabulary of agent timing marks.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TraceEvent {
    /// The model's final plan was read and accepted by the agent.
    PlanReady,
    /// The decision failed (fallback, timeout, invalid answer).
    PlanFailed,
    /// The agent sent one planned action to the host.
    ActionSubmitted,
    ActionSettled,
}

/// The only streaming event kind: one completed provider tool call, as
/// `{"id":..,"name":..,"arguments":<JSON string>}` in [`Response::output`].
pub const EVENT_TOOL_CALL: &str = "tool_call";

/// An intermediate streaming event requested with `deltas`: raw argument text
/// appended to the tool call in progress, as
/// `{"index":u32,"id":str|null,"name":str,"delta":str}` in
/// [`Response::output`]. Every delta of a call precedes its `tool_call`.
pub const EVENT_TOOL_CALL_DELTA: &str = "tool_call_delta";

#[derive(Debug, Deserialize, Serialize)]
pub struct Frame<T> {
    pub version: u16,
    #[serde(flatten)]
    pub value: T,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Response {
    pub ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub configured: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Additive RPC3 diagnostic. Older peers ignore this field; absent on older gateways.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_error: Option<agent_provider_config::protocol::ModelError>,
    /// Set only on intermediate streaming frames (see [`EVENT_TOOL_CALL`]).
    /// A response without an event is the final frame of a request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub event: Option<String>,
}

impl Response {
    /// Construct a redacted failure while retaining its machine-readable kind.
    pub fn failure(mut error: agent_provider_config::protocol::ModelError) -> Self {
        error.message = agent_provider_config::protocol::ModelError::new(error.kind).message;
        Self {
            ok: false,
            output: None,
            configured: None,
            error: Some(error.message.clone()),
            model_error: Some(error),
            event: None,
        }
    }

    /// Typed errors take precedence. English matching is only for old gateways.
    pub fn failure_error(&self) -> ClientError {
        match &self.model_error {
            Some(error) => {
                ClientError::Model(agent_provider_config::protocol::ModelError::new(error.kind))
            }
            None => ClientError::Rejected(self.error.clone().unwrap_or_default()),
        }
    }

    pub fn into_result(self) -> Result<Self, ClientError> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.failure_error())
        }
    }
}

#[derive(Error)]
pub enum ClientError {
    #[error("Tilo model gateway is unavailable")]
    Unavailable,
    #[error("{0}")]
    Model(agent_provider_config::protocol::ModelError),
    #[error("model gateway protocol error")]
    Protocol(String),
    #[error("model gateway refused request: {}", self.model_error())]
    Rejected(String),
}

impl std::fmt::Debug for ClientError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, formatter)
    }
}

impl ClientError {
    /// A safe, actionable diagnostic for neutral streaming consumers.
    pub fn model_error(&self) -> agent_provider_config::protocol::ModelError {
        use agent_provider_config::protocol::{ErrorKind, ModelError};
        let kind = match self {
            Self::Model(error) => return error.clone(),
            Self::Unavailable => ErrorKind::Unavailable,
            Self::Protocol(_) => ErrorKind::InvalidResponse,
            Self::Rejected(detail) => {
                // RPC3 predates typed errors. Classify only at this compatibility
                // boundary; never repeat the gateway's diagnostic to a frontend.
                let detail = detail.to_ascii_lowercase();
                let patterns: &[(ErrorKind, &[&str])] = &[
                    (
                        ErrorKind::CreditsExhausted,
                        &["credits", "quota", "subscription_required"],
                    ),
                    (
                        ErrorKind::ContextLimit,
                        &["context limit", "context_length"],
                    ),
                    (ErrorKind::Authentication, &["authentication", "api key"]),
                    (ErrorKind::PermissionDenied, &["permission denied"]),
                    (ErrorKind::RateLimited, &["rate limit"]),
                    (ErrorKind::TimedOut, &["timed out"]),
                    (ErrorKind::Cancelled, &["cancelled"]),
                    (
                        ErrorKind::Truncated,
                        &["truncated", "without a final response"],
                    ),
                    (
                        ErrorKind::Transport,
                        &["network", "transport failed", "stream interrupted"],
                    ),
                    (
                        ErrorKind::Refused,
                        &[
                            "model declined",
                            "model refused",
                            "provider refusal",
                            "content filter",
                        ],
                    ),
                    (ErrorKind::InvalidRequest, &["unsupported image media type"]),
                    (
                        ErrorKind::InvalidResponse,
                        &["malformed", "unreadable", "unsupported finish reason"],
                    ),
                ];
                patterns
                    .iter()
                    .find(|(_, phrases)| phrases.iter().any(|phrase| detail.contains(phrase)))
                    .map_or(ErrorKind::Provider, |(kind, _)| *kind)
            }
        };
        ModelError::new(kind)
    }
}

/// Whether this process has the launcher-issued service descriptor. This does
/// not probe or connect to a pathname socket, so the sandbox cannot substitute
/// a different same-UID service.
#[cfg(unix)]
pub fn available() -> bool {
    std::env::var(SERVICE_FD_ENV)
        .ok()
        .and_then(|value| value.parse::<RawFd>().ok())
        .is_some_and(|fd| fd >= 3 && unsafe { libc::fcntl(fd, libc::F_GETFD) } != -1)
}

/// No launcher-issued gateway transport is implemented on this platform.
/// Environment variables cannot manufacture a supported capability.
#[cfg(not(unix))]
pub fn available() -> bool {
    false
}

/// Send a request over the launcher-provided service fd. The fd is duplicated
/// for each RPC so a short-lived helper cannot close the parent app's channel.
///
/// # Errors
///
/// Returns [`ClientError::Unavailable`] when the launcher service descriptor or
/// gateway connection is unavailable, [`ClientError::Protocol`] for malformed
/// frames, and [`ClientError::Rejected`] when the gateway refuses the request.
#[cfg(unix)]
pub fn request(request: Request) -> Result<Response, ClientError> {
    let turn = ChannelTurn::take()?;
    let response = exchange(request);
    drop(turn);
    response
}

/// [`request`], on this thread's turn of the channel.
#[cfg(unix)]
fn exchange(request: Request) -> Result<Response, ClientError> {
    exchange_on(service_stream()?, request)
}

/// `request` on the connection `stream`, written as one frame and answered.
#[cfg(unix)]
fn exchange_on(mut stream: UnixStream, request: Request) -> Result<Response, ClientError> {
    write_frame(
        &mut stream,
        &Frame {
            version: RPC_VERSION,
            value: request,
        },
    )?;
    let response: Response = read_frame(&mut stream)?;
    response.into_result()
}

/// A duplicate of `descriptor` this side owns, for one exchange: the launcher
/// handed the caller the service connection, and every RPC takes a duplicate
/// so concurrent exchanges never interleave their frames.
///
/// # Errors
/// [`ClientError::Unavailable`] when the descriptor cannot be duplicated.
#[cfg(unix)]
fn duplicate(descriptor: std::os::fd::BorrowedFd<'_>) -> Result<UnixStream, ClientError> {
    let owned = descriptor
        .try_clone_to_owned()
        .map_err(|_| ClientError::Unavailable)?;
    Ok(UnixStream::from(owned))
}

/// [`analyze_image`] on the connection `descriptor`, for a host that holds the
/// model gateway's descriptor itself rather than through the launcher's
/// environment (the session's own services).
///
/// # Errors
/// [`ClientError::Unavailable`] when the descriptor cannot be used, else why
/// the gateway did not answer.
#[cfg(unix)]
pub fn analyze_image_on(
    descriptor: std::os::fd::BorrowedFd<'_>,
    profile_id: &str,
    model_id: &str,
    image: VisionImage,
) -> Result<String, ClientError> {
    let response = exchange_on(
        duplicate(descriptor)?,
        Request::AnalyzeImage {
            profile_id: profile_id.to_string(),
            model_id: model_id.to_string(),
            image,
        },
    )?;
    response
        .output
        .ok_or_else(|| ClientError::Protocol("gateway returned no image analysis".into()))
}

/// [`cluster_faces`] on the connection `descriptor`; see [`analyze_image_on`].
///
/// # Errors
/// [`ClientError::Unavailable`] when the descriptor cannot be used, else why
/// the gateway did not answer.
#[cfg(unix)]
pub fn cluster_faces_on(
    descriptor: std::os::fd::BorrowedFd<'_>,
    profile_id: &str,
    model_id: &str,
    images: Vec<FaceImage>,
) -> Result<String, ClientError> {
    let response = exchange_on(
        duplicate(descriptor)?,
        Request::ClusterFaces {
            profile_id: profile_id.to_string(),
            model_id: model_id.to_string(),
            images,
        },
    )?;
    response
        .output
        .ok_or_else(|| ClientError::Protocol("gateway returned no face clusters".into()))
}

/// The process's one exchange on the launcher channel.
///
/// Every RPC duplicates the same connected socket, so the duplicates share
/// one byte stream, and the gateway answers a connection's requests in the
/// order they came. Two threads talking at once (a one-shot call beside a
/// planning turn, two agents of one host) would read each
/// other's frames: one caller handed another's answer, or a frame split
/// between two readers. The gateway serves one request at a time anyway,
/// so taking turns costs no throughput.
#[cfg(unix)]
static CHANNEL: std::sync::Mutex<()> = std::sync::Mutex::new(());

#[cfg(unix)]
thread_local! {
    /// Whether this thread is in an exchange: a call from inside a stream's
    /// event callback would otherwise wait on itself forever.
    static IN_EXCHANGE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// This thread's turn on the launcher channel, until dropped.
#[cfg(unix)]
struct ChannelTurn {
    _held: std::sync::MutexGuard<'static, ()>,
}

#[cfg(unix)]
impl ChannelTurn {
    /// Wait for the channel.
    ///
    /// # Errors
    ///
    /// [`ClientError::Protocol`] when this thread is already in an exchange
    /// (a call from a stream's event callback): its frames would be read as
    /// the stream's.
    fn take() -> Result<Self, ClientError> {
        if IN_EXCHANGE.get() {
            return Err(ClientError::Protocol(
                "a gateway call was made while this thread's call was in progress".into(),
            ));
        }
        // The guard protects no data: a panic mid-exchange leaves nothing
        // to repair, so a poisoned lock is taken as it is.
        let held = CHANNEL
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        IN_EXCHANGE.set(true);
        Ok(Self { _held: held })
    }
}

#[cfg(unix)]
impl Drop for ChannelTurn {
    fn drop(&mut self) {
        IN_EXCHANGE.set(false);
    }
}

/// Duplicate the launcher-issued service descriptor for one RPC.
#[cfg(unix)]
fn service_stream() -> Result<UnixStream, ClientError> {
    let fd = std::env::var(SERVICE_FD_ENV)
        .ok()
        .and_then(|value| value.parse::<RawFd>().ok())
        .filter(|fd| *fd >= 3 && unsafe { libc::fcntl(*fd, libc::F_GETFD) } != -1)
        .ok_or(ClientError::Unavailable)?;
    // SAFETY: F_DUPFD_CLOEXEC duplicates a checked open descriptor; ownership
    // of the duplicate transfers immediately to UnixStream.
    let duplicate = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
    if duplicate < 0 {
        return Err(ClientError::Unavailable);
    }
    Ok(unsafe { UnixStream::from_raw_fd(duplicate) })
}

/// Refuse gateway operations when the launcher capability transport is absent.
///
/// # Errors
///
/// Always returns [`ClientError::Unavailable`]. There is no direct-network or
/// pathname-socket fallback for an unsupported host.
#[cfg(not(unix))]
pub fn request(_request: Request) -> Result<Response, ClientError> {
    Err(ClientError::Unavailable)
}

/// Complete a neutral turn, delivering presentation-only deltas followed by
/// its authoritative response. Deltas never authorize tool execution.
///
/// # Errors
/// Rejects unavailable gateways, provider failures and malformed responses.
/// Malformed event payloads are rejected after draining the response so the
/// shared capability channel remains synchronized.
pub fn complete_streaming(
    profile_id: &str,
    model_id: &str,
    model_request: agent_provider_config::protocol::ModelRequest,
    timeout: Duration,
    on_event: &mut dyn FnMut(&agent_provider_config::protocol::StreamEvent),
) -> Result<agent_provider_config::protocol::ModelResponse, ClientError> {
    complete_stream(
        (profile_id, model_id),
        model_request,
        timeout,
        on_event,
        None,
    )
}

/// [`complete_streaming`] for a caller that may stop wanting the answer:
/// once `stop` says so (it is asked every [`STOP_POLL`] while the turn
/// runs), the gateway is told to stop the provider call, so
/// an abandoned turn is not paid for to its end and no longer holds the
/// process's one gateway channel.
///
/// # Errors
/// As [`complete_streaming`]; a stopped turn fails as
/// [`ErrorKind::Cancelled`](agent_provider_config::protocol::ErrorKind::Cancelled),
/// and a gateway that cannot stop calls refuses the turn before any work.
pub fn complete_streaming_until(
    profile_id: &str,
    model_id: &str,
    model_request: agent_provider_config::protocol::ModelRequest,
    timeout: Duration,
    on_event: &mut dyn FnMut(&agent_provider_config::protocol::StreamEvent),
    stop: &(dyn Fn() -> bool + Sync),
) -> Result<agent_provider_config::protocol::ModelResponse, ClientError> {
    complete_stream(
        (profile_id, model_id),
        model_request,
        timeout,
        on_event,
        Some(stop),
    )
}

fn complete_stream(
    (profile_id, model_id): (&str, &str),
    model_request: agent_provider_config::protocol::ModelRequest,
    timeout: Duration,
    on_event: &mut dyn FnMut(&agent_provider_config::protocol::StreamEvent),
    stop: Option<&(dyn Fn() -> bool + Sync)>,
) -> Result<agent_provider_config::protocol::ModelResponse, ClientError> {
    let request = Request::Complete {
        profile_id: profile_id.into(),
        model_id: model_id.into(),
        request: model_request,
        timeout_ms: u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
        stream: true,
    };
    let mut invalid = false;
    let output = streaming_request(
        request,
        true,
        &mut |kind, payload| {
            // Drain after a malformed event to preserve the shared legacy channel,
            // but never deliver more deltas from a poisoned turn.
            if invalid {
                return;
            }
            match transport::decode_event(kind, payload) {
                Ok(Some(event)) => on_event(&event),
                Ok(None) => {}
                Err(_) => invalid = true,
            }
        },
        stop,
    );
    let result = if invalid {
        Err(agent_provider_config::protocol::ModelError::invalid(
            "invalid gateway stream event",
        ))
    } else {
        output
            .map_err(|error| error.model_error())
            .and_then(|output| transport::decode_completion(&output))
    };
    transport::finish_stream(result, on_event).map_err(ClientError::Model)
}

/// How often a stoppable stream asks whether its caller still wants it.
pub const STOP_POLL: Duration = Duration::from_millis(100);

#[cfg(not(unix))]
fn streaming_request(
    _request: Request,
    _deltas: bool,
    _on_event: &mut dyn FnMut(&str, &str),
    _stop: Option<&(dyn Fn() -> bool + Sync)>,
) -> Result<String, ClientError> {
    Err(ClientError::Unavailable)
}

#[cfg(unix)]
fn streaming_request(
    request: Request,
    deltas: bool,
    on_event: &mut dyn FnMut(&str, &str),
    stop: Option<&(dyn Fn() -> bool + Sync)>,
) -> Result<String, ClientError> {
    let turn = ChannelTurn::take()?;
    let output = streaming_exchange(request, deltas, on_event, stop);
    drop(turn);
    output
}

/// [`streaming_request`], on this thread's turn of the channel.
#[cfg(unix)]
fn streaming_exchange(
    request: Request,
    deltas: bool,
    on_event: &mut dyn FnMut(&str, &str),
    stop: Option<&(dyn Fn() -> bool + Sync)>,
) -> Result<String, ClientError> {
    let mut stream = service_stream()?;
    let Some(stop) = stop else {
        write_frame(
            &mut stream,
            &Frame {
                version: RPC_VERSION,
                value: request,
            },
        )?;
        return read_stream(&mut stream, deltas, on_event, None);
    };
    let id = cancellable(&mut stream, request)?;
    let writer = stream.try_clone().map_err(|error| io_error(&error))?;
    let watch = StopWatch::default();
    std::thread::scope(|scope| {
        // Without a watcher the turn still runs, only unstoppable between
        // its events.
        let _ = std::thread::Builder::new()
            .name("model-gateway-stop".into())
            .spawn_scoped(scope, || watch.stop_when(stop, id, writer));
        let output = read_stream(&mut stream, deltas, on_event, Some((&watch, id)));
        watch.finish();
        output
    })
}

/// Start `request` as a cancellable operation on `stream`, after the
/// gateway agreed to stop operations: its id.
#[cfg(unix)]
fn cancellable(stream: &mut UnixStream, request: Request) -> Result<u64, ClientError> {
    use agent_provider_config::protocol::{ErrorKind, ModelError};
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    write_frame(
        stream,
        &Frame {
            version: RPC_VERSION,
            value: Request::CancellationSupported,
        },
    )?;
    let supported: Response = read_frame(stream)?;
    if !supported.ok
        || supported.event.is_some()
        || supported.output.as_deref() != Some("cancel-v1")
    {
        return Err(ClientError::Model(ModelError::new(ErrorKind::Unsupported)));
    }
    let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    write_frame(
        stream,
        &Frame {
            version: RPC_VERSION,
            value: Request::Cancellable {
                id,
                request: Box::new(request),
            },
        },
    )?;
    Ok(id)
}

/// Where a stoppable stream is: over (its answer read), or told to stop.
#[cfg(unix)]
#[derive(Default)]
struct StopWatch {
    state: std::sync::Mutex<Stopping>,
    over: std::sync::Condvar,
}

#[cfg(unix)]
#[derive(Default)]
struct Stopping {
    over: bool,
    cancelled: bool,
}

#[cfg(unix)]
impl StopWatch {
    /// Until the stream is over, ask `stop` every [`STOP_POLL`]; once it
    /// says so, tell the gateway to stop operation `id`.
    fn stop_when(&self, stop: &(dyn Fn() -> bool + Sync), id: u64, mut writer: UnixStream) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while !state.over && !stop() {
            state = self
                .over
                .wait_timeout(state, STOP_POLL)
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .0;
        }
        if !state.over {
            // Under the lock: the reader either sees the stream told to
            // stop, or has taken its answer and this is not sent.
            state.cancelled = write_frame(
                &mut writer,
                &Frame {
                    version: RPC_VERSION,
                    value: Request::Cancel { id },
                },
            )
            .is_ok();
        }
        drop(state);
    }

    /// One frame was read; `last` when it is the stream's answer. Whether
    /// the stream was told to stop, so the frame is not the caller's.
    fn read(&self, last: bool) -> bool {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let cancelled = state.cancelled;
        let over = last && !cancelled;
        if over {
            state.over = true;
        }
        drop(state);
        if over {
            self.over.notify_all();
        }
        cancelled
    }

    /// The stream ended, however it did: the watcher stops.
    fn finish(&self) {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .over = true;
        self.over.notify_all();
    }
}

/// Read a streamed answer's frames from `stream`, delivering its events. A
/// stoppable stream (`watch`) told to stop reads on, discarding, to the
/// gateway's acknowledgement, so no frame of it is left on the channel.
#[cfg(unix)]
fn read_stream(
    stream: &mut UnixStream,
    deltas: bool,
    on_event: &mut dyn FnMut(&str, &str),
    watch: Option<(&StopWatch, u64)>,
) -> Result<String, ClientError> {
    // A bounded number of intermediate frames: one per completed tool call,
    // and (only when asked for) a separately bounded number of deltas.
    let mut calls = 0_usize;
    let mut delta_frames = 0_usize;
    let mut stopped = 0_usize;
    loop {
        let response: Response = read_frame(stream)?;
        if let Some((watch, id)) = watch
            && watch.read(response.event.is_none())
        {
            if response.event.is_none()
                && response.ok
                && response.output.as_deref() == Some(format!("cancelled:{id}").as_str())
            {
                return Err(ClientError::Model(
                    agent_provider_config::protocol::ModelError::new(
                        agent_provider_config::protocol::ErrorKind::Cancelled,
                    ),
                ));
            }
            stopped = stopped.saturating_add(1);
            if stopped > MAX_STREAM_EVENTS + MAX_DELTA_EVENTS + 1 {
                let _ = stream.shutdown(std::net::Shutdown::Both);
                return Err(ClientError::Protocol(
                    "gateway did not acknowledge the stop".into(),
                ));
            }
            continue;
        }
        let response = response.into_result()?;
        match response.event {
            Some(event) => {
                let count = if deltas
                    && (matches!(
                        event.as_str(),
                        EVENT_TOOL_CALL_DELTA | "text_delta" | "reasoning_delta"
                    )) {
                    delta_frames = delta_frames.saturating_add(1);
                    delta_frames > MAX_DELTA_EVENTS
                } else {
                    calls = calls.saturating_add(1);
                    calls > MAX_STREAM_EVENTS
                };
                if count {
                    // Do not leave unread frames on the shared launcher channel.
                    let _ = stream.shutdown(std::net::Shutdown::Both);
                    return Err(ClientError::Protocol(
                        "gateway sent too many streaming events".into(),
                    ));
                }
                on_event(&event, response.output.as_deref().unwrap_or(""));
            }
            None => {
                return response.output.ok_or_else(|| {
                    ClientError::Protocol("gateway returned no provider response".into())
                });
            }
        }
    }
}

/// The most intermediate frames one streamed turn may carry.
pub const MAX_STREAM_EVENTS: usize = 64;

/// The most `tool_call_delta` frames one streamed turn may carry; bounded
/// separately from [`MAX_STREAM_EVENTS`]. A gateway stops sending deltas at
/// this count (the completed `tool_call` events still follow).
pub const MAX_DELTA_EVENTS: usize = 4096;

/// Send a content-free timing mark. Best effort: a gateway that predates the
/// verb refuses it, and that refusal is ignored by callers.
///
/// # Errors
///
/// As [`request`].
pub fn trace(trace: PlanTrace, event: TraceEvent) -> Result<(), ClientError> {
    trace_at(trace, event, None)
}

/// [`trace`] for a mark that happened at `at_unix_ms` and was held back while
/// a streamed turn used the channel; the gateway logs that time.
///
/// # Errors
///
/// As [`trace`].
pub fn trace_at(
    trace: PlanTrace,
    event: TraceEvent,
    at_unix_ms: Option<u64>,
) -> Result<(), ClientError> {
    request(Request::Trace {
        trace,
        event,
        at_unix_ms,
    })
    .map(|_| ())
}

/// Request a fixed-schema visual analysis through the launcher-issued gateway
/// descriptor. This operation can only be authorized for Photos by the
/// gateway; callers cannot provide a URL, arbitrary prompt, or timeout.
pub fn analyze_image(
    profile_id: &str,
    model_id: &str,
    image: VisionImage,
) -> Result<String, ClientError> {
    let response = request(Request::AnalyzeImage {
        profile_id: profile_id.to_string(),
        model_id: model_id.to_string(),
        image,
    })?;
    response
        .output
        .ok_or_else(|| ClientError::Protocol("gateway returned no image analysis".into()))
}

/// Run the dedicated local face model against one bounded batch.  This is not
/// a generic multimodal request and cannot be redirected to a hosted model.
pub fn cluster_faces(
    profile_id: &str,
    model_id: &str,
    images: Vec<FaceImage>,
) -> Result<String, ClientError> {
    let response = request(Request::ClusterFaces {
        profile_id: profile_id.to_string(),
        model_id: model_id.to_string(),
        images,
    })?;
    response
        .output
        .ok_or_else(|| ClientError::Protocol("gateway returned no face clusters".into()))
}

/// Find the subject of one bounded picture with the installed on-device
/// segmentation model.
///
/// # Errors
///
/// Returns [`ClientError`] if the launcher gateway is absent, no model is
/// installed ([`ClientError::Rejected`] with [`NO_SEGMENTATION_MODEL`]), the
/// picture is refused, or the answer is malformed.
pub fn segment_subject(image: VisionImage) -> Result<SubjectMatte, ClientError> {
    let response = request(Request::SegmentSubject { image })?;
    let output = response
        .output
        .ok_or_else(|| ClientError::Protocol("gateway returned no subject".into()))?;
    serde_json::from_str(&output)
        .map_err(|error| ClientError::Protocol(format!("malformed subject: {error}")))
}

/// Write one size-bounded JSON frame to a gateway stream.
///
/// # Errors
///
/// Returns [`ClientError::Protocol`] when serialization fails or the frame is
/// too large, and a typed transport/timeout error when writing fails.
#[cfg(unix)]
pub fn write_frame<T: Serialize>(stream: &mut UnixStream, value: &T) -> Result<(), ClientError> {
    let body = Zeroizing::new(
        serde_json::to_vec(value).map_err(|error| ClientError::Protocol(error.to_string()))?,
    );
    FRAMING.write(stream, &body).map_err(|error| match error {
        wire_frame::FrameError::Io(error) => io_error(&error),
        _ => ClientError::Protocol("request exceeds gateway frame limit".into()),
    })?;
    stream.flush().map_err(|error| io_error(&error))
}

#[cfg(unix)]
fn io_error(error: &std::io::Error) -> ClientError {
    use agent_provider_config::protocol::{ErrorKind, ModelError};
    ClientError::Model(ModelError::new(match error.kind() {
        std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ErrorKind::TimedOut,
        _ => ErrorKind::Transport,
    }))
}

/// Read and decode one size-bounded JSON frame from a gateway stream.
///
/// # Errors
///
/// Returns a typed transport/truncation error on stream loss and
/// [`ClientError::Protocol`] for an invalid length or payload.
#[cfg(unix)]
pub fn read_frame<T: for<'a> Deserialize<'a>>(stream: &mut UnixStream) -> Result<T, ClientError> {
    use agent_provider_config::protocol::{ErrorKind, ModelError};
    let mut body = Zeroizing::new(Vec::new());
    match FRAMING.read_into(stream, &mut body) {
        Ok(true) => {}
        Err(wire_frame::FrameError::TooLarge(_)) => {
            return Err(ClientError::Protocol("gateway frame exceeds limit".into()));
        }
        Ok(false) | Err(wire_frame::FrameError::Truncated | wire_frame::FrameError::Closed) => {
            return Err(ClientError::Model(ModelError::new(ErrorKind::Truncated)));
        }
        Err(wire_frame::FrameError::Io(error)) => return Err(io_error(&error)),
        Err(_) => return Err(ClientError::Protocol("invalid gateway frame".into())),
    }
    serde_json::from_slice(&body)
        .map_err(|_| ClientError::Protocol("invalid gateway response".into()))
}

#[cfg(test)]
#[cfg(unix)]
mod wire_tests {
    use super::*;

    /// The gateway socket's bytes: a little-endian `u32` length, then JSON.
    #[test]
    fn gateway_wire_bytes_are_pinned() {
        use std::io::Read as _;
        let (mut client, mut gateway) = UnixStream::pair().unwrap();
        write_frame(
            &mut client,
            &Response {
                ok: true,
                output: Some("x".into()),
                configured: None,
                error: None,
                model_error: None,
                event: None,
            },
        )
        .unwrap();
        let mut sent = [0_u8; 28];
        gateway.read_exact(&mut sent).unwrap();
        assert_eq!(sent[..4], [24, 0, 0, 0]);
        assert_eq!(&sent[4..], br#"{"ok":true,"output":"x"}"#);

        gateway.write_all(&[12, 0, 0, 0]).unwrap();
        gateway.write_all(br#"{"ok":false}"#).unwrap();
        let response: Response = read_frame(&mut client).unwrap();
        assert!(!response.ok);
    }

    fn answer(output: &str, event: Option<&str>) -> Response {
        Response {
            ok: true,
            output: Some(output.into()),
            configured: None,
            error: None,
            model_error: None,
            event: event.map(Into::into),
        }
    }

    tilo_test_env::scenario! {
        /// The one launcher channel under a stream, a stop and a nested call. Each case hands the
        /// client a socket pair of its own through a scoped environment, and every exchange gives its
        /// turn back when it ends, so a case starts with the channel free.
        fn calls_on_the_shared_launcher_channel_take_turns_and_stop_cleanly;

        phase a_call_beside_a_stream_on_the_shared_channel_gets_its_own_answer;
        // A one-shot call runs beside a streamed planning turn, over the one
        // launcher channel. A call asked while the turn's caller is still busy
        // with one of its events used to read the turn's next frame as its own
        // answer, and the turn then read the call's: it now waits its turn, and
        // each caller gets its own answer.
        {
            use std::os::fd::AsRawFd as _;
            let (app, mut gateway) = UnixStream::pair().unwrap();
            let mut env = tilo_test_env::ScopedEnv::new();
            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
            let (asked_by, asked) = std::sync::mpsc::channel();
            let server = std::thread::spawn(move || {
                // The stream: one event, then its answer, written at once, as a
                // gateway writes them whenever the provider has them.
                let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
                assert!(matches!(frame.value, Request::Complete { .. }));
                write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
                write_frame(&mut gateway, &answer("the plan", None)).unwrap();
                // Then each one-shot call, answered with what it carried.
                while let Ok(frame) = read_frame::<Frame<Request>>(&mut gateway) {
                    let _ = asked_by.send(());
                    write_frame(&mut gateway, &answer(&echoed(&frame.value), None)).unwrap();
                }
            });
            let (in_event, event_seen) = std::sync::mpsc::channel();
            let (go_on, go) = std::sync::mpsc::channel::<()>();
            let stream = std::thread::spawn(move || {
                streaming_request(
                    streamed_turn(),
                    false,
                    &mut |kind, _| {
                        assert_eq!(kind, EVENT_TOOL_CALL);
                        // The turn's caller is busy with the event (running the
                        // call) while the one-shot call is asked.
                        in_event.send(()).unwrap();
                        let _ = go.recv_timeout(tilo_test_env::hang_bound());
                    },
                    None,
                )
            });
            tilo_test_env::recv("the stream's event", &event_seen);
            let call = std::thread::spawn(|| one_shot(7));
            // Long enough for a call on the channel to have read a frame.
            let _ = asked.recv_timeout(Duration::from_millis(300));
            std::thread::sleep(Duration::from_millis(100));
            go_on.send(()).unwrap();
            assert_eq!(stream.join().unwrap().unwrap(), "the plan");
            assert_eq!(call.join().unwrap().unwrap(), "7");
            drop(env);
            drop(app);
            server.join().unwrap();
        }

        phase a_stream_its_caller_gives_up_on_is_stopped_at_the_gateway;
        // The agent lets go of a planning turn when its task is stopped. The
        // turn used to run to its end at the provider, billed, holding the
        // channel: the gateway is now told to stop it, the turn ends as
        // cancelled, and the next call on the channel gets its own answer.
        {
            use std::os::fd::AsRawFd as _;
            let (app, gateway) = UnixStream::pair().unwrap();
            let mut env = tilo_test_env::ScopedEnv::new();
            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
            let server = stoppable_gateway(gateway, false);
            let (plan, after) = give_up_then_call();
            let Err(ClientError::Model(error)) = plan else {
                panic!("a stopped turn is cancelled, not answered: {plan:?}");
            };
            assert_eq!(
                error.kind,
                agent_provider_config::protocol::ErrorKind::Cancelled
            );
            assert_eq!(after.unwrap(), "9");
            drop(env);
            drop(app);
            server.join().unwrap();
        }

        phase a_stop_that_crosses_the_answer_leaves_nothing_on_the_channel;
        // The stop can cross the answer: the gateway acknowledges it after
        // the answer went out, and that acknowledgement is read here, not
        // left on the channel as the next call's answer.
        {
            use std::os::fd::AsRawFd as _;
            let (app, gateway) = UnixStream::pair().unwrap();
            let mut env = tilo_test_env::ScopedEnv::new();
            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
            let server = stoppable_gateway(gateway, true);
            let (plan, after) = give_up_then_call();
            assert!(
                matches!(&plan, Err(ClientError::Model(error)) if error.kind == agent_provider_config::protocol::ErrorKind::Cancelled),
                "{plan:?}"
            );
            assert_eq!(after.unwrap(), "9");
            drop(env);
            drop(app);
            server.join().unwrap();
        }

        phase a_call_from_inside_a_stream_is_refused_rather_than_waiting_on_itself;
        // A call from inside a stream's event callback, on the stream's own
        // thread, would read the stream's frames as its answer, and waiting
        // for the channel would wait on itself: it is refused instead.
        {
            use std::os::fd::AsRawFd as _;
            let (app, mut gateway) = UnixStream::pair().unwrap();
            let mut env = tilo_test_env::ScopedEnv::new();
            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
            let server = std::thread::spawn(move || {
                let _: Frame<Request> = read_frame(&mut gateway).unwrap();
                write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
                write_frame(&mut gateway, &answer("the plan", None)).unwrap();
            });
            let mut nested = None;
            let plan = streaming_request(
                streamed_turn(),
                false,
                &mut |_, _| {
                    nested = Some(request(Request::Trace {
                        trace: PlanTrace { id: 1, turn: 0 },
                        event: TraceEvent::ActionSubmitted,
                        at_unix_ms: None,
                    }));
                },
                None,
            );
            assert_eq!(plan.unwrap(), "the plan");
            assert!(matches!(nested, Some(Err(ClientError::Protocol(_)))));
            server.join().unwrap();
            drop(env);
        }
    }

    /// A streamed neutral turn, as the agent asks for one.
    fn streamed_turn() -> Request {
        Request::Complete {
            profile_id: "hosted".into(),
            model_id: "model".into(),
            request: agent_provider_config::protocol::Conversation::new("system", "hello")
                .request(Vec::new(), 64),
            timeout_ms: 1000,
            stream: true,
        }
    }

    /// A gateway that streams one event of a cancellable turn, then
    /// (when `answers_first`) its answer, and acknowledges the stop it is
    /// then sent; afterwards it answers each one-shot call with what it carried.
    /// Hands back the id the stop named.
    fn stoppable_gateway(
        mut gateway: UnixStream,
        answers_first: bool,
    ) -> std::thread::JoinHandle<u64> {
        std::thread::spawn(move || {
            gateway
                .set_read_timeout(Some(tilo_test_env::hang_bound()))
                .unwrap();
            let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
            assert!(matches!(frame.value, Request::CancellationSupported));
            write_frame(&mut gateway, &answer("cancel-v1", None)).unwrap();
            let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
            let Request::Cancellable { id, request } = frame.value else {
                panic!("a stoppable stream starts a cancellable operation");
            };
            assert!(matches!(*request, Request::Complete { .. }));
            write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
            if answers_first {
                write_frame(&mut gateway, &answer("the plan", None)).unwrap();
            }
            let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
            let Request::Cancel { id: stopped } = frame.value else {
                panic!("the caller stops the operation");
            };
            if !answers_first {
                // A frame the provider produced before the stop arrived.
                write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
            }
            write_frame(&mut gateway, &answer(&format!("cancelled:{stopped}"), None)).unwrap();
            assert_eq!(stopped, id);
            while let Ok(frame) = read_frame::<Frame<Request>>(&mut gateway) {
                write_frame(&mut gateway, &answer(&echoed(&frame.value), None)).unwrap();
            }
            stopped
        })
    }

    /// Ask a stoppable turn that its caller gives up on at its first event,
    /// then a one-shot call on the same channel.
    fn give_up_then_call() -> (Result<String, ClientError>, Result<String, ClientError>) {
        let stop = std::sync::atomic::AtomicBool::new(false);
        let mut events = 0_usize;
        let plan = streaming_request(
            streamed_turn(),
            false,
            &mut |_, _| {
                events = events.saturating_add(1);
                stop.store(true, std::sync::atomic::Ordering::Relaxed);
                // Long enough for the watcher to see it before the answer
                // is read.
                std::thread::sleep(Duration::from_millis(300));
            },
            Some(&|| stop.load(std::sync::atomic::Ordering::Relaxed)),
        );
        assert_eq!(events, 1, "nothing after the stop reaches the caller");
        (plan, one_shot(9))
    }

    /// A one-shot call on the launcher channel, carrying `id`: the fake gateways answer it
    /// with that id ([`echoed`]).
    fn one_shot(id: u64) -> Result<String, ClientError> {
        request(Request::Trace {
            trace: PlanTrace { id, turn: 0 },
            event: TraceEvent::ActionSubmitted,
            at_unix_ms: None,
        })
        .map(|answered| answered.output.unwrap_or_default())
    }

    /// What a fake gateway answers a one-shot call with: the id it carried.
    fn echoed(asked: &Request) -> String {
        let Request::Trace { trace, .. } = asked else {
            panic!("only one-shot calls follow the stream");
        };
        trace.id.to_string()
    }
}

#[cfg(test)]
#[cfg(not(unix))]
mod unsupported_platform_tests {
    use super::*;

    #[test]
    fn photos_and_secret_operations_require_a_supported_gateway_capability() {
        assert!(!available());
        assert!(matches!(
            analyze_image(
                "local",
                "vision",
                VisionImage {
                    media_type: "image/png".into(),
                    data_base64: String::new(),
                    source_content_hash: String::new(),
                }
            ),
            Err(ClientError::Unavailable)
        ));
        assert!(matches!(
            cluster_faces("local", "faces", Vec::new()),
            Err(ClientError::Unavailable)
        ));
        assert!(matches!(
            plan(
                "hosted",
                "model",
                serde_json::Value::Null,
                Duration::from_secs(1)
            ),
            Err(ClientError::Unavailable)
        ));
    }
}

#[cfg(test)]
mod local_model_tests {
    use super::*;

    #[test]
    fn local_vision_requires_an_immutable_model_revision() {
        assert!(is_pinned_revision(&"a".repeat(40)));
        assert!(is_pinned_revision(&"b".repeat(64)));
        assert!(!is_pinned_revision("main"));
        assert!(!is_pinned_revision(&"A".repeat(40)));
        assert!(!is_pinned_revision(&"g".repeat(40)));
    }
}