polyc-judgment-systemone 2026.9.6

JudgmentProvider backend over the System One protocol, reached through a gateway (POST {base_url}/systemone).
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
//! A concrete [`JudgmentProvider`] over the System One protocol, reached
//! through a gateway rather than a single vendor's own host.
//!
//! One request is `POST {base_url}/systemone` with a bearer key. `base_url`
//! is the gateway's API path prefix; this crate appends `/systemone` to
//! build the endpoint. The body is the [`JudgmentRequest`] plus the
//! configured model, and the response decodes into [`JudgmentResponse`]
//! verbatim — a gateway response can carry extra fields (a request id, the
//! routed provider, a cost figure) this crate never reads, and those decode
//! away silently rather than failing the response.
//!
//! The key stays wrapped in [`Sensitive`] for the provider's whole lifetime.
//! Only the `bearer_auth` call in [`SystemOneJudgment::judge`] reads it, and
//! no error carries a header, a body, or the key.

use async_trait::async_trait;
use polyc_crypto::sensitive::Sensitive;
use polyc_judgment::{JudgmentError, JudgmentProvider, JudgmentRequest, JudgmentResponse};
use serde::Serialize;

/// The gateway's default API path prefix. `/systemone` is appended to build
/// the endpoint.
pub const DEFAULT_BASE_URL: &str = "https://openrouter.ai/api/v1";

/// Which endpoint, model, and credential to call.
#[derive(Debug, Clone)]
pub struct SystemOneConfig {
    /// The gateway's API path prefix, without a trailing slash.
    /// `/systemone` is appended. Defaults to [`DEFAULT_BASE_URL`].
    pub base_url: String,
    /// The bearer key. Stays wrapped for the provider's whole lifetime.
    pub api_key: Sensitive<String>,
    /// The model alias every request names.
    pub model: String,
}

/// How long to wait for the TCP/TLS connection to establish.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Total request timeout. A judgment is one small non-streaming response, so
/// a whole-request bound fits, unlike the streaming completion adapters.
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// `JudgmentProvider` over the System One protocol, dialed through a gateway.
pub struct SystemOneJudgment {
    http: reqwest::Client,
    config: SystemOneConfig,
}

impl std::fmt::Debug for SystemOneJudgment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SystemOneJudgment")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl SystemOneJudgment {
    /// Builds a provider. Construction resolves no ambient credential, so
    /// the only way it fails is the local HTTP client build itself.
    ///
    /// # Errors
    ///
    /// Returns [`JudgmentError::Transport`] when the client fails to build.
    /// A client that fell back to one with no configured timeouts would
    /// defeat the connect and request timeouts silently, so construction
    /// fails instead of substituting a default client.
    pub fn new(config: SystemOneConfig) -> Result<Self, JudgmentError> {
        let http = reqwest::Client::builder()
            .connect_timeout(CONNECT_TIMEOUT)
            .timeout(REQUEST_TIMEOUT)
            .build()
            .map_err(|err| JudgmentError::Transport(Box::new(err)))?;
        Ok(Self { http, config })
    }

    fn endpoint(&self) -> String {
        format!("{}/systemone", self.config.base_url.trim_end_matches('/'))
    }
}

/// The wire body: the request plus the model alias.
#[derive(Serialize)]
struct WireRequest<'a> {
    model: &'a str,
    #[serde(flatten)]
    request: &'a JudgmentRequest,
}

/// Maps a non-success status onto the shared [`JudgmentError`] classes.
///
/// The body is dropped: the gateway describes a 422 in its body, and that
/// text can quote the state, which may hold conversation content.
///
/// `401`/`403` are `Unauthorized`, `402` is `Exhausted` (an out-of-credit
/// gateway, not a bad request), `429` is `RateLimited`, and every other `4xx`
/// is `Invalid` — a rejected request shape, not a backend, credential, or
/// balance problem. Every remaining status, `5xx` included, is `Unavailable`.
fn error_for_status(status: u16, retry_after: Option<std::time::Duration>) -> JudgmentError {
    match status {
        401 | 403 => JudgmentError::Unauthorized,
        402 => JudgmentError::Exhausted,
        429 => JudgmentError::RateLimited { retry_after },
        400..=499 => JudgmentError::Invalid(format!("status {status}")),
        _ => JudgmentError::Unavailable { status },
    }
}

/// Reads a `Retry-After` header, either form: whole-seconds delta
/// (`"120"`) or an HTTP-date (`"Wed, 21 Oct 2026 07:28:00 GMT"`).
///
/// An HTTP-date in the past yields a zero duration rather than `None` — the
/// header still said to back off, just not for how much longer.
fn parse_retry_after(value: &str) -> Option<std::time::Duration> {
    let value = value.trim();
    if let Ok(secs) = value.parse::<u64>() {
        return Some(std::time::Duration::from_secs(secs));
    }
    let target = httpdate::parse_http_date(value).ok()?;
    Some(
        target
            .duration_since(std::time::SystemTime::now())
            .unwrap_or(std::time::Duration::ZERO),
    )
}

#[async_trait]
impl JudgmentProvider for SystemOneJudgment {
    type Error = JudgmentError;

    async fn judge(&self, request: JudgmentRequest) -> Result<JudgmentResponse, Self::Error> {
        let body = WireRequest {
            model: &self.config.model,
            request: &request,
        };
        tracing::debug!(
            questions = request.questions.len(),
            model = %self.config.model,
            "judgment request"
        );
        let resp = self
            .http
            .post(self.endpoint())
            .bearer_auth(self.config.api_key.expose())
            .json(&body)
            .send()
            .await
            .map_err(|err| JudgmentError::Transport(Box::new(err)))?;

        let status = resp.status();
        if !status.is_success() {
            let retry_after = resp
                .headers()
                .get(reqwest::header::RETRY_AFTER)
                .and_then(|v| v.to_str().ok())
                .and_then(parse_retry_after);
            return Err(error_for_status(status.as_u16(), retry_after));
        }
        let bytes = resp
            .bytes()
            .await
            .map_err(|err| JudgmentError::Transport(Box::new(err)))?;
        serde_json::from_slice(&bytes).map_err(|err| JudgmentError::Malformed(err.to_string()))
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use std::collections::BTreeMap;

    use polyc_judgment::{Answer, Question};
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{body_partial_json, header, method, path},
    };

    use super::*;

    fn provider(base_url: String) -> SystemOneJudgment {
        SystemOneJudgment::new(SystemOneConfig {
            base_url,
            api_key: Sensitive::new("gw-test-key".to_owned()),
            model: "judge-test-model".to_owned(),
        })
        .expect("client builds")
    }

    fn request() -> JudgmentRequest {
        let mut questions = BTreeMap::new();
        questions.insert(
            "urgent".to_owned(),
            Question::Noul {
                instructions: "Is it urgent?".to_owned(),
                criteria: None,
            },
        );
        JudgmentRequest {
            state: serde_json::json!({"message": "Help now"}),
            questions,
        }
    }

    #[tokio::test]
    async fn posts_the_wire_shape_with_bearer_and_decodes_answers() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/systemone"))
            .and(header("authorization", "Bearer gw-test-key"))
            .and(body_partial_json(serde_json::json!({
                "model": "judge-test-model",
                "state": {"message": "Help now"},
                "questions": {"urgent": {"type": "noul", "instructions": "Is it urgent?"}}
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "model": "judge-test-model-2",
                "answers": {"urgent": {"type": "noul", "noul": 0.93}},
                "usage": {"input_tokens": 312, "output_tokens": 48}
            })))
            .expect(1)
            .mount(&server)
            .await;

        let response = provider(server.uri())
            .judge(request())
            .await
            .expect("judged");
        assert_eq!(response.model, "judge-test-model-2");
        assert_eq!(response.noul("urgent"), Some(0.93));
        assert_eq!(response.usage.input_tokens, 312);
        assert!(matches!(
            response.answers.get("urgent"),
            Some(Answer::Noul { noul }) if (*noul - 0.93).abs() < f64::EPSILON
        ));
    }

    /// A gateway response carries fields this crate never reads (a request
    /// id, the routed provider, a per-call cost). They decode away silently
    /// instead of failing the response.
    #[tokio::test]
    async fn extra_gateway_fields_are_ignored_not_required() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/systemone"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "gen-01JAR3X9K2",
                "provider": "routed-provider",
                "model": "judge-test-model-2",
                "answers": {"urgent": {"type": "noul", "noul": 0.2}},
                "usage": {"input_tokens": 100, "output_tokens": 10, "cost": 0.0004}
            })))
            .expect(1)
            .mount(&server)
            .await;

        let response = provider(server.uri())
            .judge(request())
            .await
            .expect("judged despite extra fields");
        assert_eq!(response.noul("urgent"), Some(0.2));
    }

    #[tokio::test]
    async fn unauthorized_maps_without_leaking_the_body() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(401).set_body_string("bad key gw-test-key"))
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("refused");
        assert!(matches!(err, JudgmentError::Unauthorized), "{err:?}");
        assert!(!err.to_string().contains("gw-test-key"));
    }

    #[tokio::test]
    async fn rate_limit_carries_retry_after() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "7"))
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("limited");
        assert!(
            matches!(
                err,
                JudgmentError::RateLimited {
                    retry_after: Some(d)
                } if d == std::time::Duration::from_secs(7)
            ),
            "{err:?}"
        );
    }

    #[tokio::test]
    async fn validation_failure_is_invalid_and_overload_is_unavailable() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(body_partial_json(
                serde_json::json!({"model": "judge-test-model"}),
            ))
            .respond_with(ResponseTemplate::new(422).set_body_json(serde_json::json!({
                "detail": [{"loc": ["body", "questions"], "msg": "bad"}]
            })))
            .up_to_n_times(1)
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("invalid");
        assert!(matches!(err, JudgmentError::Invalid(_)), "{err:?}");

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(529))
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("overloaded");
        assert!(
            matches!(err, JudgmentError::Unavailable { status: 529 }),
            "{err:?}"
        );
    }

    #[tokio::test]
    async fn malformed_success_body_is_malformed() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(200).set_body_string("not json"))
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("malformed");
        assert!(matches!(err, JudgmentError::Malformed(_)), "{err:?}");
    }

    /// The key never reaches a `Debug` rendering of the provider.
    #[test]
    fn debug_output_redacts_the_key() {
        let debug = format!("{:?}", provider("http://localhost:1".to_owned()));
        assert!(!debug.contains("gw-test-key"), "{debug}");
        assert!(debug.contains("Sensitive(<redacted>)"), "{debug}");
    }

    #[test]
    fn endpoint_trims_a_trailing_slash() {
        let p = provider("http://localhost:1/".to_owned());
        assert_eq!(p.endpoint(), "http://localhost:1/systemone");
    }

    /// An exhausted gateway balance is an availability failure, not a bad
    /// request — `FallbackJudgment` needs to tell it apart from `Invalid` so
    /// it can fall back.
    #[tokio::test]
    async fn payment_required_is_exhausted() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(402))
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("payment required");
        assert!(matches!(err, JudgmentError::Exhausted), "{err:?}");
    }

    #[tokio::test]
    async fn conflict_is_invalid() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(409))
            .mount(&server)
            .await;
        let err = provider(server.uri())
            .judge(request())
            .await
            .expect_err("conflict");
        assert!(matches!(err, JudgmentError::Invalid(_)), "{err:?}");
    }

    #[test]
    fn retry_after_parses_a_delta_seconds_value() {
        assert_eq!(
            parse_retry_after("120"),
            Some(std::time::Duration::from_secs(120))
        );
    }

    #[test]
    fn retry_after_parses_an_http_date_value() {
        // Far enough in the future that "now" during the test run never
        // catches up to it.
        let duration = parse_retry_after("Thu, 01 Jan 2099 00:00:00 GMT").expect("parses");
        assert!(duration.as_secs() > 0, "{duration:?}");
    }

    #[test]
    fn retry_after_rejects_an_unrecognized_value() {
        assert_eq!(parse_retry_after("not a duration"), None);
    }
}