everruns-core 0.13.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
// Observer domain types — online scoring of production sessions.
//
// Design Decision: Observers watch real production traffic instead of creating
// synthetic sessions (that is what Evals do). An Observer holds match rules
// (which sessions to score) and scorer configs (how to score them). Scoring is
// asynchronous: matching enqueues pending TraceScore rows, background workers
// claim and complete them.
//
// Design Decision: Scores are derived data with their own lifecycle and live in
// their own table; they are never appended to the immutable session event log.
//
// See specs/online-evals.md for full specification.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::eval::Scorer;
use crate::typed_id::{AgentId, AgentVersionId, HarnessId, ObserverId, SessionId, TraceScoreId};

#[cfg(feature = "openapi")]
use utoipa::ToSchema;

// ============================================
// Observer status
// ============================================

/// Observer lifecycle status. `paused` keeps configuration but stops matching.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum ObserverStatus {
    Active,
    Paused,
    Archived,
    Deleted,
}

impl std::fmt::Display for ObserverStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ObserverStatus::Active => write!(f, "active"),
            ObserverStatus::Paused => write!(f, "paused"),
            ObserverStatus::Archived => write!(f, "archived"),
            ObserverStatus::Deleted => write!(f, "deleted"),
        }
    }
}

impl From<&str> for ObserverStatus {
    fn from(s: &str) -> Self {
        match s {
            "paused" => ObserverStatus::Paused,
            "archived" => ObserverStatus::Archived,
            "deleted" => ObserverStatus::Deleted,
            _ => ObserverStatus::Active,
        }
    }
}

// ============================================
// Match rules
// ============================================

/// Predicates selecting which production sessions an observer scores.
/// All present predicates must match (AND); within a list, any entry matches (OR).
/// An empty match block matches all org traffic. Sessions tagged `eval` are
/// always excluded so synthetic eval-run sessions are never scored.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ObserverMatch {
    /// Match sessions running any of these agents.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<Vec<String>>))]
    pub agent_ids: Option<Vec<AgentId>>,
    /// Match sessions on any of these harnesses.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<Vec<String>>))]
    pub harness_ids: Option<Vec<HarnessId>>,
    /// Match sessions carrying any of these tags.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_tags: Option<Vec<String>>,
}

impl ObserverMatch {
    /// Evaluate predicates against session attributes.
    pub fn matches(
        &self,
        agent_id: Option<AgentId>,
        harness_id: Option<HarnessId>,
        session_tags: &[String],
    ) -> bool {
        if let Some(agent_ids) = &self.agent_ids {
            let Some(agent_id) = agent_id else {
                return false;
            };
            if !agent_ids.contains(&agent_id) {
                return false;
            }
        }
        if let Some(harness_ids) = &self.harness_ids {
            let Some(harness_id) = harness_id else {
                return false;
            };
            if !harness_ids.contains(&harness_id) {
                return false;
            }
        }
        if let Some(tags) = &self.session_tags
            && !tags.iter().any(|t| session_tags.contains(t))
        {
            return false;
        }
        true
    }
}

// ============================================
// Scorer config
// ============================================

/// What slice of the trace a scorer grades. Phase 1 implements `turn` only;
/// `session` and `tool` scopes are specced in specs/online-evals.md.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum ObserverScope {
    #[default]
    Turn,
}

impl std::fmt::Display for ObserverScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ObserverScope::Turn => write!(f, "turn"),
        }
    }
}

/// One scoring rule inside an observer. `key` names the score series in
/// listings and future dashboards; `rule` reuses the eval scorer vocabulary.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ObserverScorerConfig {
    /// Stable name within the observer (score series name).
    pub key: String,
    /// Trace slice this scorer grades.
    #[serde(default)]
    pub scope: ObserverScope,
    /// Scoring rule. `file_contains` is rejected for observers (session
    /// filesystems are not part of the observable trace contract).
    pub rule: Scorer,
}

// ============================================
// Observer entity
// ============================================

/// An observer: online scoring config over production sessions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct Observer {
    /// External identifier (observer_<32-hex>). Shown as "id" in API.
    #[serde(rename = "id")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "observer_01933b5a000070008000000000000001"))]
    pub public_id: ObserverId,
    /// Internal UUID primary key. Never exposed in API.
    #[serde(skip, default = "Uuid::nil")]
    pub internal_id: Uuid,
    /// Organization ID. Internal only.
    #[serde(skip, default)]
    pub org_id: i64,
    /// Display name.
    pub name: String,
    /// Optional description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Which sessions to score.
    #[serde(rename = "match", default)]
    pub match_config: ObserverMatch,
    /// Fraction of matching turns to score (0.0–1.0), applied after match.
    pub sampling_rate: f64,
    /// Scoring rules.
    pub scorers: Vec<ObserverScorerConfig>,
    /// Lifecycle status.
    pub status: ObserverStatus,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archived_at: Option<DateTime<Utc>>,
}

// ============================================
// Trace scores
// ============================================

/// Lifecycle of one trace score. `pending` rows double as the scoring queue.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum TraceScoreStatus {
    Pending,
    Scoring,
    Completed,
    Errored,
    Skipped,
}

impl std::fmt::Display for TraceScoreStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TraceScoreStatus::Pending => write!(f, "pending"),
            TraceScoreStatus::Scoring => write!(f, "scoring"),
            TraceScoreStatus::Completed => write!(f, "completed"),
            TraceScoreStatus::Errored => write!(f, "errored"),
            TraceScoreStatus::Skipped => write!(f, "skipped"),
        }
    }
}

impl From<&str> for TraceScoreStatus {
    fn from(s: &str) -> Self {
        match s {
            "scoring" => TraceScoreStatus::Scoring,
            "completed" => TraceScoreStatus::Completed,
            "errored" => TraceScoreStatus::Errored,
            "skipped" => TraceScoreStatus::Skipped,
            _ => TraceScoreStatus::Pending,
        }
    }
}

/// One score produced by an observer scorer for one trace slice. Linked back
/// to the exact session/turn it graded; agent/harness identifiers are
/// denormalized at scoring time for aggregation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct TraceScore {
    /// External identifier (score_<32-hex>). Shown as "id" in API.
    #[serde(rename = "id")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, example = "score_01933b5a000070008000000000000001"))]
    pub public_id: TraceScoreId,
    /// Internal UUID primary key. Never exposed in API.
    #[serde(skip, default = "Uuid::nil")]
    pub internal_id: Uuid,
    /// Organization ID. Internal only.
    #[serde(skip, default)]
    pub org_id: i64,
    /// Observer that produced this score.
    #[cfg_attr(feature = "openapi", schema(value_type = String))]
    pub observer_id: ObserverId,
    /// Scorer key within the observer.
    pub scorer_key: String,
    /// Session this score grades.
    #[cfg_attr(feature = "openapi", schema(value_type = String))]
    pub session_id: SessionId,
    /// Turn this score grades (turn scope).
    pub turn_id: String,
    /// Agent active in the session at scoring time.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
    pub agent_id: Option<AgentId>,
    /// Agent version active in the session at scoring time.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
    pub agent_version_id: Option<AgentVersionId>,
    /// Harness of the session.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
    pub harness_id: Option<HarnessId>,
    pub status: TraceScoreStatus,
    /// Whether the scorer passed (set when completed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pass: Option<bool>,
    /// Score value 0.0–1.0 (set when completed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<f64>,
    /// Human-readable explanation (set when completed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Error details if errored.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

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

    #[test]
    fn observer_status_roundtrip() {
        for (s, v) in [
            ("active", ObserverStatus::Active),
            ("paused", ObserverStatus::Paused),
            ("archived", ObserverStatus::Archived),
            ("deleted", ObserverStatus::Deleted),
        ] {
            assert_eq!(ObserverStatus::from(s), v);
            assert_eq!(v.to_string(), s);
        }
        assert_eq!(ObserverStatus::from("unknown"), ObserverStatus::Active);
    }

    #[test]
    fn trace_score_status_roundtrip() {
        for (s, v) in [
            ("pending", TraceScoreStatus::Pending),
            ("scoring", TraceScoreStatus::Scoring),
            ("completed", TraceScoreStatus::Completed),
            ("errored", TraceScoreStatus::Errored),
            ("skipped", TraceScoreStatus::Skipped),
        ] {
            assert_eq!(TraceScoreStatus::from(s), v);
            assert_eq!(v.to_string(), s);
        }
        assert_eq!(TraceScoreStatus::from("unknown"), TraceScoreStatus::Pending);
    }

    #[test]
    fn empty_match_matches_everything() {
        let m = ObserverMatch::default();
        assert!(m.matches(None, None, &[]));
        assert!(m.matches(Some(AgentId::new()), Some(HarnessId::new()), &["x".into()]));
    }

    #[test]
    fn match_agent_predicate() {
        let agent = AgentId::new();
        let m = ObserverMatch {
            agent_ids: Some(vec![agent]),
            ..Default::default()
        };
        assert!(m.matches(Some(agent), None, &[]));
        assert!(!m.matches(Some(AgentId::new()), None, &[]));
        assert!(!m.matches(None, None, &[]));
    }

    #[test]
    fn match_harness_predicate() {
        let harness = HarnessId::new();
        let m = ObserverMatch {
            harness_ids: Some(vec![harness]),
            ..Default::default()
        };
        assert!(m.matches(None, Some(harness), &[]));
        assert!(!m.matches(None, Some(HarnessId::new()), &[]));
        assert!(!m.matches(None, None, &[]));
    }

    #[test]
    fn match_tags_any_of() {
        let m = ObserverMatch {
            session_tags: Some(vec!["prod".into(), "beta".into()]),
            ..Default::default()
        };
        assert!(m.matches(None, None, &["beta".into()]));
        assert!(!m.matches(None, None, &["other".into()]));
        assert!(!m.matches(None, None, &[]));
    }

    #[test]
    fn match_predicates_are_anded() {
        let agent = AgentId::new();
        let m = ObserverMatch {
            agent_ids: Some(vec![agent]),
            session_tags: Some(vec!["prod".into()]),
            ..Default::default()
        };
        assert!(m.matches(Some(agent), None, &["prod".into()]));
        assert!(!m.matches(Some(agent), None, &[]));
        assert!(!m.matches(None, None, &["prod".into()]));
    }

    #[test]
    fn scorer_config_serde_defaults_scope() {
        let json = serde_json::json!({
            "key": "greeting",
            "rule": { "type": "contains", "text": "hello" }
        });
        let config: ObserverScorerConfig = serde_json::from_value(json).unwrap();
        assert_eq!(config.scope, ObserverScope::Turn);
        assert_eq!(config.key, "greeting");
    }

    #[test]
    fn observer_serde_skips_internal_fields() {
        let observer = Observer {
            public_id: ObserverId::from_uuid(Uuid::nil()),
            internal_id: Uuid::nil(),
            org_id: 1,
            name: "test".into(),
            description: None,
            match_config: ObserverMatch::default(),
            sampling_rate: 0.1,
            scorers: vec![],
            status: ObserverStatus::Active,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            archived_at: None,
        };
        let json = serde_json::to_value(&observer).unwrap();
        assert!(json.get("id").is_some());
        assert!(json.get("match").is_some());
        assert!(json.get("internal_id").is_none());
        assert!(json.get("org_id").is_none());
        assert_eq!(json["sampling_rate"], 0.1);
    }
}