1use crate::gcode_index::SlicerPlan;
19use crate::records::{EffectiveBounds, Intervention, JobManifest, PrintRecord};
20use crate::watch::{DetectorHealth, DetectorHealthStatus};
21use printobserver_printer_api::{
22 HeaterSnapshot, JobError, JobSnapshot, PrinterSnapshot, PrinterState,
23};
24use printobserver_types::EventPayload;
25use printobserver_types::contract::Sample;
26use printobserver_types::schemars::JsonSchema;
27use printobserver_types::serde::{Deserialize, Serialize};
28use printobserver_types::serde_json::Value;
29use printobserver_types::{
30 EventId, EventKind, EventRecord, ImageRef, PrintId, Reported, Timestamp,
31};
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
35#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
36#[schemars(crate = "printobserver_types::schemars")]
37pub struct PrintContext {
38 pub print: PrintRecord,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub printer: Option<PrinterSnapshot>,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub job: Option<JobSnapshot>,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub manifest: Option<JobManifest>,
49 pub bounds: EffectiveBounds,
51 pub interventions: Vec<Intervention>,
53 pub recent_events: Vec<EventRecord>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub latest_image: Option<ImageRef>,
58 #[serde(default)]
60 pub detector: DetectorHealth,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub slicer: Option<SlicerPlan>,
66}
67
68impl Sample for PrintContext {
69 fn sample_full() -> Self {
70 Self {
71 print: PrintRecord::sample_full(),
72 printer: Some(PrinterSnapshot::sample_full()),
73 job: Some(JobSnapshot::sample_full()),
74 manifest: Some(JobManifest::sample_full()),
75 bounds: EffectiveBounds::sample_full(),
76 interventions: vec![Intervention::sample_full()],
77 recent_events: vec![EventRecord::sample_full()],
78 latest_image: Some(ImageRef::sample_full()),
79 detector: DetectorHealth::sample_full(),
80 slicer: Some(SlicerPlan::sample_full()),
81 }
82 }
83
84 fn sample_minimal() -> Self {
85 Self {
86 print: PrintRecord::sample_minimal(),
87 printer: None,
88 job: None,
89 manifest: None,
90 bounds: EffectiveBounds::sample_full(),
91 interventions: vec![],
92 recent_events: vec![],
93 latest_image: None,
94 detector: DetectorHealth::sample_minimal(),
95 slicer: None,
96 }
97 }
98}
99
100const UNREAD_PAYLOAD_FIELDS: [&str; 8] = [
105 "printer",
106 "job",
107 "assessment",
108 "interval_s",
109 "session_name",
110 "harness_identity",
111 "delivered",
112 "waited_s",
113];
114
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
134#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
135#[schemars(crate = "printobserver_types::schemars")]
136pub struct AgentContext {
137 pub print: AgentPrint,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub printer: Option<AgentPrinter>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub job_error: Option<JobError>,
145 pub bounds: EffectiveBounds,
147 pub interventions: Vec<Intervention>,
149 pub detector: DetectorHealthStatus,
152 pub recent_events: Vec<AgentEvent>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub latest_image: Option<ImageRef>,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub newest_event: Option<EventId>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub slicer: Option<SlicerPlan>,
166}
167
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
170#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
171#[schemars(crate = "printobserver_types::schemars")]
172pub struct AgentPrint {
173 pub id: PrintId,
175 pub state: PrinterState,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub end_reason: Option<String>,
180}
181
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
184#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
185#[schemars(crate = "printobserver_types::schemars")]
186pub struct AgentPrinter {
187 #[serde(default, skip_serializing_if = "Vec::is_empty")]
189 pub tools: Vec<AgentHeater>,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub bed: Option<AgentHeater>,
193}
194
195#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
198#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
199#[schemars(crate = "printobserver_types::schemars")]
200pub struct AgentHeater {
201 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub actual_c: Option<f64>,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub target_c: Option<f64>,
207}
208
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
212#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
213#[schemars(crate = "printobserver_types::schemars")]
214pub struct AgentEvent {
215 pub id: EventId,
217 pub kind: EventKind,
219 pub received_at: Timestamp,
221 #[serde(default, skip_serializing_if = "is_empty_payload")]
224 pub payload: Value,
225}
226
227fn is_empty_payload(payload: &Value) -> bool {
229 match payload {
230 Value::Null => true,
231 Value::Object(fields) => fields.is_empty(),
232 _ => false,
233 }
234}
235
236#[derive(Debug, Clone, Copy)]
239pub struct Since<'events> {
240 pub event: EventId,
242 pub newer: &'events [EventRecord],
244}
245
246impl PrintContext {
247 #[must_use]
250 pub fn for_agent(&self, since: Option<Since<'_>>) -> AgentContext {
251 let heater = |heater: &HeaterSnapshot| AgentHeater {
252 actual_c: in_range(heater.actual_c.as_ref()),
253 target_c: in_range(heater.target_c.as_ref()),
254 };
255 let (events, newest_event) = match since {
256 Some(since) => (
257 since.newer,
258 Some(since.newer.first().map_or(since.event, |newest| newest.id)),
259 ),
260 None => (
261 self.recent_events.as_slice(),
262 self.recent_events.first().map(|newest| newest.id),
263 ),
264 };
265 AgentContext {
266 print: AgentPrint {
267 id: self.print.id,
268 state: self.print.state.clone(),
269 end_reason: self.print.end_reason.clone(),
270 },
271 printer: self.printer.as_ref().map(|printer| AgentPrinter {
272 tools: printer.tools.iter().map(heater).collect(),
273 bed: printer.bed.as_ref().map(heater),
274 }),
275 job_error: self.job.as_ref().and_then(|job| job.error.clone()),
276 bounds: self.bounds.clone(),
277 interventions: self.interventions.clone(),
278 detector: self.detector.status(),
279 recent_events: events.iter().map(agent_event).collect(),
280 latest_image: self.latest_image.clone(),
281 newest_event,
282 slicer: self.slicer.clone(),
283 }
284 }
285}
286
287#[must_use]
292pub fn turn_facts(
293 context: &AgentContext,
294) -> Option<printobserver_types::serde_json::Map<String, Value>> {
295 let mut facts = context.clone();
296 facts.recent_events = unseen_events(&context.recent_events);
297 match printobserver_types::serde_json::to_value(facts) {
298 Ok(Value::Object(fields)) => Some(fields),
299 _ => None,
300 }
301}
302
303#[must_use]
315pub fn unseen_events(events: &[AgentEvent]) -> Vec<AgentEvent> {
316 let is_answer = |event: &AgentEvent| {
317 event.kind.as_str() == <crate::kinds::AgentAssessmentPayload as EventPayload>::KIND
318 };
319 let Some(answered) = events.iter().position(is_answer) else {
320 return events.to_vec();
321 };
322 let (newer, older) = events.split_at(answered);
323 let older = &older[1..];
324 let turn = &older[..older.iter().position(is_answer).unwrap_or(older.len())];
325 let during = events
326 .iter()
327 .find_map(agents_acknowledged_event)
328 .and_then(|answered_event| turn.iter().position(|event| event.id == answered_event))
329 .map_or(turn, |at| &turn[..at]);
330 let own: Vec<&Value> = during
331 .iter()
332 .filter(|event| is_agents_request(event))
333 .filter_map(|event| event.payload.get("action_id"))
334 .collect();
335 let acknowledged: Vec<&Value> = newer
336 .iter()
337 .filter(|event| agents_acknowledged_event(event).is_some())
338 .filter_map(|event| event.payload.get("action_id"))
339 .collect();
340 let mut unseen: Vec<AgentEvent> = newer
341 .iter()
342 .filter(|event| {
343 !event
344 .payload
345 .get("action_id")
346 .is_some_and(|action| acknowledged.contains(&action))
347 })
348 .cloned()
349 .collect();
350 unseen.extend(
351 during
352 .iter()
353 .filter(|event| {
354 !TURNS_OWN_KINDS.contains(&event.kind.as_str())
355 && !event
356 .payload
357 .get("action_id")
358 .is_some_and(|action| own.contains(&action))
359 })
360 .cloned(),
361 );
362 unseen
363}
364
365const TURNS_OWN_KINDS: [&str; 2] = [
368 <crate::kinds::CameraLookPayload as EventPayload>::KIND,
369 <printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
370];
371
372fn is_agents_request(event: &AgentEvent) -> bool {
374 event.kind.as_str() == <crate::kinds::ActionRequestedPayload as EventPayload>::KIND
375 && event
376 .payload
377 .get("actor")
378 .is_some_and(|actor| actor.get("agent").is_some())
379}
380
381fn agents_acknowledged_event(event: &AgentEvent) -> Option<EventId> {
383 if !is_agents_request(event) {
384 return None;
385 }
386 let action = event.payload.get("action")?;
387 if action.get("action")?.as_str()? != "acknowledge_failure" {
388 return None;
389 }
390 printobserver_types::serde_json::from_value(action.get("event_id")?.clone()).ok()
391}
392
393#[must_use]
396pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
397 events
398 .iter()
399 .position(|event| event.id == since)
400 .map(|at| &events[..at])
401}
402
403fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
405 reported
406 .filter(|reported| !reported.out_of_range())
407 .map(Reported::value)
408}
409
410fn agent_event(event: &EventRecord) -> AgentEvent {
412 let mut payload = event.body.payload.clone();
413 if let Value::Object(fields) = &mut payload {
414 for unread in UNREAD_PAYLOAD_FIELDS {
415 fields.remove(unread);
416 }
417 }
418 AgentEvent {
419 id: event.id,
420 kind: event.kind().clone(),
421 received_at: event.received_at,
422 payload,
423 }
424}
425
426impl Sample for AgentContext {
427 fn sample_full() -> Self {
428 PrintContext::sample_full().for_agent(None)
429 }
430
431 fn sample_minimal() -> Self {
432 PrintContext::sample_minimal().for_agent(None)
433 }
434}