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]
313pub fn unseen_events(events: &[AgentEvent]) -> Vec<AgentEvent> {
314 let is_answer = |event: &AgentEvent| {
315 event.kind.as_str() == <crate::kinds::AgentAssessmentPayload as EventPayload>::KIND
316 };
317 let Some(answered) = events.iter().position(is_answer) else {
318 return events.to_vec();
319 };
320 let (newer, older) = events.split_at(answered);
321 let older = &older[1..];
322 let turn = &older[..older.iter().position(is_answer).unwrap_or(older.len())];
323 let during = events
324 .iter()
325 .find_map(agents_acknowledged_event)
326 .and_then(|answered_event| turn.iter().position(|event| event.id == answered_event))
327 .map_or(turn, |at| &turn[..at]);
328 let own: Vec<&Value> = during
329 .iter()
330 .filter(|event| is_agents_request(event))
331 .filter_map(|event| event.payload.get("action_id"))
332 .collect();
333 let mut unseen = newer.to_vec();
334 unseen.extend(
335 during
336 .iter()
337 .filter(|event| {
338 !TURNS_OWN_KINDS.contains(&event.kind.as_str())
339 && !event
340 .payload
341 .get("action_id")
342 .is_some_and(|action| own.contains(&action))
343 })
344 .cloned(),
345 );
346 unseen
347}
348
349const TURNS_OWN_KINDS: [&str; 2] = [
352 <crate::kinds::CameraLookPayload as EventPayload>::KIND,
353 <printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
354];
355
356fn is_agents_request(event: &AgentEvent) -> bool {
358 event.kind.as_str() == <crate::kinds::ActionRequestedPayload as EventPayload>::KIND
359 && event
360 .payload
361 .get("actor")
362 .is_some_and(|actor| actor.get("agent").is_some())
363}
364
365fn agents_acknowledged_event(event: &AgentEvent) -> Option<EventId> {
367 if !is_agents_request(event) {
368 return None;
369 }
370 let action = event.payload.get("action")?;
371 if action.get("action")?.as_str()? != "acknowledge_failure" {
372 return None;
373 }
374 printobserver_types::serde_json::from_value(action.get("event_id")?.clone()).ok()
375}
376
377#[must_use]
380pub fn newer_than(events: &[EventRecord], since: EventId) -> Option<&[EventRecord]> {
381 events
382 .iter()
383 .position(|event| event.id == since)
384 .map(|at| &events[..at])
385}
386
387fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
389 reported
390 .filter(|reported| !reported.out_of_range())
391 .map(Reported::value)
392}
393
394fn agent_event(event: &EventRecord) -> AgentEvent {
396 let mut payload = event.body.payload.clone();
397 if let Value::Object(fields) = &mut payload {
398 for unread in UNREAD_PAYLOAD_FIELDS {
399 fields.remove(unread);
400 }
401 }
402 AgentEvent {
403 id: event.id,
404 kind: event.kind().clone(),
405 received_at: event.received_at,
406 payload,
407 }
408}
409
410impl Sample for AgentContext {
411 fn sample_full() -> Self {
412 PrintContext::sample_full().for_agent(None)
413 }
414
415 fn sample_minimal() -> Self {
416 PrintContext::sample_minimal().for_agent(None)
417 }
418}