Skip to main content

printobserver_core/
context.rs

1//! The one aggregate a caller and the agent both read.
2//!
3//! [`PrintContext`] is the supervision domain's own view of one print: the
4//! record, the printer and job as the printer port last reported them, the
5//! manifest and the bounds in force, the interventions still active, the
6//! events most recently written down — the print's own, and what the printer
7//! watch recorded of the machine since the print opened — the failure
8//! detector's health, and what the slicer planned at the job's current file
9//! position ([`crate::gcode_index`]). The loop collects it when it handles an
10//! event, holds it for the turn that event prompts, and answers it to the
11//! `context` operation, so what the agent reasons about is the state the event
12//! was handled at rather than whatever the machine has drifted to since.
13//!
14//! It is declared here rather than centrally because every field of it is
15//! this domain's to collect: a domain that adds a fact a turn should see edits
16//! this crate and regenerates the clients, and nothing central.
17
18use 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/// Everything a supervision turn is given about one print.
34#[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    /// The print itself.
39    pub print: PrintRecord,
40    /// The printer, when a snapshot could be taken.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub printer: Option<PrinterSnapshot>,
43    /// The job, when a snapshot could be taken.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub job: Option<JobSnapshot>,
46    /// The manifest, when the print has one.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub manifest: Option<JobManifest>,
49    /// The limits in force, so that the agent can see them before it asks.
50    pub bounds: EffectiveBounds,
51    /// The interventions still active.
52    pub interventions: Vec<Intervention>,
53    /// A bounded list of this print's events, newest first.
54    pub recent_events: Vec<EventRecord>,
55    /// The most recent image, when there is one.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub latest_image: Option<ImageRef>,
58    /// The failure detector's health, and since when it has been so.
59    #[serde(default)]
60    pub detector: DetectorHealth,
61    /// What the slicer planned at the job's current file position, read from
62    /// the print's own G-code: absent when the file could not be read, or the
63    /// job is not this print's.
64    #[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
100/// The payload fields a context's recent events leave out: the printer and job
101/// snapshots an observation took, which the context states once as they are
102/// now; the agent's own assessment, which its conversation already holds; and
103/// the bookkeeping no supervision decision reads.
104const 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/// What a supervision turn reads about one print: [`PrintContext`] with each
116/// fact stated once, as it is now, and nothing no supervision decision reads.
117///
118/// Left out of it, each because no step of the skill, no check and no recorded
119/// case decides anything by it: the print's file, provider and times; the
120/// printer's and the job's own states (the print states it once); every heater's
121/// offset, the chamber and the time they were read; the printer's reported
122/// feedrate, flowrate and fan (the slicer's plan states the flow and fan in
123/// force, and no step reads the feedrate); the job's file, size, progress, time
124/// and position (the plan states where the print is); the manifest (its limits
125/// are the bounds); and the detector's health beyond its status — since when,
126/// and why — which only the status read carries.
127///
128/// The printer and the job are stated here and nowhere in the events; each
129/// event is what happened, when, and what it changed; and asked `since` an
130/// event, only the events newer than it are carried, so a turn that has read
131/// the rest is not handed them again. `newest_event` is what the next read
132/// asks `since`.
133#[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    /// The print.
138    pub print: AgentPrint,
139    /// The printer's heaters now, when they could be read.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub printer: Option<AgentPrinter>,
142    /// The error the job stopped on, when it stopped on one.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub job_error: Option<JobError>,
145    /// The limits in force, so that the agent can see them before it asks.
146    pub bounds: EffectiveBounds,
147    /// The interventions still active.
148    pub interventions: Vec<Intervention>,
149    /// What the failure detector's status is for this print: whether it is
150    /// scoring the print and has flagged it, or what it is otherwise.
151    pub detector: DetectorHealthStatus,
152    /// This print's events newer than the one asked `since`, or its recent
153    /// ones when none was named, newest first.
154    pub recent_events: Vec<AgentEvent>,
155    /// The most recent image, whose path is answered beside the context and
156    /// whose record states its digest.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub latest_image: Option<ImageRef>,
159    /// The newest event of this print's, which a later read asks `since`:
160    /// absent only when the print has none.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub newest_event: Option<EventId>,
163    /// What the slicer planned at the job's current file position.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub slicer: Option<SlicerPlan>,
166}
167
168/// The print a context is about.
169#[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    /// Its identifier.
174    pub id: PrintId,
175    /// What the printer was last found doing with it, or the state it ended in.
176    pub state: PrinterState,
177    /// Why it ended, once it has.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub end_reason: Option<String>,
180}
181
182/// The printer's heaters as they are now.
183#[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    /// Each tool's heater, in order.
188    #[serde(default, skip_serializing_if = "Vec::is_empty")]
189    pub tools: Vec<AgentHeater>,
190    /// The bed's heater, when it has one.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub bed: Option<AgentHeater>,
193}
194
195/// One heater, in degrees Celsius: each reading absent when the printer did not
196/// report it, or reported one outside what a heater can read.
197#[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    /// The temperature it is at.
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub actual_c: Option<f64>,
204    /// The temperature it is driving towards.
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub target_c: Option<f64>,
207}
208
209/// One event of the print's, as a turn reads it: what happened, when, and the
210/// facts it changed.
211#[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    /// Its identifier, which a later read asks `since`.
216    pub id: EventId,
217    /// What kind of event it is.
218    pub kind: EventKind,
219    /// When it was received.
220    pub received_at: Timestamp,
221    /// What it carried, less the snapshots the context states once, the
222    /// agent's own assessment and the bookkeeping no decision reads.
223    #[serde(default, skip_serializing_if = "is_empty_payload")]
224    pub payload: Value,
225}
226
227/// Whether a payload says nothing.
228fn 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/// The events a context read asked `since` one carries: that event, and the
237/// print's events newer than it, newest first.
238#[derive(Debug, Clone, Copy)]
239pub struct Since<'events> {
240    /// The event named.
241    pub event: EventId,
242    /// Every event of the print's newer than it, newest first.
243    pub newer: &'events [EventRecord],
244}
245
246impl PrintContext {
247    /// What a supervision turn reads of this context: its recent events, or
248    /// those `since` names when it names any.
249    #[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/// The facts a supervision turn is handed up front: the context read as the
288/// turn began, as [`AgentContext`] answers it — and no field that answer does
289/// not carry — with its events cut to [`unseen_events`]: what happened that the
290/// agent has not been shown, which its own conversation does not hold.
291#[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/// Of a print's events, newest first, those the agent has not been shown:
304/// every event newer than its last answer, and every one that arrived while
305/// the turn behind that answer ran — after the event that turn answered, which
306/// its acknowledgement names — and was not that turn's own doing: a person's
307/// resume taken as the agent answered, or the printer's own report. The turn's
308/// own requests, their outcomes and what it recorded of itself are left out, and
309/// so is the acknowledgement written from that answer after the turn ended, with
310/// its outcome: the conversation already holds the answer it was written from. A
311/// print the agent has not answered on keeps every event; one whose answered
312/// event cannot be found keeps every event back to the answer before, its
313/// own aside, because one shown twice costs less than one never shown.
314#[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
365/// What a turn records of itself as it runs: the looks it took and the session
366/// it opened, which it already saw or has no use for.
367const TURNS_OWN_KINDS: [&str; 2] = [
368    <crate::kinds::CameraLookPayload as EventPayload>::KIND,
369    <printobserver_supervisor_api::SupervisionSessionOpenedPayload as EventPayload>::KIND,
370];
371
372/// Whether an event is a request the agent made.
373fn 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
381/// The event an acknowledgement the agent asked for names, when this is one.
382fn 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/// The events newer than `since`, newest first, when `events` — newest first —
394/// holds it.
395#[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
403/// A reading in range, as its value alone.
404fn in_range(reported: Option<&Reported<f64>>) -> Option<f64> {
405    reported
406        .filter(|reported| !reported.out_of_range())
407        .map(Reported::value)
408}
409
410/// One event, as a turn reads it.
411fn 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}