Skip to main content

jev/
wire.rs

1//! Faithful wire-format mappings: request/response envelopes, usage, and metadata.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::{answer::Answers, question::Questions, state::State};
7
8/// Opaque, pass-through trace configuration.
9///
10/// The Decisions surface accepts a `trace` object whose shape is not yet stable
11/// upstream; this SDK passes it through verbatim rather than modelling a schema
12/// that might change. See the design doc's "Open Questions" for the plan to grow
13/// this into typed sub-structs once the field stabilizes.
14///
15/// # Examples
16///
17/// ```
18/// use jev::TraceConfig;
19///
20/// let trace = TraceConfig::new(serde_json::json!({"sampled": true}));
21/// assert_eq!(trace.value()["sampled"], true);
22/// ```
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24#[serde(transparent)]
25pub struct TraceConfig(Value);
26
27impl TraceConfig {
28    /// Wraps an arbitrary JSON value as trace configuration.
29    #[must_use]
30    pub fn new(value: Value) -> Self {
31        TraceConfig(value)
32    }
33
34    /// The wrapped JSON value.
35    #[must_use]
36    pub fn value(&self) -> &Value {
37        &self.0
38    }
39}
40
41/// The request body sent to either surface.
42///
43/// `session_id`, `user`, and `trace` are Decisions-surface-only; the client clears
44/// them (and logs a `debug!`) before serializing when [`crate::config::Surface::SystemOne`]
45/// is selected, so this one struct is the single copy of the wire-serialization logic
46/// for both surfaces.
47#[derive(Debug, Serialize)]
48pub(crate) struct DecisionRequest<'a> {
49    pub model: &'a str,
50    pub state: &'a State,
51    pub questions: &'a Questions,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub session_id: Option<&'a str>,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub user: Option<&'a str>,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub trace: Option<&'a TraceConfig>,
58}
59
60/// Token and cost accounting for one request, as reported by the gateway.
61#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
62pub struct Usage {
63    /// Input tokens billed for the request (state + questions).
64    pub input_tokens: u32,
65    /// Output tokens billed for the response.
66    pub output_tokens: u32,
67    /// Billed cost, when the gateway reports it.
68    #[serde(default)]
69    pub cost: Option<f64>,
70}
71
72/// The full response body from either surface.
73#[derive(Debug, Deserialize)]
74pub struct Response {
75    /// The model snapshot that actually served the request.
76    pub model: String,
77    /// The answered questions.
78    pub answers: Answers,
79    /// Token and cost accounting.
80    pub usage: Usage,
81    /// Request identifier, when the gateway reports one.
82    #[serde(default)]
83    pub id: Option<String>,
84    /// The serving provider, when the gateway reports one.
85    #[serde(default)]
86    pub provider: Option<String>,
87}
88
89/// The response envelope without the answers: identifiers, model snapshot, usage,
90/// cost, and latency.
91///
92/// Returned alongside a typed decision by [`crate::Client::decide_with`], for callers
93/// who need to record cost or the dated model snapshot without giving up the typed
94/// answer struct.
95#[derive(Debug, Clone, PartialEq)]
96pub struct ResponseMeta {
97    /// Request identifier, when the gateway reported one.
98    pub id: Option<String>,
99    /// The model snapshot that actually served the request.
100    pub model: String,
101    /// The serving provider, when the gateway reported one.
102    pub provider: Option<String>,
103    /// Token and cost accounting.
104    pub usage: Usage,
105    /// Wall-clock latency of the request, including any retries.
106    pub latency: std::time::Duration,
107}
108
109impl ResponseMeta {
110    /// Builds a `ResponseMeta` from a [`Response`] and the measured latency.
111    pub(crate) fn from_response(response: &Response, latency: std::time::Duration) -> Self {
112        ResponseMeta {
113            id: response.id.clone(),
114            model: response.model.clone(),
115            provider: response.provider.clone(),
116            usage: response.usage,
117            latency,
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn test_should_deserialize_full_response() {
128        let body = r#"{
129            "model": "typesafe/jev-1.13",
130            "id": "req_123",
131            "provider": "openrouter",
132            "usage": {"input_tokens": 100, "output_tokens": 5, "cost": 0.001},
133            "answers": {"refund": {"type": "noul", "noul": 0.9}}
134        }"#;
135        let response: Response = serde_json::from_str(body).unwrap();
136        assert_eq!(response.model, "typesafe/jev-1.13");
137        assert_eq!(response.id, Some("req_123".to_string()));
138        assert_eq!(response.usage.input_tokens, 100);
139        assert_eq!(response.answers.noul("refund").unwrap(), 0.9);
140    }
141
142    #[test]
143    fn test_should_default_optional_response_fields_when_absent() {
144        let body = r#"{
145            "model": "jev-1.13",
146            "usage": {"input_tokens": 1, "output_tokens": 1},
147            "answers": {}
148        }"#;
149        let response: Response = serde_json::from_str(body).unwrap();
150        assert_eq!(response.id, None);
151        assert_eq!(response.provider, None);
152        assert_eq!(response.usage.cost, None);
153    }
154
155    #[test]
156    fn test_should_wrap_trace_config_transparently() {
157        let trace = TraceConfig::new(serde_json::json!({"sampled": true}));
158        let encoded = serde_json::to_value(&trace).unwrap();
159        assert_eq!(encoded, serde_json::json!({"sampled": true}));
160    }
161
162    #[test]
163    fn test_should_skip_none_optional_request_fields() {
164        let questions = Questions::builder()
165            .noul("refund", "Is this a refund?")
166            .build()
167            .unwrap();
168        let state: State = "hi".into();
169        let req = DecisionRequest {
170            model: "jev-1.13",
171            state: &state,
172            questions: &questions,
173            session_id: None,
174            user: None,
175            trace: None,
176        };
177        let json = serde_json::to_value(&req).unwrap();
178        assert!(json.get("session_id").is_none());
179        assert!(json.get("user").is_none());
180        assert!(json.get("trace").is_none());
181    }
182
183    #[test]
184    fn test_should_build_response_meta_from_response() {
185        let body = r#"{
186            "model": "jev-1.13",
187            "usage": {"input_tokens": 1, "output_tokens": 1},
188            "answers": {}
189        }"#;
190        let response: Response = serde_json::from_str(body).unwrap();
191        let meta = ResponseMeta::from_response(&response, std::time::Duration::from_millis(42));
192        assert_eq!(meta.model, "jev-1.13");
193        assert_eq!(meta.latency, std::time::Duration::from_millis(42));
194    }
195}