nrouter 3.1.5

nRouter SDK — one API key for models across six provider clouds
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
//! Typed errors, derived from `spec/nrouter-sdk-spec.json`.
//!
//! The gateway states a stable `code` in the error body. That code — not the
//! HTTP status alone — decides the variant, because two codes share 400 and two
//! share 429, and a caller reacts differently to each.

use std::fmt;

/// Why the gateway refused a request.
///
/// Variants map one-to-one to the `errors` block of the SDK spec. A code the
/// SDK does not know is preserved as [`NRouterError::Other`] rather than being
/// forced into a neighbouring variant — guessing here would tell a caller to
/// retry something permanent.
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::large_enum_variant)] // every payload variant is boxed below
pub enum NRouterError {
    /// `invalid_request` (400) — invalid JSON or request shape.
    Request(Box<ErrorBody>),
    /// `guardrail_blocked` (400) — a guardrail rule denied the request.
    GuardrailBlocked(Box<ErrorBody>),
    /// `invalid_api_key` (401) — virtual-key authentication refused.
    Authentication(Box<ErrorBody>),
    /// `insufficient_credits` (402) — the credit reserve failed. Top up.
    Credit(Box<ErrorBody>),
    /// A BUDGET ceiling (402), not a shortfall.
    ///
    /// Three conditions share 402 and two are budget ceilings, whose fix is the
    /// OPPOSITE of a credit shortfall's: raise the budget, not top up. Telling
    /// a customer whose budget is exhausted to add money is a wrong answer
    /// delivered confidently.
    BudgetExceeded(Box<ErrorBody>),
    /// `model_not_found` (404) — alias absent or invisible to this tenant.
    NotFound(Box<ErrorBody>),
    /// `rate_limit_exceeded` / `tpm_limit_exceeded` (429).
    RateLimit(Box<ErrorBody>),
    /// `credit_check_failed` / `service_unavailable` (503).
    Service(Box<ErrorBody>),
    /// A code this SDK version does not know. Never re-classified.
    Other(Box<ErrorBody>),
    /// The request left this process and did not get an answer — DNS, TLS, a
    /// dropped connection, a timeout. Retryable.
    Transport(String),
    /// The SDK refused before sending anything: no key, or a key that is not
    /// shaped like an nRouter key.
    ///
    /// Separate from [`NRouterError::Transport`] on purpose. Both are raised
    /// locally, but this one is PERMANENT — a caller retrying on
    /// `is_retryable()` would spin forever without ever making a request.
    Configuration(String),
}

/// The parsed gateway error payload plus the metadata worth acting on.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ErrorBody {
    pub message: String,
    pub code: Option<String>,
    pub param: Option<String>,
    pub error_type: Option<String>,
    pub status: Option<u16>,
    pub request_id: Option<String>,
    /// Present on a 429: which limit measured the refusal. Never guessed —
    /// absent means the gateway did not say, and reporting a guess sends a
    /// customer to raise the wrong limit.
    pub limit_source: Option<String>,
    /// Present on a 401: the gateway's stable reason, e.g. `key_route_not_allowed`.
    pub auth_reason: Option<String>,
    /// Present on a 429 when the gateway supplied `retry-after`, in seconds.
    pub retry_after: Option<u64>,
    /// Posture of the guardrail chain when reported by the gateway.
    pub guardrails: Option<String>,
    /// Parsed response metadata when available.
    pub meta: Option<crate::meta::ResponseMeta>,
}

impl NRouterError {
    /// Classify a gateway refusal.
    ///
    /// Three signals, in order, because no single one is sufficient:
    ///
    /// 1. **`code`**, when present — the only thing that separates
    ///    `rate_limit_exceeded` from `tpm_limit_exceeded`. The gateway's WAF
    ///    and its upstream passthrough send one.
    /// 2. **status**, otherwise. The gateway's main error path
    ///    (`GatewayError::into_response`) emits `{"error":{"type","message"}}`
    ///    with **no code at all**, so this is the ordinary case, not the
    ///    fallback it looks like.
    /// 3. **the message**, to split the two 400s. `invalid_request` and
    ///    `guardrail_blocked` share a status, and with no code the message is
    ///    the only signal present — classifying every 400 as a request error
    ///    would make [`NRouterError::GuardrailBlocked`] unreachable, telling a
    ///    caller to fix a body that was never the problem.
    pub fn from_code(mut body: ErrorBody) -> Self {
        body.message = redact_keys(&body.message);
        let boxed = Box::new(body);
        let body = boxed;
        match body.code.as_deref() {
            Some("invalid_request")
            | Some("input_too_large")
            | Some("max_output_tokens_too_large")
            | Some("fallback_not_allowed")
            | Some("guardrail_not_found")
            | Some("image_input_unsupported")
            | Some("pot_route_feature_unsupported")
            | Some("cost_band_unsatisfiable") => Self::Request(body),
            Some("guardrail_blocked") => Self::GuardrailBlocked(body),
            Some("invalid_api_key") => Self::Authentication(body),
            Some("insufficient_credits")
            | Some("plan_allowance_exhausted")
            | Some("plan_required")
            | Some("insufficient_promo_credit")
            | Some("insufficient_hack_credit") => Self::Credit(body),
            Some("model_not_found") => Self::NotFound(body),
            Some("rate_limit_exceeded")
            | Some("tpm_limit_exceeded")
            | Some("pot_spend_limit_exceeded") => Self::RateLimit(body),
            Some("credit_check_failed") | Some("service_unavailable") => Self::Service(body),
            // 403 model deny lists: no permission variant, so `Other` carries
            // the code and the status.
            Some("model_denied_by_org")
            | Some("model_denied_by_team")
            | Some("model_denied_by_key") => Self::Other(body),
            Some(_) => Self::Other(body),
            None => match body.status {
                Some(400) => {
                    if body.guardrails.as_deref() == Some("blocked")
                        || body.error_type.as_deref() == Some("guardrail_blocked")
                        || body.message.to_lowercase().contains("guardrail")
                    {
                        Self::GuardrailBlocked(body)
                    } else {
                        Self::Request(body)
                    }
                }
                Some(401) => Self::Authentication(body),
                // A permission refusal with no code: no dedicated variant, so
                // the base `Other` keeps the status.
                Some(403) => Self::Other(body),
                // The gateway's own wording is the only discriminator it gives
                // us, and it is stable: GatewayError::{BudgetExceeded,
                // ScopedBudgetExceeded} both start their Display with "budget".
                Some(402) => {
                    if body
                        .message
                        .trim_start()
                        .to_lowercase()
                        .starts_with("budget")
                    {
                        Self::BudgetExceeded(body)
                    } else {
                        Self::Credit(body)
                    }
                }
                // Scoped to MODELS. A 404 is also a missing video job, an
                // unknown MCP server or an unknown agent run; calling those
                // `model_not_found` is a wrong answer with a confident stable
                // code on it. Anything unidentifiable stays Other.
                Some(404) => {
                    if body.message.to_lowercase().contains("model") {
                        Self::NotFound(body)
                    } else {
                        Self::Other(body)
                    }
                }
                Some(429) => Self::RateLimit(body),
                Some(502) | Some(504) => {
                    if body.message.to_lowercase().contains("too large") {
                        Self::Other(body)
                    } else {
                        Self::Service(body)
                    }
                }
                Some(503) => Self::Service(body),
                _ => Self::Other(body),
            },
        }
    }

    /// The gateway payload, when the request actually reached the gateway.
    pub fn body(&self) -> Option<&ErrorBody> {
        match self {
            Self::Request(b)
            | Self::GuardrailBlocked(b)
            | Self::Authentication(b)
            | Self::Credit(b)
            | Self::BudgetExceeded(b)
            | Self::NotFound(b)
            | Self::RateLimit(b)
            | Self::Service(b)
            | Self::Other(b) => Some(b),
            Self::Transport(_) | Self::Configuration(_) => None,
        }
    }

    /// Parameter name in error when reported by gateway.
    pub fn param(&self) -> Option<&str> {
        self.body().and_then(|b| b.param.as_deref())
    }

    /// Error family/type when reported by gateway.
    pub fn error_type(&self) -> Option<&str> {
        self.body().and_then(|b| b.error_type.as_deref())
    }

    /// Request ID of the response when available.
    pub fn request_id(&self) -> Option<&str> {
        self.body().and_then(|b| b.request_id.as_deref())
    }

    /// Limit source when reported by gateway.
    pub fn limit_source(&self) -> Option<&str> {
        self.body().and_then(|b| b.limit_source.as_deref())
    }

    /// Auth reason when reported by gateway.
    pub fn auth_reason(&self) -> Option<&str> {
        self.body().and_then(|b| b.auth_reason.as_deref())
    }

    /// Guardrail posture when reported by gateway.
    pub fn guardrails(&self) -> Option<&str> {
        self.body().and_then(|b| b.guardrails.as_deref())
    }

    /// Response metadata when available.
    pub fn meta(&self) -> Option<&crate::meta::ResponseMeta> {
        self.body().and_then(|b| b.meta.as_ref())
    }

    /// Whether retrying the identical request could plausibly succeed.
    ///
    /// Deliberately false for every 4xx that names a permanent condition: a
    /// retry there burns quota and cannot change the answer.
    pub fn is_retryable(&self) -> bool {
        if let Some(body) = self.body() {
            if matches!(body.status, Some(408) | Some(425)) {
                return true;
            }
        }
        matches!(
            self,
            Self::RateLimit(_) | Self::Service(_) | Self::Transport(_)
        )
    }
}

/// Redacts nRouter and upstream API keys from arbitrary strings.
pub fn redact_keys(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut remaining = s;

    while let Some(pos) = remaining.find("sk-") {
        out.push_str(&remaining[..pos]);
        let slice = &remaining[pos..];
        if let Some(stripped) = slice.strip_prefix("sk-nrouter-***") {
            out.push_str("sk-nrouter-***");
            remaining = stripped;
        } else if let Some(rest) = slice.strip_prefix("sk-nrouter-") {
            out.push_str("sk-nrouter-***");
            let skip = rest
                .find(|c: char| !c.is_alphanumeric() && c != '_' && c != '-' && c != '.')
                .unwrap_or(rest.len());
            remaining = &rest[skip..];
        } else if let Some(stripped) = slice.strip_prefix("sk-***") {
            out.push_str("sk-***");
            remaining = stripped;
        } else {
            let rest = &slice["sk-".len()..];
            let key_len = rest
                .find(|c: char| !c.is_alphanumeric() && c != '_' && c != '-' && c != '.')
                .unwrap_or(rest.len());
            if key_len >= 4 {
                out.push_str("sk-***");
                remaining = &rest[key_len..];
            } else {
                out.push_str("sk-");
                remaining = rest;
            }
        }
    }
    out.push_str(remaining);
    out
}

/// Formats any NRouterError into a human-readable, log-safe diagnostic string,
/// masking all API keys.
pub fn format_error(err: &NRouterError) -> String {
    let mut parts = vec![match err {
        NRouterError::Request(_) => "[request]".to_string(),
        NRouterError::GuardrailBlocked(_) => "[guardrail_blocked]".to_string(),
        NRouterError::Authentication(_) => "[authentication]".to_string(),
        NRouterError::Credit(_) => "[credit]".to_string(),
        NRouterError::BudgetExceeded(_) => "[budget_exceeded]".to_string(),
        NRouterError::NotFound(_) => "[not_found]".to_string(),
        NRouterError::RateLimit(_) => "[rate_limit]".to_string(),
        NRouterError::Service(_) => "[service]".to_string(),
        NRouterError::Other(_) => "[other]".to_string(),
        NRouterError::Transport(_) => "[transport]".to_string(),
        NRouterError::Configuration(_) => "[configuration]".to_string(),
    }];

    if let Some(b) = err.body() {
        if let Some(status) = b.status {
            parts.push(format!("HTTP {status}"));
        }
        if let Some(code) = &b.code {
            parts.push(format!("code={code}"));
        }
        if let Some(param) = &b.param {
            parts.push(format!("param={param}"));
        }
        if let Some(req_id) = &b.request_id {
            parts.push(format!("requestId={req_id}"));
        }
        if let Some(src) = &b.limit_source {
            parts.push(format!("limitSource={src}"));
        }
        if let Some(ra) = b.retry_after {
            parts.push(format!("retryAfter={ra}s"));
        }
        parts.push(format!(": {}", redact_keys(&b.message)));
    } else {
        parts.push(format!(": {}", redact_keys(&err.to_string())));
    }
    parts.join(" ")
}

/// Structured gateway error envelope.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ErrorEnvelope {
    pub code: Option<String>,
    pub message: Option<String>,
    pub param: Option<String>,
    pub error_type: Option<String>,
}

/// Parse a gateway JSON error body into a structured ErrorEnvelope with secret redaction.
pub fn parse_gateway_error_envelope(body: &serde_json::Value) -> ErrorEnvelope {
    let node = body.get("error").unwrap_or(body);
    ErrorEnvelope {
        code: node
            .get("code")
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned),
        message: node
            .get("message")
            .and_then(serde_json::Value::as_str)
            .map(redact_keys),
        param: node
            .get("param")
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned),
        error_type: node
            .get("type")
            .and_then(serde_json::Value::as_str)
            .map(str::to_owned),
    }
}

impl fmt::Display for NRouterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Transport(m) => write!(f, "nRouter transport error: {}", redact_keys(m)),
            Self::Configuration(m) => write!(f, "nRouter configuration error: {}", redact_keys(m)),
            other => {
                let b = other.body().expect("non-transport variants carry a body");
                let msg = redact_keys(&b.message);
                match &b.code {
                    Some(code) => write!(f, "{} ({code})", msg),
                    None => write!(f, "{}", msg),
                }
            }
        }
    }
}

impl std::error::Error for NRouterError {}

/// Maximum allowable backoff in seconds (24 hours).
pub const MAX_RETRY_AFTER_SECONDS: u64 = 86400;

/// Parses an RFC 9110 Retry-After header value (delta-seconds or HTTP-date).
pub fn parse_retry_after(raw: Option<&str>) -> Option<u64> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    parse_retry_after_at(raw, now)
}

/// Parses an RFC 9110 Retry-After header value relative to a given epoch timestamp in seconds.
pub fn parse_retry_after_at(raw: Option<&str>, now_epoch: u64) -> Option<u64> {
    let raw = raw?.trim();
    if raw.is_empty() {
        return None;
    }
    if let Ok(seconds) = raw.parse::<u64>() {
        return Some(seconds.min(MAX_RETRY_AFTER_SECONDS));
    }
    parse_http_date(raw).map(|epoch| {
        if epoch <= now_epoch {
            0
        } else {
            (epoch - now_epoch).min(MAX_RETRY_AFTER_SECONDS)
        }
    })
}

/// Computes a bounded jittered exponential backoff duration.
///
/// Honors `retry_after_seconds` when present and > 0, bounded by `max_delay`.
/// Clamps `attempt` to 30 to prevent arithmetic overflow on `2^attempt`.
/// Jitter spreads backoff between 50% and 100% of the computed window.
pub fn compute_jittered_backoff(
    attempt: u32,
    base_delay: std::time::Duration,
    max_delay: std::time::Duration,
    retry_after_seconds: Option<u64>,
) -> std::time::Duration {
    let attempt = attempt.min(30);
    if let Some(ra) = retry_after_seconds {
        if ra > 0 {
            let retry_dur = std::time::Duration::from_secs(ra).min(max_delay);
            let nanos = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.subsec_nanos())
                .unwrap_or(0);
            let factor = 0.5 + 0.5 * ((nanos % 1000) as f64 / 1000.0);
            return std::time::Duration::from_secs_f64(retry_dur.as_secs_f64() * factor);
        }
    }

    let mult = 1u64 << attempt;
    let raw = base_delay.saturating_mul(mult as u32);
    let capped = raw.min(max_delay);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or(0);
    let factor = 0.5 + 0.5 * ((nanos % 1000) as f64 / 1000.0);
    std::time::Duration::from_secs_f64(capped.as_secs_f64() * factor)
}

fn parse_http_date(s: &str) -> Option<u64> {
    let parts: Vec<&str> = s.split_whitespace().collect();
    if parts.len() != 6 {
        return None;
    }
    if !parts[0].ends_with(',') {
        return None;
    }
    let day: u32 = parts[1].parse().ok()?;
    let month: u32 = match parts[2].to_ascii_lowercase().as_str() {
        "jan" => 1,
        "feb" => 2,
        "mar" => 3,
        "apr" => 4,
        "may" => 5,
        "jun" => 6,
        "jul" => 7,
        "aug" => 8,
        "sep" => 9,
        "oct" => 10,
        "nov" => 11,
        "dec" => 12,
        _ => return None,
    };
    let year: i64 = parts[3].parse().ok()?;
    if year < 1970 {
        return None;
    }
    let time_parts: Vec<&str> = parts[4].split(':').collect();
    if time_parts.len() != 3 {
        return None;
    }
    let hour: u32 = time_parts[0].parse().ok()?;
    let min: u32 = time_parts[1].parse().ok()?;
    let sec: u32 = time_parts[2].parse().ok()?;
    if hour > 23 || min > 59 || sec > 60 || day == 0 || day > 31 {
        return None;
    }
    let days = days_from_civil(year, month, day)?;
    let total_secs = days as u64 * 86400 + hour as u64 * 3600 + min as u64 * 60 + sec as u64;
    Some(total_secs)
}

fn days_from_civil(y: i64, m: u32, d: u32) -> Option<i64> {
    let mut y = y;
    if m <= 2 {
        y -= 1;
    }
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = (y - era * 400) as u32;
    let m_adj = if m > 2 { m - 3 } else { m + 9 };
    let doy = (153 * m_adj + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    let days = era * 146097 + doe as i64 - 719468;
    if days >= 0 {
        Some(days)
    } else {
        None
    }
}