Skip to main content

printobserver_server/
config.rs

1//! The one configuration file a running supervisor reads, and its validation.
2//!
3//! # Every field this program takes is declared once, here
4//!
5//! [`ConfigField`] is that declaration: one variant per configured value, each
6//! carrying the dotted key it is spelled under. Two things read it rather than
7//! restating it — the refusal a bad value produces names its field through it,
8//! and this crate's own tier walks it, driving a server against a configuration
9//! in which each field in turn is unacceptable. A field added to the shapes
10//! below and not to [`ConfigField::ALL`] fails that tier's own coverage check,
11//! so the walk cannot fall behind the type.
12//!
13//! # Validation happens at startup, and names the field
14//!
15//! A value that cannot work is refused where it is configured rather than at
16//! the first request that needs it, and the refusal carries the field's own key
17//! so an operator editing the file knows which line to change. That includes
18//! the two values only the machine can rule on: an `OctoPrint` address nothing
19//! answers at and a key that instance refuses are both configuration mistakes,
20//! and [`crate::Server::start`] refuses them naming
21//! [`ConfigField::OctoprintUrl`] and [`ConfigField::OctoprintApiKey`].
22//!
23//! # The ingress answer bound
24//!
25//! `Obico`'s webhook notification plugin posts best-effort with a short timeout
26//! and does not retry, so this server answers its ingress before the handling
27//! completes and inside a bound it declares here. The shipped default is
28//! [`DEFAULT_INGRESS_ANSWER_BOUND_MS`] and the timeout it must stay below is
29//! [`OBICO_POSTING_TIMEOUT_MS`]; `AGENTS.md`'s "The Obico ingress answer bound"
30//! records that number, where it was read and why the default is where it is,
31//! and `just check-repo` refuses a tree in which the two disagree.
32//!
33//! # The operator's credential, by its verifier
34//!
35//! Every request beneath the versioned prefix carries one credential. The
36//! operator's is checked against a [`CredentialVerifier`] — the SHA-256 of the
37//! credential, written `sha256:<64 lowercase hex>` — which `api.credential_verifier`
38//! names, so the server holds nothing a supervision turn reading its files
39//! could authenticate with. The plaintext lives with the operator, in the
40//! client configuration `printobserver credential issue` writes.
41//!
42//! `api.credential`, a plaintext credential, is still read for an installation
43//! that wrote one, and admitted until it is replaced; the composition root warns
44//! on every start that it is there. Either way a credential is held in a type
45//! neither rendering of which shows it, and is compared in constant time.
46//!
47//! # The periodic observation
48//!
49//! `supervisor.observation_interval_s` is how often every active print is given
50//! a periodic observation and its agent a turn on it, whether or not the
51//! detector has alerted. Left out it is
52//! [`DEFAULT_OBSERVATION_INTERVAL_S`] — two minutes — and zero is refused,
53//! because an interval of nothing is a turn started the moment the last one
54//! returns.
55//!
56//! # The printer watch
57//!
58//! `supervisor.printer_poll_s` is how often the printer watch reads the machine
59//! — from 5 to 300 seconds, fifteen when left out — whether or not a print is
60//! active, and `supervisor.unattended_window_s` how long after a print ends
61//! `interrupted` or `failed` the printer heating or moving on its own is
62//! recorded — from 60 to 86400 seconds, an hour when left out. A value outside
63//! either range is refused naming its key.
64//!
65//! # Compaction
66//!
67//! `supervisor.idle_compact_tokens` is the conversation size, in tokens, at or
68//! above which a print's session is compacted while no turn of it runs, and
69//! `supervisor.auto_compact_tokens` the size at which the harness compacts a
70//! session on its own during a turn, set through `OneHarness`'s
71//! harness-agnostic setting of that name. Each is a whole number from 1, and
72//! each left out does nothing.
73//!
74//! # The harness check
75//!
76//! `supervisor.check_turn_timeout_s` is how long the one turn a harness check
77//! runs may take before the check answers that it timed out — from 1 to 900
78//! seconds, [`DEFAULT_CHECK_TURN_TIMEOUT_S`] when left out. A value outside
79//! that range is refused naming its key.
80//!
81//! # The camera and `Obico`'s own API
82//!
83//! Both are optional. `camera.snapshot_url` is where a look fetches a fresh
84//! frame; without it a look carries the printer's state and no frame.
85//! `obico.url` and `obico.access_token` are given together or not at all: they
86//! are how a print the detector paused and the agent adjusted is acknowledged
87//! to `Obico`, which re-arms its detection. Each address must be an `http` or
88//! `https` URL, and the token is held in a type whose debug form never shows
89//! it, so no refusal or log line this program writes can carry it.
90//! `obico.ml_api_url` is the failure detector's own service, whose
91//! unauthenticated health check is asked during every print; without it the
92//! detector's health check is never asked. With `obico.url` and
93//! `obico.access_token`, `Obico`'s own record of the printer's live prediction
94//! is read once per observation interval, from the printer `obico.printer_id`
95//! names — a whole number from 1 — or, left out, the one the last body `Obico`
96//! posted named; that is what says the detector is scoring a print.
97//! `vision.blank_frame_max_stddev` is the
98//! grey-level spread at or below which a frame is blank — from 1 to 128, 36.5
99//! when left out.
100//!
101//! # Recovery
102//!
103//! `[recovery]` states the printer's own facts a recovery action is checked
104//! against — `away_from_bed` (`z_plus` or `z_minus`), `max_z_mm`,
105//! `max_lift_mm` (50 when left out), `clearance_margin_mm` (5 when left out),
106//! `park_xy`, `z_home_xy` and `z_home_sweeps_bed`. Left out, every recovery
107//! action is refused as not configured; written, every key without a default
108//! is required. `[policy.recovery]` says who may ask for which: `operator`,
109//! `agent` and `asserting`, by default every action, none, and the operator
110//! alone. Granting `recover_home_z` to the agent, or letting the agent's word
111//! count as clearance, is refused naming the key, and so is every value
112//! outside the range its key admits.
113//!
114//! # The spool check
115//!
116//! `[spools]` is optional, and so is every key in it: `preflight` is what a
117//! start does when the loaded spool is short, unverified or the file has no
118//! analysis — `refuse`, `warn` or `off` — `buffer_percent` and `buffer_min_g`
119//! the margin asked beyond what a print needs, and `analysis_wait_seconds` how
120//! long a start waits for `OctoPrint`'s analysis of a file that has none yet.
121//! Each left out takes the supervision core's own default, and a negative
122//! figure or a mode outside the three is refused naming its key. The same mode
123//! governs the material and sheet checks a start is held to beside it.
124//!
125//! # The sheet table
126//!
127//! `[sheets.allowed]` is optional: one key per material, each listing the
128//! build sheets a print of that material may go down on, as the ids a start's
129//! manifest declares in `sheet`. Written, it replaces the defaults
130//! ([`DEFAULT_SHEETS`](printobserver_core::DEFAULT_SHEETS)) whole; left out,
131//! those defaults apply. A blank material or sheet, a material listing no
132//! sheet, or two materials differing only in case is refused naming
133//! `sheets.allowed`.
134
135use core::num::NonZeroU64;
136use std::net::SocketAddr;
137use std::path::{Path, PathBuf};
138
139use printobserver_core::{
140    ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
141    PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SheetTable,
142    SpoolPolicy,
143};
144use printobserver_obico::{
145    AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
146    ObicoPrinterId,
147};
148use printobserver_octoprint::{FanSupport, OctoPrintConfig};
149use printobserver_oneharness::{HarnessIdentity, ModelName};
150use printobserver_types::schemars::JsonSchema;
151use printobserver_types::serde::{Deserialize, Serialize};
152use printobserver_vision_api::WebAddress;
153
154/// The answer bound this repository ships, in milliseconds.
155///
156/// A fifth of [`OBICO_POSTING_TIMEOUT_MS`]. The margin is deliberate: the
157/// supported host is a small ARM board beside the printer, and a bound set just
158/// under the producer's timeout would be exceeded by the first slow moment on
159/// it — after which `Obico` drops the alert, because its posting does not retry.
160pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
161
162/// How often every active print is observed, in seconds, when the
163/// configuration names no interval: the core's own default.
164pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
165    printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
166
167/// How often the printer watch reads the machine, in seconds, when the
168/// configuration names no poll: the core's own default.
169pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
170
171/// The least and the most seconds `supervisor.printer_poll_s` admits.
172pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
173
174/// How long after an unfinished ending activity is recorded, in seconds, when
175/// the configuration names no window: the core's own default.
176pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
177    printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
178
179/// The least and the most seconds `supervisor.unattended_window_s` admits.
180pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
181
182/// How long a harness check's one turn may take, in seconds, when the
183/// configuration names no bound: long enough for a signed-in harness to answer
184/// one line over a slow link from a small board, and short enough that a
185/// client's preflight waiting on it is told within two minutes.
186pub const DEFAULT_CHECK_TURN_TIMEOUT_S: u64 = 120;
187
188/// The least and the most seconds `supervisor.check_turn_timeout_s` admits:
189/// up to a supervision turn's own bound, which no check needs to outlast.
190pub const CHECK_TURN_TIMEOUT_RANGE_S: (u64, u64) = (1, 900);
191
192/// The timeout `Obico`'s own webhook notification plugin posts under.
193///
194/// Read from the `Obico` release the `obico-fixture` node stands up — revision
195/// `49c0bc7001a3fd8d56297fc3032ba287bfe1d50b`,
196/// `backend/notifications/plugins/webhook/__init__.py`, whose `execute_webhook`
197/// takes `timeout: float = 5.0` and calls `raise_for_status` with no retry.
198/// This repository's claim about an external producer; what reconciles it
199/// against a live `Obico` is the scheduled `Obico` tier.
200pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
201
202/// The directory under the state directory this server materializes the
203/// supervising agent's prompt template and assessment schema into. The skill
204/// is not among them: it is installed with [`SKILL_INSTALL`] and configured by
205/// `supervisor.skill_path`.
206pub const ASSETS_DIRECTORY: &str = "assets";
207
208/// How the supervising agent's skill is installed, and what names it after.
209///
210/// This program carries no skill of its own: the skill is the Agent Skill this
211/// repository publishes, installed as any other is, and every refusal of
212/// `supervisor.skill_path` says so, because it is the one instruction an
213/// operator whose configuration predates that needs.
214pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
215     nickderobertis/printobserver printobserver --dir <dir>`, and \
216     `supervisor.skill_path` names the installed `SKILL.md`, \
217     `<dir>/printobserver/SKILL.md`";
218
219/// Every value this program is configured with, and the key it is spelled under.
220///
221/// The walk in this crate's tier is over this array, and the array is compared
222/// against the configuration shapes' own declared properties, so neither can
223/// grow a field the other does not know about.
224#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
225pub enum ConfigField {
226    /// Where the store, the images and the sessions live.
227    StateDir,
228    /// The address the API and the ingress are served on.
229    Listen,
230    /// Where the `OctoPrint` instance answers.
231    OctoprintUrl,
232    /// The key that instance authenticates every request by.
233    OctoprintApiKey,
234    /// Whether the machine has a part-cooling fan this server may command.
235    OctoprintFan,
236    /// The operator's safety envelope.
237    SafetyEnvelope,
238    /// The harness identity supervision turns run on.
239    Harness,
240    /// The model turns are pinned to, when one is pinned.
241    Model,
242    /// The `PrintObserver` skill sent as every turn's system prompt.
243    SkillPath,
244    /// The prompt template one turn fills.
245    PromptTemplatePath,
246    /// How often every active print is observed, in seconds.
247    ObservationIntervalS,
248    /// How often the printer watch reads the machine, in seconds.
249    PrinterPollS,
250    /// How long after an unfinished ending the printer acting on its own is
251    /// recorded, in seconds.
252    UnattendedWindowS,
253    /// The conversation size at which the harness compacts a session during a
254    /// turn, in tokens.
255    AutoCompactTokens,
256    /// The conversation size at or above which a session is compacted while
257    /// idle, in tokens.
258    IdleCompactTokens,
259    /// How long a harness check's one turn may take, in seconds.
260    CheckTurnTimeoutS,
261    /// How long the ingress may take to answer, in milliseconds.
262    IngressAnswerBoundMs,
263    /// The shared secret the ingress requires of every post.
264    IngressSharedSecret,
265    /// A plaintext operator credential, read for an installation that wrote
266    /// one until it is replaced by its verifier.
267    ApiCredential,
268    /// The verifier the operator's credential is checked against.
269    ApiCredentialVerifier,
270    /// Where a fresh frame of the print is fetched from, when a camera is
271    /// configured.
272    CameraSnapshotUrl,
273    /// The camera's calibration file, when one is configured.
274    CameraCalibration,
275    /// Where `Obico`'s own API answers, when it is configured.
276    ObicoUrl,
277    /// The bearer token `Obico`'s API is reached with.
278    ObicoAccessToken,
279    /// Where the failure detector's own service answers its health check.
280    ObicoMlApiUrl,
281    /// Which of `Obico`'s printers its record of the print is read from.
282    ObicoPrinterId,
283    /// The grey-level spread at or below which a camera frame is blank.
284    VisionBlankFrameMaxStddev,
285    /// What a start does when the spool check finds a problem.
286    SpoolsPreflight,
287    /// The margin asked beyond a print's requirement, as a percentage of it.
288    SpoolsBufferPercent,
289    /// The least margin asked, in grams.
290    SpoolsBufferMinG,
291    /// How long a start waits for a file's analysis, in seconds.
292    SpoolsAnalysisWaitSeconds,
293    /// Which build sheets each material may be printed on.
294    SheetsAllowed,
295    /// Which way along Z moves the nozzle away from the bed.
296    RecoveryAwayFromBed,
297    /// The highest Z the machine reaches, in millimetres.
298    RecoveryMaxZMm,
299    /// The longest lift one recovery may ask for, in millimetres.
300    RecoveryMaxLiftMm,
301    /// How far above the tallest part the nozzle must be, in millimetres.
302    RecoveryClearanceMarginMm,
303    /// Where a park moves the head, in X and Y.
304    RecoveryParkXy,
305    /// Where the machine homes Z, in X and Y.
306    RecoveryZHomeXy,
307    /// Whether homing Z brings a gantry down over the whole bed.
308    RecoveryZHomeSweepsBed,
309    /// The recovery actions the operator may ask for.
310    PolicyRecoveryOperator,
311    /// The recovery actions the agent may ask for.
312    PolicyRecoveryAgent,
313    /// The actor classes whose clearance assertions count.
314    PolicyRecoveryAsserting,
315}
316
317impl ConfigField {
318    /// Every field this program takes, and there is no other.
319    pub const ALL: [Self; 42] = [
320        Self::StateDir,
321        Self::Listen,
322        Self::OctoprintUrl,
323        Self::OctoprintApiKey,
324        Self::OctoprintFan,
325        Self::SafetyEnvelope,
326        Self::Harness,
327        Self::Model,
328        Self::SkillPath,
329        Self::PromptTemplatePath,
330        Self::ObservationIntervalS,
331        Self::PrinterPollS,
332        Self::UnattendedWindowS,
333        Self::AutoCompactTokens,
334        Self::IdleCompactTokens,
335        Self::CheckTurnTimeoutS,
336        Self::IngressAnswerBoundMs,
337        Self::IngressSharedSecret,
338        Self::ApiCredential,
339        Self::ApiCredentialVerifier,
340        Self::CameraSnapshotUrl,
341        Self::CameraCalibration,
342        Self::ObicoUrl,
343        Self::ObicoAccessToken,
344        Self::ObicoMlApiUrl,
345        Self::ObicoPrinterId,
346        Self::VisionBlankFrameMaxStddev,
347        Self::SpoolsPreflight,
348        Self::SpoolsBufferPercent,
349        Self::SpoolsBufferMinG,
350        Self::SpoolsAnalysisWaitSeconds,
351        Self::SheetsAllowed,
352        Self::RecoveryAwayFromBed,
353        Self::RecoveryMaxZMm,
354        Self::RecoveryMaxLiftMm,
355        Self::RecoveryClearanceMarginMm,
356        Self::RecoveryParkXy,
357        Self::RecoveryZHomeXy,
358        Self::RecoveryZHomeSweepsBed,
359        Self::PolicyRecoveryOperator,
360        Self::PolicyRecoveryAgent,
361        Self::PolicyRecoveryAsserting,
362    ];
363
364    /// The dotted key this field is spelled under in the configuration file.
365    #[must_use]
366    pub const fn key(self) -> &'static str {
367        match self {
368            Self::StateDir => "state_dir",
369            Self::Listen => "listen",
370            Self::OctoprintUrl => "octoprint.url",
371            Self::OctoprintApiKey => "octoprint.api_key",
372            Self::OctoprintFan => "octoprint.fan",
373            Self::SafetyEnvelope => "safety",
374            Self::Harness => "supervisor.harness",
375            Self::Model => "supervisor.model",
376            Self::SkillPath => "supervisor.skill_path",
377            Self::PromptTemplatePath => "supervisor.prompt_template_path",
378            Self::ObservationIntervalS => "supervisor.observation_interval_s",
379            Self::PrinterPollS => "supervisor.printer_poll_s",
380            Self::UnattendedWindowS => "supervisor.unattended_window_s",
381            Self::AutoCompactTokens => "supervisor.auto_compact_tokens",
382            Self::IdleCompactTokens => "supervisor.idle_compact_tokens",
383            Self::CheckTurnTimeoutS => "supervisor.check_turn_timeout_s",
384            Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
385            Self::IngressSharedSecret => "ingress.shared_secret",
386            Self::ApiCredential => "api.credential",
387            Self::ApiCredentialVerifier => "api.credential_verifier",
388            Self::CameraSnapshotUrl => "camera.snapshot_url",
389            Self::CameraCalibration => "camera.calibration",
390            Self::ObicoUrl => "obico.url",
391            Self::ObicoAccessToken => "obico.access_token",
392            Self::ObicoMlApiUrl => "obico.ml_api_url",
393            Self::ObicoPrinterId => "obico.printer_id",
394            Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
395            Self::SpoolsPreflight => "spools.preflight",
396            Self::SpoolsBufferPercent => "spools.buffer_percent",
397            Self::SpoolsBufferMinG => "spools.buffer_min_g",
398            Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
399            Self::SheetsAllowed => "sheets.allowed",
400            Self::RecoveryAwayFromBed => "recovery.away_from_bed",
401            Self::RecoveryMaxZMm => "recovery.max_z_mm",
402            Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
403            Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
404            Self::RecoveryParkXy => "recovery.park_xy",
405            Self::RecoveryZHomeXy => "recovery.z_home_xy",
406            Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
407            Self::PolicyRecoveryOperator => "policy.recovery.operator",
408            Self::PolicyRecoveryAgent => "policy.recovery.agent",
409            Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
410        }
411    }
412}
413
414impl core::fmt::Display for ConfigField {
415    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
416        formatter.write_str(self.key())
417    }
418}
419
420/// Why this server will not start under the configuration it was given.
421///
422/// Every variant names the field it is about, because the answer an operator
423/// needs is which line of the file to change.
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub enum ConfigError {
426    /// The file could not be read at all.
427    Unreadable {
428        /// The path that was named.
429        path: PathBuf,
430        /// What went wrong reading it.
431        detail: String,
432    },
433    /// The file is not the document this program takes.
434    Unparsable {
435        /// The path that was named.
436        path: PathBuf,
437        /// What could not be parsed, in the parser's own words.
438        detail: String,
439    },
440    /// One field carries a value this program cannot accept.
441    Field {
442        /// The field it is about.
443        field: ConfigField,
444        /// Why the value cannot be accepted.
445        detail: String,
446    },
447}
448
449impl ConfigError {
450    /// The field this refusal is about, when it is about one.
451    #[must_use]
452    pub const fn field(&self) -> Option<ConfigField> {
453        match self {
454            Self::Field { field, .. } => Some(*field),
455            _ => None,
456        }
457    }
458
459    /// One field's refusal, in its own words.
460    pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
461        Self::Field {
462            field,
463            detail: detail.into(),
464        }
465    }
466}
467
468impl core::fmt::Display for ConfigError {
469    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
470        match self {
471            Self::Unreadable { path, detail } => write!(
472                formatter,
473                "the configuration file {} could not be read: {detail}",
474                path.display()
475            ),
476            Self::Unparsable { path, detail } => write!(
477                formatter,
478                "the configuration file {} could not be read as this program's \
479                 configuration: {detail}",
480                path.display()
481            ),
482            Self::Field { field, detail } => write!(
483                formatter,
484                "the configuration field `{field}` cannot be accepted: {detail}"
485            ),
486        }
487    }
488}
489
490impl core::error::Error for ConfigError {}
491
492/// Where the `OctoPrint` instance is and what it is like, as written down.
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(
495    crate = "printobserver_types::serde",
496    deny_unknown_fields,
497    rename_all = "snake_case"
498)]
499#[schemars(crate = "printobserver_types::schemars")]
500pub struct OctoprintSection {
501    /// The base URL the instance answers on.
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub url: Option<String>,
504    /// The key it authenticates every request by.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub api_key: Option<String>,
507    /// Whether the machine has a part-cooling fan this server may command.
508    #[serde(default = "commandable")]
509    pub fan: String,
510}
511
512/// The vocabulary [`OctoprintSection::fan`] takes, spelled as the operator
513/// writes it.
514pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
515    ("commandable", FanSupport::Commandable),
516    ("absent", FanSupport::Absent),
517];
518
519/// The fan setting a configuration naming none takes.
520fn commandable() -> String {
521    FAN_VOCABULARY[0].0.to_owned()
522}
523
524impl Default for OctoprintSection {
525    fn default() -> Self {
526        Self {
527            url: None,
528            api_key: None,
529            fan: commandable(),
530        }
531    }
532}
533
534/// How the supervising agent is reached, as written down.
535#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
536#[serde(
537    crate = "printobserver_types::serde",
538    deny_unknown_fields,
539    rename_all = "snake_case"
540)]
541#[schemars(crate = "printobserver_types::schemars")]
542pub struct SupervisorSection {
543    /// The harness identity turns run on.
544    #[serde(default, skip_serializing_if = "Option::is_none")]
545    pub harness: Option<String>,
546    /// The model turns are pinned to, when one is pinned.
547    #[serde(default, skip_serializing_if = "Option::is_none")]
548    pub model: Option<String>,
549    /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
550    /// system prompt; the agent runs from the directory holding it. Required:
551    /// this program carries no skill, and an absent one refuses the start.
552    #[serde(default, skip_serializing_if = "Option::is_none")]
553    pub skill_path: Option<PathBuf>,
554    /// The prompt template one turn fills, when the operator supplies one
555    /// instead of the committed template this program carries.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub prompt_template_path: Option<PathBuf>,
558    /// How often every active print is given a periodic observation, and its
559    /// agent a turn on it, in seconds. Left out, two minutes.
560    #[serde(default = "default_observation_interval_s")]
561    pub observation_interval_s: u64,
562    /// How often the printer watch reads the machine, whether or not a print
563    /// is active, in seconds: from 5 to 300. Left out, fifteen seconds.
564    #[serde(default = "default_printer_poll_s")]
565    pub printer_poll_s: u64,
566    /// How long after a print ends `interrupted` or `failed` the printer
567    /// heating or moving on its own is recorded, in seconds: from 60 to
568    /// 86400. Left out, an hour.
569    #[serde(default = "default_unattended_window_s")]
570    pub unattended_window_s: u64,
571    /// The conversation size, in tokens, at which the harness compacts a
572    /// session on its own during a turn. Left out, nothing is set.
573    #[serde(default, skip_serializing_if = "Option::is_none")]
574    pub auto_compact_tokens: Option<i64>,
575    /// The conversation size, in tokens, at or above which a print's session
576    /// is compacted while no turn of it runs. Left out, never.
577    #[serde(default, skip_serializing_if = "Option::is_none")]
578    pub idle_compact_tokens: Option<i64>,
579    /// How long a harness check's one turn may take, in seconds: from 1 to
580    /// 900. Left out, two minutes.
581    #[serde(default = "default_check_turn_timeout_s")]
582    pub check_turn_timeout_s: u64,
583}
584
585/// The harness check's turn bound a configuration naming none takes.
586const fn default_check_turn_timeout_s() -> u64 {
587    DEFAULT_CHECK_TURN_TIMEOUT_S
588}
589
590/// The printer poll a configuration naming none takes.
591const fn default_printer_poll_s() -> u64 {
592    DEFAULT_PRINTER_POLL_S
593}
594
595/// The unattended window a configuration naming none takes.
596const fn default_unattended_window_s() -> u64 {
597    DEFAULT_UNATTENDED_WINDOW_S
598}
599
600/// The observation interval a configuration naming none takes.
601const fn default_observation_interval_s() -> u64 {
602    DEFAULT_OBSERVATION_INTERVAL_S
603}
604
605impl Default for SupervisorSection {
606    fn default() -> Self {
607        Self {
608            harness: None,
609            model: None,
610            skill_path: None,
611            prompt_template_path: None,
612            observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
613            printer_poll_s: DEFAULT_PRINTER_POLL_S,
614            unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
615            auto_compact_tokens: None,
616            idle_compact_tokens: None,
617            check_turn_timeout_s: DEFAULT_CHECK_TURN_TIMEOUT_S,
618        }
619    }
620}
621
622/// What the `Obico` ingress requires and how fast it answers, as written down.
623#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
624#[serde(
625    crate = "printobserver_types::serde",
626    deny_unknown_fields,
627    rename_all = "snake_case"
628)]
629#[schemars(crate = "printobserver_types::schemars")]
630pub struct IngressSection {
631    /// The shared secret every post must carry.
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub shared_secret: Option<String>,
634    /// How long the ingress may take to answer, in milliseconds.
635    #[serde(default = "default_answer_bound_ms")]
636    pub answer_bound_ms: u64,
637}
638
639/// The answer bound a configuration naming none takes.
640const fn default_answer_bound_ms() -> u64 {
641    DEFAULT_INGRESS_ANSWER_BOUND_MS
642}
643
644impl Default for IngressSection {
645    fn default() -> Self {
646        Self {
647            shared_secret: None,
648            answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
649        }
650    }
651}
652
653/// What a caller of the versioned API authenticates with, as written down.
654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
655#[serde(
656    crate = "printobserver_types::serde",
657    deny_unknown_fields,
658    rename_all = "snake_case"
659)]
660#[schemars(crate = "printobserver_types::schemars")]
661pub struct ApiSection {
662    /// A plaintext operator credential. Superseded by `credential_verifier`:
663    /// still admitted until it is replaced, with a warning on every start,
664    /// because a supervision turn can read the file it is written in.
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub credential: Option<String>,
667    /// The verifier the operator's credential is checked against:
668    /// `sha256:` and the 64 lowercase hexadecimal digits of the SHA-256 of the
669    /// credential's UTF-8 bytes, as `printobserver credential issue` prints it.
670    /// Left out, the server reads `api-credential.verifier` in its state
671    /// directory, and admits no operator at all when that is absent too.
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub credential_verifier: Option<String>,
674}
675
676/// Where a fresh frame of the print is fetched from, as written down.
677#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
678#[serde(
679    crate = "printobserver_types::serde",
680    deny_unknown_fields,
681    rename_all = "snake_case"
682)]
683#[schemars(crate = "printobserver_types::schemars")]
684pub struct CameraSection {
685    /// An `http` or `https` URL answering one still image of the print, such
686    /// as a `go2rtc` `frame.jpeg` address. Left out, a look carries no frame.
687    #[serde(default, skip_serializing_if = "Option::is_none")]
688    pub snapshot_url: Option<String>,
689    /// The path of this camera's calibration file, which
690    /// `tools/camera-calibration` writes: it lets a check draw the planned
691    /// toolpath where it sits in this camera's view. Read and validated at
692    /// start, and an unreadable or invalid file is refused. Left out, nothing
693    /// is drawn and no print's first-layer alignment is checked.
694    #[serde(default, skip_serializing_if = "Option::is_none")]
695    pub calibration: Option<PathBuf>,
696}
697
698/// Where `Obico`'s own API answers, as written down.
699///
700/// Its debug form never shows the token.
701#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
702#[serde(
703    crate = "printobserver_types::serde",
704    deny_unknown_fields,
705    rename_all = "snake_case"
706)]
707#[schemars(crate = "printobserver_types::schemars")]
708pub struct ObicoSection {
709    /// The server's own `http` or `https` address, such as
710    /// `http://127.0.0.1:3334`. Given with `access_token` or not at all.
711    #[serde(default, skip_serializing_if = "Option::is_none")]
712    pub url: Option<String>,
713    /// A bearer token for its API, issued by the instance's own OAuth
714    /// administration. Left out with the address, a print the detector paused
715    /// and the supervisor resumed is not acknowledged to `Obico`.
716    #[serde(default, skip_serializing_if = "Option::is_none")]
717    pub access_token: Option<String>,
718    /// The failure detector's own service — `Obico`'s `ml_api` — as an `http`
719    /// or `https` address, whose unauthenticated `/hc/` is asked during every
720    /// print whether detection is up. Left out, nothing checks it and its
721    /// health reads `unchecked`.
722    #[serde(default, skip_serializing_if = "Option::is_none")]
723    pub ml_api_url: Option<String>,
724    /// `Obico`'s own identifier for the printer — the number in its printer
725    /// page's address — whose record of the print is read once per
726    /// observation interval for the detector's status. Left out, the printer
727    /// the last body `Obico` posted named is read, and nothing until it has
728    /// posted one.
729    #[serde(default, skip_serializing_if = "Option::is_none")]
730    pub printer_id: Option<i64>,
731}
732
733/// How a camera frame is judged, as written down.
734#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
735#[serde(
736    crate = "printobserver_types::serde",
737    deny_unknown_fields,
738    rename_all = "snake_case"
739)]
740#[schemars(crate = "printobserver_types::schemars")]
741pub struct VisionSection {
742    /// The grey-level standard deviation at or below which a frame is blank
743    /// and is fetched again: from 1 to 128. Left out, 36.5.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub blank_frame_max_stddev: Option<f64>,
746}
747
748impl core::fmt::Debug for ObicoSection {
749    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
750        formatter
751            .debug_struct("ObicoSection")
752            .field("url", &self.url)
753            .field(
754                "access_token",
755                &self.access_token.as_ref().map(|_| REDACTED),
756            )
757            .field("ml_api_url", &self.ml_api_url)
758            .field("printer_id", &self.printer_id)
759            .finish()
760    }
761}
762
763/// How spools are checked before a print, as written down.
764///
765/// Every key is optional, and one left out takes the supervision core's own
766/// default. The mode is read as text rather than as the core's own type so
767/// that a mode outside the three is refused naming its key rather than by the
768/// parser in words of its own.
769#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
770#[serde(
771    crate = "printobserver_types::serde",
772    deny_unknown_fields,
773    rename_all = "snake_case"
774)]
775#[schemars(crate = "printobserver_types::schemars")]
776pub struct SpoolsSection {
777    /// What a start does when the loaded spool is short, unverified, or the
778    /// file has no analysis: `refuse`, `warn` or `off`. Left out, `refuse`.
779    #[serde(default, skip_serializing_if = "Option::is_none")]
780    pub preflight: Option<String>,
781    /// The margin asked beyond what a print needs, as a percentage of it.
782    #[serde(default, skip_serializing_if = "Option::is_none")]
783    pub buffer_percent: Option<f64>,
784    /// The least margin asked, in grams, however small the print.
785    #[serde(default, skip_serializing_if = "Option::is_none")]
786    pub buffer_min_g: Option<f64>,
787    /// How long a start waits for `OctoPrint`'s analysis of a file that has
788    /// none yet, in whole seconds; zero waits not at all.
789    #[serde(default, skip_serializing_if = "Option::is_none")]
790    pub analysis_wait_seconds: Option<i64>,
791}
792
793/// Which build sheets each material may be printed on, as written down.
794///
795/// Left out, the supervision core's defaults stand; written, `allowed`
796/// replaces them whole.
797#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
798#[serde(
799    crate = "printobserver_types::serde",
800    deny_unknown_fields,
801    rename_all = "snake_case"
802)]
803#[schemars(crate = "printobserver_types::schemars")]
804pub struct SheetsSection {
805    /// Each material, as a spool's own material names it, and the sheet ids
806    /// a print of it may go down on.
807    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
808    #[serde(default, skip_serializing_if = "Option::is_none")]
809    pub allowed: Option<std::collections::BTreeMap<String, Vec<String>>>,
810}
811
812/// The printer's own facts a recovery is checked against, as written down.
813///
814/// Left out altogether, or written with no key, no recovery action can be
815/// checked and every one is refused as not configured. Written with any key,
816/// every key without a default is required. Each is read as written so that a
817/// value that cannot work is refused naming its key.
818#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
819#[serde(
820    crate = "printobserver_types::serde",
821    deny_unknown_fields,
822    rename_all = "snake_case"
823)]
824#[schemars(crate = "printobserver_types::schemars")]
825pub struct RecoverySection {
826    /// Which way along Z moves the nozzle away from the bed: `z_plus` or
827    /// `z_minus`.
828    #[serde(default, skip_serializing_if = "Option::is_none")]
829    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
830    pub away_from_bed: Option<String>,
831    /// The highest Z the machine reaches, in millimetres.
832    #[serde(default, skip_serializing_if = "Option::is_none")]
833    pub max_z_mm: Option<f64>,
834    /// The longest lift one recovery may ask for, in millimetres; 50 when
835    /// left out.
836    #[serde(default, skip_serializing_if = "Option::is_none")]
837    pub max_lift_mm: Option<f64>,
838    /// How far above the tallest part the nozzle must be, in millimetres; 5
839    /// when left out.
840    #[serde(default, skip_serializing_if = "Option::is_none")]
841    pub clearance_margin_mm: Option<f64>,
842    /// Where a park moves the head, as `[x, y]` in millimetres.
843    #[serde(default, skip_serializing_if = "Option::is_none")]
844    pub park_xy: Option<Vec<f64>>,
845    /// Where the machine homes Z, as `[x, y]` in millimetres.
846    #[serde(default, skip_serializing_if = "Option::is_none")]
847    pub z_home_xy: Option<Vec<f64>>,
848    /// Whether homing Z brings a gantry down over the whole bed.
849    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub z_home_sweeps_bed: Option<bool>,
852}
853
854/// Who may ask for which recovery action, as written down under
855/// `[policy.recovery]`. Each list left out takes its default: the operator
856/// every action, the agent none, and only the operator's assertions counting.
857#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
858#[serde(
859    crate = "printobserver_types::serde",
860    deny_unknown_fields,
861    rename_all = "snake_case"
862)]
863#[schemars(crate = "printobserver_types::schemars")]
864pub struct RecoveryPolicySection {
865    /// The recovery actions the operator may ask for, by name.
866    #[serde(default, skip_serializing_if = "Option::is_none")]
867    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
868    pub operator: Option<Vec<String>>,
869    /// The recovery actions the agent may ask for, by name. `recover_home_z`
870    /// is refused here.
871    #[serde(default, skip_serializing_if = "Option::is_none")]
872    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
873    pub agent: Option<Vec<String>>,
874    /// The actor classes whose word that the nozzle or the bed is clear
875    /// counts. `agent` is refused here.
876    #[serde(default, skip_serializing_if = "Option::is_none")]
877    // llmlint: ignore[invalid_states_unrepresentable] suppressions.toml has the reason.
878    pub asserting: Option<Vec<String>>,
879}
880
881/// The policies this program is configured with beside the safety envelope.
882#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
883#[serde(
884    crate = "printobserver_types::serde",
885    deny_unknown_fields,
886    rename_all = "snake_case"
887)]
888#[schemars(crate = "printobserver_types::schemars")]
889pub struct PolicySection {
890    /// Who may ask for which recovery action.
891    #[serde(default)]
892    pub recovery: RecoveryPolicySection,
893}
894
895/// The whole configuration file, exactly as it is written down.
896///
897/// This is the parsed document rather than the validated configuration:
898/// [`ServerConfig::load`] is what turns one into the other, and every value a
899/// later step could find wrong is ruled on there.
900#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
901#[serde(
902    crate = "printobserver_types::serde",
903    deny_unknown_fields,
904    rename_all = "snake_case"
905)]
906#[schemars(crate = "printobserver_types::schemars")]
907pub struct ConfigFile {
908    /// Where the store, the images and the sessions live.
909    #[serde(default, skip_serializing_if = "Option::is_none")]
910    pub state_dir: Option<PathBuf>,
911    /// The address the API and the ingress are served on.
912    #[serde(default, skip_serializing_if = "Option::is_none")]
913    pub listen: Option<String>,
914    /// Where the `OctoPrint` instance is.
915    #[serde(default)]
916    pub octoprint: OctoprintSection,
917    /// The operator's safety envelope.
918    #[serde(default, skip_serializing_if = "Option::is_none")]
919    pub safety: Option<SafetyEnvelope>,
920    /// How the supervising agent is reached.
921    #[serde(default)]
922    pub supervisor: SupervisorSection,
923    /// What the `Obico` ingress requires.
924    #[serde(default)]
925    pub ingress: IngressSection,
926    /// What a caller of the versioned API authenticates with.
927    #[serde(default)]
928    pub api: ApiSection,
929    /// Where a fresh frame of the print is fetched from.
930    #[serde(default)]
931    pub camera: CameraSection,
932    /// Where `Obico`'s own API answers.
933    #[serde(default)]
934    pub obico: ObicoSection,
935    /// How a camera frame is judged.
936    #[serde(default)]
937    pub vision: VisionSection,
938    /// How spools are checked before a print.
939    #[serde(default)]
940    pub spools: SpoolsSection,
941    /// Which build sheets each material may be printed on.
942    #[serde(default)]
943    pub sheets: SheetsSection,
944    /// The printer's own facts a recovery is checked against.
945    #[serde(default)]
946    pub recovery: RecoverySection,
947    /// The policies beside the safety envelope.
948    #[serde(default)]
949    pub policy: PolicySection,
950}
951
952/// The shared secret the ingress requires of every post.
953///
954/// Neither rendering of this type shows the value, so it cannot reach a log
955/// record, a panic message or an error's own text by being formatted — and the
956/// comparison that admits a post lives here rather than at the endpoint, so
957/// there is no way to read the secret out in order to compare it.
958#[derive(Clone, PartialEq, Eq)]
959pub struct SharedSecret(String);
960
961/// What a secret renders as, wherever a value carrying one is rendered.
962pub const REDACTED: &str = "<redacted>";
963
964impl SharedSecret {
965    /// The secret this text names.
966    ///
967    /// # Errors
968    ///
969    /// Returns [`ConfigError`] when the text is empty or is nothing but
970    /// whitespace: anything that can post to the ingress can pause a printer,
971    /// and a secret nothing has to carry is no secret.
972    pub fn new(value: &str) -> Result<Self, ConfigError> {
973        if value.trim().is_empty() {
974            return Err(ConfigError::about(
975                ConfigField::IngressSharedSecret,
976                "it is empty, and anything that can post to the ingress can pause a printer",
977            ));
978        }
979        Ok(Self(value.to_owned()))
980    }
981
982    /// Whether a post carried this secret.
983    ///
984    /// Compared over the whole of both values with the two lengths mixed in,
985    /// rather than by returning at the first difference or at a length
986    /// mismatch, so that how long this takes says nothing about how much of the
987    /// secret a caller guessed.
988    #[must_use]
989    pub fn matches(&self, offered: Option<&str>) -> bool {
990        let Some(offered) = offered else {
991            return false;
992        };
993        let expected = self.0.as_bytes();
994        let mut difference = expected.len() ^ offered.len();
995        for (index, byte) in offered.bytes().enumerate() {
996            let against = expected[index % expected.len().max(1)];
997            difference |= usize::from(byte ^ against);
998        }
999        difference == 0
1000    }
1001}
1002
1003impl core::fmt::Display for SharedSecret {
1004    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1005        formatter.write_str(REDACTED)
1006    }
1007}
1008
1009impl core::fmt::Debug for SharedSecret {
1010    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1011        write!(formatter, "SharedSecret({REDACTED})")
1012    }
1013}
1014
1015/// How many random bytes a credential this server generates is drawn from.
1016pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
1017
1018/// One credential in plaintext: a legacy `api.credential`, the legacy file a
1019/// server generated into its state directory, or one `printobserver credential
1020/// issue` draws for the operator's own configuration.
1021///
1022/// Neither rendering of this type shows the value. Its text is read in exactly
1023/// one place — [`Self::written`], for the operator's own client configuration,
1024/// which exists to carry it, and for the verifier computed from it — and the
1025/// one comparison a presented credential is admitted by is [`Self::admits`], so
1026/// there is no second comparison anywhere that could return early.
1027#[derive(Clone)]
1028pub struct ApiCredential(String);
1029
1030impl ApiCredential {
1031    /// The credential this text names.
1032    ///
1033    /// # Errors
1034    ///
1035    /// Answers why the text cannot be a credential, in words that never quote
1036    /// it: empty or nothing but whitespace, or carrying a control character or
1037    /// a character outside printable ASCII, or beginning or ending with a space
1038    /// — none of which an `Authorization` header carries intact.
1039    pub fn new(value: &str) -> Result<Self, &'static str> {
1040        if value.trim().is_empty() {
1041            return Err(
1042                "it is empty, and anything that can reach this server's API can command a printer",
1043            );
1044        }
1045        if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
1046            return Err(
1047                "it carries a control character or a character outside printable ASCII, which \
1048                 no `Authorization` header carries intact",
1049            );
1050        }
1051        if value.starts_with(' ') || value.ends_with(' ') {
1052            return Err(
1053                "it begins or ends with a space, which an `Authorization` header does not carry",
1054            );
1055        }
1056        // llmlint: ignore[boundary_inputs_validated] The refusal set above is exactly the contract this server's API credential is planned against, shared with the nodes that build on it: empty or whitespace, a control or non-printable-ASCII byte, a leading or trailing space. A length floor would refuse operator credentials that contract admits, so it is recorded as a follow-up rather than added here; the default an operator gets without configuring one is the generated 32 random bytes.
1057        Ok(Self(value.to_owned()))
1058    }
1059
1060    /// A fresh credential, drawn from the operating system's own
1061    /// cryptographically secure random source.
1062    ///
1063    /// [`GENERATED_CREDENTIAL_BYTES`] bytes, written as unpadded URL-safe
1064    /// base64 so an operator can copy it and a header can carry it as it is.
1065    ///
1066    /// # Errors
1067    ///
1068    /// Answers the random source's own refusal, when it has none to give.
1069    pub fn generate() -> Result<Self, getrandom::Error> {
1070        use base64::Engine as _;
1071
1072        let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
1073        getrandom::fill(&mut drawn)?;
1074        Ok(Self(
1075            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
1076        ))
1077    }
1078
1079    /// Whether a presented credential is this one.
1080    ///
1081    /// The lengths are compared first, which says how long the credential is and
1082    /// nothing else; the bytes are then compared in constant time, so how long
1083    /// this takes says nothing about how much of it a caller guessed.
1084    #[must_use]
1085    pub fn admits(&self, presented: &[u8]) -> bool {
1086        use subtle::ConstantTimeEq as _;
1087
1088        let expected = self.0.as_bytes();
1089        expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
1090    }
1091
1092    /// The text, for the one file whose purpose is to carry it — the
1093    /// operator's own client configuration — and nothing else.
1094    #[must_use]
1095    pub fn written(&self) -> &str {
1096        &self.0
1097    }
1098
1099    /// The verifier this credential is checked by.
1100    #[must_use]
1101    pub fn verifier(&self) -> CredentialVerifier {
1102        CredentialVerifier::of(&self.0)
1103    }
1104}
1105
1106impl PartialEq for ApiCredential {
1107    fn eq(&self, other: &Self) -> bool {
1108        self.admits(other.0.as_bytes())
1109    }
1110}
1111
1112impl Eq for ApiCredential {}
1113
1114impl core::fmt::Display for ApiCredential {
1115    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1116        formatter.write_str(REDACTED)
1117    }
1118}
1119
1120impl core::fmt::Debug for ApiCredential {
1121    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1122        write!(formatter, "ApiCredential({REDACTED})")
1123    }
1124}
1125
1126/// What a credential verifier is written with before its digest.
1127pub const VERIFIER_PREFIX: &str = "sha256:";
1128
1129/// How many hexadecimal digits a verifier's digest is written in.
1130const VERIFIER_DIGITS: usize = 64;
1131
1132/// What one operator credential is checked against: the SHA-256 of its UTF-8
1133/// bytes.
1134///
1135/// It is not a secret, so its rendering shows it — written as
1136/// [`VERIFIER_PREFIX`] and the digest in lowercase hexadecimal, which is the
1137/// one spelling [`Self::parse`] accepts. It is still printed by nothing but the
1138/// two commands that exist to print it, and logged by nothing. A verifier of a
1139/// short or guessable credential can be searched offline, which is why the
1140/// credential it verifies is drawn from 32 random bytes when this program
1141/// draws it.
1142#[derive(Clone, PartialEq, Eq)]
1143pub struct CredentialVerifier([u8; 32]);
1144
1145impl CredentialVerifier {
1146    /// The verifier of one credential.
1147    #[must_use]
1148    pub fn of(credential: &str) -> Self {
1149        use sha2::Digest as _;
1150
1151        Self(sha2::Sha256::digest(credential.as_bytes()).into())
1152    }
1153
1154    /// The verifier this text writes down.
1155    ///
1156    /// # Errors
1157    ///
1158    /// Answers why the text is not one: anything but [`VERIFIER_PREFIX`]
1159    /// followed by exactly 64 lowercase hexadecimal digits.
1160    pub fn parse(text: &str) -> Result<Self, &'static str> {
1161        const SHAPE: &str = "it is not `sha256:` followed by the 64 lowercase hexadecimal digits                              of a SHA-256 digest, which is what `printobserver credential issue`                              and `printobserver credential verifier` print";
1162        let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
1163        if digits.len() != VERIFIER_DIGITS
1164            || !digits
1165                .bytes()
1166                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1167        {
1168            return Err(SHAPE);
1169        }
1170        let mut digest = [0_u8; 32];
1171        for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
1172            let high = hex_value(pair[0]);
1173            let low = hex_value(pair[1]);
1174            digest[index] = (high << 4) | low;
1175        }
1176        Ok(Self(digest))
1177    }
1178
1179    /// Whether a presented credential is the one this verifies.
1180    ///
1181    /// The presented bytes are digested and the two digests compared in
1182    /// constant time, so how long this takes says nothing about how much of
1183    /// the credential a caller guessed.
1184    #[must_use]
1185    pub fn admits(&self, presented: &[u8]) -> bool {
1186        use sha2::Digest as _;
1187        use subtle::ConstantTimeEq as _;
1188
1189        let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
1190        bool::from(self.0.ct_eq(&offered))
1191    }
1192}
1193
1194/// One lowercase hexadecimal digit's value, for a digit already checked.
1195const fn hex_value(digit: u8) -> u8 {
1196    if digit.is_ascii_digit() {
1197        digit - b'0'
1198    } else {
1199        digit - b'a' + 10
1200    }
1201}
1202
1203impl core::fmt::Display for CredentialVerifier {
1204    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1205        formatter.write_str(VERIFIER_PREFIX)?;
1206        for byte in self.0 {
1207            write!(formatter, "{byte:02x}")?;
1208        }
1209        Ok(())
1210    }
1211}
1212
1213impl core::fmt::Debug for CredentialVerifier {
1214    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1215        write!(formatter, "CredentialVerifier({self})")
1216    }
1217}
1218
1219/// One running server's validated configuration.
1220///
1221/// Every value here is one no later step has to re-examine, and where a
1222/// validated type for one already exists it is that type rather than the text
1223/// it was written as: the `OctoPrint` instance is the adapter's own
1224/// configuration, which redacts the key it carries; the harness and the model
1225/// are the supervisor adapter's own names; and the ingress secret is a value
1226/// neither rendering of which shows.
1227#[derive(Debug, Clone, PartialEq)]
1228pub struct ServerConfig {
1229    /// Where the store, the images and the sessions live.
1230    pub state_dir: PathBuf,
1231    /// The address the API and the ingress are served on.
1232    pub listen: SocketAddr,
1233    /// Everything the printer adapter needs to reach the instance.
1234    pub octoprint: OctoPrintConfig,
1235    /// The operator's safety envelope.
1236    pub safety: SafetyEnvelope,
1237    /// The harness identity turns run on.
1238    pub harness: HarnessIdentity,
1239    /// The model turns are pinned to, when one is pinned.
1240    pub model: Option<ModelName>,
1241    /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
1242    /// system prompt. The agent runs from the directory holding it, which is
1243    /// where the skill's own `reference/` documents sit.
1244    pub skill_path: PathBuf,
1245    /// The prompt template one turn fills, when the operator supplied one.
1246    pub prompt_template_path: Option<PathBuf>,
1247    /// How often every active print is given a periodic observation.
1248    pub observation_interval: core::time::Duration,
1249    /// How often the printer watch reads the machine.
1250    pub printer_poll: core::time::Duration,
1251    /// How long after an unfinished ending the printer acting on its own is
1252    /// recorded.
1253    pub unattended_window: core::time::Duration,
1254    /// The conversation size at which the harness compacts a session during a
1255    /// turn, when one is set.
1256    pub auto_compact_tokens: Option<NonZeroU64>,
1257    /// The conversation size at or above which a session is compacted while
1258    /// idle, when one is set.
1259    pub idle_compact_tokens: Option<NonZeroU64>,
1260    /// How long a harness check's one turn may take.
1261    pub check_turn_timeout: core::time::Duration,
1262    /// The grey-level spread at or below which a camera frame is blank.
1263    pub blank_frame_max_stddev: BlankFrameBound,
1264    /// Where the failure detector's own service answers its health check,
1265    /// when configured.
1266    pub obico_ml_api_url: Option<WebAddress>,
1267    /// Which of `Obico`'s printers its record of the print is read from, when
1268    /// configured.
1269    pub obico_printer_id: Option<ObicoPrinterId>,
1270    /// How long the ingress may take to answer.
1271    pub ingress_answer_bound: core::time::Duration,
1272    /// The shared secret every post to the ingress must carry.
1273    pub ingress_shared_secret: SharedSecret,
1274    /// A plaintext operator credential the configuration still carries, which
1275    /// is admitted — with a warning on every start — until it is replaced by
1276    /// its verifier.
1277    pub api_credential: Option<ApiCredential>,
1278    /// The verifier the operator's credential is checked against, when the
1279    /// configuration names one. Absent, the composition root reads the one in
1280    /// the state directory.
1281    pub api_credential_verifier: Option<CredentialVerifier>,
1282    /// Where a fresh frame of the print is fetched from, when configured.
1283    pub camera_snapshot_url: Option<WebAddress>,
1284    /// The camera's calibration, read and validated at start, when one is
1285    /// configured.
1286    pub camera_calibration: Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
1287    /// `Obico`'s own API, when configured; its debug form omits the token.
1288    pub obico_api: Option<ObicoApi>,
1289    /// How spools are checked before a print, and the margin asked for.
1290    pub spools: SpoolPolicy,
1291    /// Which build sheets each material may be printed on.
1292    pub sheets: SheetTable,
1293    /// The printer's own facts a recovery is checked against, when stated.
1294    pub recovery: Option<RecoveryConfig>,
1295    /// Who may ask for which recovery action.
1296    pub recovery_grants: RecoveryGrants,
1297}
1298
1299impl ServerConfig {
1300    /// Read and validate the one configuration file this program takes.
1301    ///
1302    /// # Errors
1303    ///
1304    /// Returns [`ConfigError::Unreadable`] when the file is not there,
1305    /// [`ConfigError::Unparsable`] when it is not this program's configuration,
1306    /// and [`ConfigError::Field`] naming the one field whose value cannot be
1307    /// accepted. The two values only the machine can rule on — the `OctoPrint`
1308    /// address and key — are ruled on by [`crate::Server::start`], which is
1309    /// where a printer exists to ask.
1310    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1311        let path = path.as_ref();
1312        Self::parse(&read(path)?, path)
1313    }
1314
1315    /// The same, over a document already read.
1316    ///
1317    /// # Errors
1318    ///
1319    /// The same as [`ServerConfig::load`], less the unreadable file.
1320    pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1321        let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1322            path: path.to_path_buf(),
1323            detail: error.to_string(),
1324        })?;
1325        Self::validate(file)
1326    }
1327
1328    /// Rule on every value the document carries.
1329    ///
1330    /// Absence is ruled on here rather than by the parser, because a parser's
1331    /// own "missing field" says which key it wanted and not which field of this
1332    /// program that is. Every refusal below names the dotted key an operator
1333    /// would edit.
1334    fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1335        let state_dir =
1336            state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1337        let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1338        let octoprint = octoprint(&file.octoprint)?;
1339        let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1340        check_envelope(&safety)?;
1341        let harness = harness_identity(file.supervisor.harness)?;
1342        let model = match file.supervisor.model {
1343            None => None,
1344            Some(name) => Some(
1345                ModelName::new(&named(ConfigField::Model, Some(name))?)
1346                    .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1347            ),
1348        };
1349        let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1350        let prompt_template_path = readable(
1351            ConfigField::PromptTemplatePath,
1352            file.supervisor.prompt_template_path.as_deref(),
1353        )?;
1354        let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1355        let printer_poll = seconds_within(
1356            ConfigField::PrinterPollS,
1357            file.supervisor.printer_poll_s,
1358            PRINTER_POLL_RANGE_S,
1359        )?;
1360        let unattended_window = seconds_within(
1361            ConfigField::UnattendedWindowS,
1362            file.supervisor.unattended_window_s,
1363            UNATTENDED_WINDOW_RANGE_S,
1364        )?;
1365        let (auto_compact_tokens, idle_compact_tokens) = compaction(
1366            file.supervisor.auto_compact_tokens,
1367            file.supervisor.idle_compact_tokens,
1368        )?;
1369        let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1370        let (obico_ml_api_url, obico_printer_id) = detector_reads(&file.obico)?;
1371        let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1372        let ingress_shared_secret = SharedSecret::new(&required(
1373            ConfigField::IngressSharedSecret,
1374            file.ingress.shared_secret,
1375        )?)?;
1376        let api_credential = file
1377            .api
1378            .credential
1379            .as_deref()
1380            .map(|value| {
1381                ApiCredential::new(value)
1382                    .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1383            })
1384            .transpose()?;
1385        let api_credential_verifier = file
1386            .api
1387            .credential_verifier
1388            .as_deref()
1389            .map(|value| {
1390                CredentialVerifier::parse(value.trim())
1391                    .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1392            })
1393            .transpose()?;
1394        let (camera_snapshot_url, camera_calibration) = camera(file.camera)?;
1395        let obico_api = obico_api(file.obico)?;
1396        let spools = spool_policy(&file.spools)?;
1397        let sheets = match file.sheets.allowed {
1398            None => SheetTable::default(),
1399            Some(entries) => SheetTable::new(entries)
1400                .map_err(|why| ConfigError::about(ConfigField::SheetsAllowed, why))?,
1401        };
1402        let recovery = recovery_facts(&file.recovery)?;
1403        let recovery_grants = recovery_grants(&file.policy.recovery)?;
1404        Ok(Self {
1405            state_dir,
1406            listen,
1407            octoprint,
1408            safety,
1409            harness,
1410            model,
1411            skill_path,
1412            prompt_template_path,
1413            observation_interval,
1414            printer_poll,
1415            unattended_window,
1416            auto_compact_tokens,
1417            idle_compact_tokens,
1418            check_turn_timeout: check_turn_timeout(file.supervisor.check_turn_timeout_s)?,
1419            blank_frame_max_stddev,
1420            obico_ml_api_url,
1421            obico_printer_id,
1422            ingress_answer_bound,
1423            ingress_shared_secret,
1424            api_credential,
1425            api_credential_verifier,
1426            camera_snapshot_url,
1427            camera_calibration,
1428            obico_api,
1429            spools,
1430            sheets,
1431            recovery,
1432            recovery_grants,
1433        })
1434    }
1435
1436    /// Where this server materializes the agent's prompt template and
1437    /// assessment schema. The skill is not among them: it is the installed one
1438    /// `skill_path` names.
1439    #[must_use]
1440    pub fn assets_dir(&self) -> PathBuf {
1441        self.state_dir.join(ASSETS_DIRECTORY)
1442    }
1443}
1444
1445/// One address a field names, refused unless it is an `http` or `https` URL
1446/// naming a host, by the field's own key and without quoting the value.
1447fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1448    WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1449}
1450
1451/// Where the failure detector's health check is asked, and which of `Obico`'s
1452/// printers its record of the print is read from — its own identifier, a whole
1453/// number from 1 — when each is written down.
1454fn detector_reads(
1455    section: &ObicoSection,
1456) -> Result<(Option<WebAddress>, Option<ObicoPrinterId>), ConfigError> {
1457    let ml_api_url = section
1458        .ml_api_url
1459        .as_deref()
1460        .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1461        .transpose()?;
1462    let printer_id = section
1463        .printer_id
1464        .map(|id| {
1465            ObicoPrinterId::new(id)
1466                .map_err(|why| ConfigError::about(ConfigField::ObicoPrinterId, why))
1467        })
1468        .transpose()?;
1469    Ok((ml_api_url, printer_id))
1470}
1471
1472/// `Obico`'s API, when both its address and its token are written down.
1473///
1474/// One without the other is refused naming the one that is missing: an address
1475/// with no token is a request `Obico` refuses, and a token with no address is a
1476/// secret written down for nothing.
1477fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1478    match (section.url, section.access_token) {
1479        (None, None) => Ok(None),
1480        (Some(_), None) => Err(ConfigError::about(
1481            ConfigField::ObicoAccessToken,
1482            "it is required when obico.url is given",
1483        )),
1484        (None, Some(_)) => Err(ConfigError::about(
1485            ConfigField::ObicoUrl,
1486            "it is required when obico.access_token is given",
1487        )),
1488        (Some(url), Some(access_token)) => {
1489            let url = web_address(ConfigField::ObicoUrl, &url)?;
1490            let access_token = AccessToken::new(&access_token)
1491                .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1492            Ok(Some(ObicoApi::new(url, access_token)))
1493        }
1494    }
1495}
1496
1497/// The two values signing a harness in reads, and nothing else.
1498///
1499/// An operator signs the agent in before or after filling in the machine and
1500/// the failure detector, so `printobserver sign-in` reads the state directory
1501/// and the harness identity out of the server's own file and nothing beside
1502/// them: every other value the file carries, present or not and valid or not,
1503/// is one it never looks at.
1504#[derive(Debug, Clone, PartialEq, Eq)]
1505pub struct SignInConfig {
1506    /// Where the state lives, and so where the harness keeps its sign-in.
1507    pub state_dir: PathBuf,
1508    /// The harness identity supervision turns run on.
1509    pub harness: HarnessIdentity,
1510}
1511
1512impl SignInConfig {
1513    /// Read those two values out of one configuration file.
1514    ///
1515    /// # Errors
1516    ///
1517    /// Returns [`ConfigError::Unreadable`] when the file is not there,
1518    /// [`ConfigError::Unparsable`] when it is not a document carrying either
1519    /// value in the shape this program reads it in, and [`ConfigError::Field`]
1520    /// naming `state_dir` or `supervisor.harness` when that value cannot be
1521    /// accepted.
1522    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1523        let path = path.as_ref();
1524        let file: SignInFile =
1525            toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1526                path: path.to_path_buf(),
1527                detail: error.to_string(),
1528            })?;
1529        Ok(Self {
1530            state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1531            harness: harness_identity(file.supervisor.harness)?,
1532        })
1533    }
1534}
1535
1536/// The configuration file, read for the two values signing in takes.
1537///
1538/// Unlike [`ConfigFile`] it refuses no key it does not know, because every key
1539/// but these two is one signing in does not read.
1540#[derive(Deserialize)]
1541#[serde(crate = "printobserver_types::serde")]
1542struct SignInFile {
1543    /// Where the state lives.
1544    #[serde(default)]
1545    state_dir: Option<PathBuf>,
1546    /// The supervisor's section, for its harness alone.
1547    #[serde(default)]
1548    supervisor: SignInSupervisor,
1549}
1550
1551/// The supervisor's section, read for the harness alone.
1552#[derive(Default, Deserialize)]
1553#[serde(crate = "printobserver_types::serde")]
1554struct SignInSupervisor {
1555    /// The harness identity turns run on.
1556    #[serde(default)]
1557    harness: Option<String>,
1558}
1559
1560/// One configuration file's text.
1561fn read(path: &Path) -> Result<String, ConfigError> {
1562    std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1563        path: path.to_path_buf(),
1564        detail: error.to_string(),
1565    })
1566}
1567
1568/// The harness identity, refused by its own key when it names nothing.
1569fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1570    HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1571        .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1572}
1573
1574/// One field the file has to carry, refused by its own key when it does not.
1575fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1576    value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1577}
1578
1579/// One field that has to carry a name rather than nothing at all.
1580fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1581    let value = required(field, value)?;
1582    if value.trim().is_empty() {
1583        return Err(ConfigError::about(
1584            field,
1585            "it is empty, and an empty value names nothing",
1586        ));
1587    }
1588    Ok(value.trim().to_owned())
1589}
1590
1591/// The state directory, created where it is not there.
1592fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1593    if named.as_os_str().is_empty() {
1594        return Err(ConfigError::about(
1595            ConfigField::StateDir,
1596            "it names no directory, and this server's whole state lives in one",
1597        ));
1598    }
1599    std::fs::create_dir_all(named).map_err(|error| {
1600        ConfigError::about(
1601            ConfigField::StateDir,
1602            format!("{} cannot be created: {error}", named.display()),
1603        )
1604    })?;
1605    named.canonicalize().map(plainly_written).map_err(|error| {
1606        ConfigError::about(
1607            ConfigField::StateDir,
1608            format!("{} cannot be resolved: {error}", named.display()),
1609        )
1610    })
1611}
1612
1613/// A resolved path, written the way its own platform's tools write it.
1614///
1615/// Resolving a path on Windows answers it in its verbatim form, `\\?\C:\…`:
1616/// one this program opens as readily as any other, and one no operator types and
1617/// some of the programs a supervision turn runs refuse — and every image path
1618/// this server answers is written under it. Where that form names an ordinary
1619/// drive path it is written as that path. Any other path, which on every other
1620/// platform is every path, is answered as it is.
1621#[must_use]
1622pub fn plainly_written(path: PathBuf) -> PathBuf {
1623    const VERBATIM: &str = r"\\?\";
1624    let drive = path
1625        .to_str()
1626        .and_then(|text| text.strip_prefix(VERBATIM))
1627        .filter(|rest| {
1628            let bytes = rest.as_bytes();
1629            bytes.len() >= 3
1630                && bytes[0].is_ascii_alphabetic()
1631                && bytes[1] == b':'
1632                && bytes[2] == b'\\'
1633        })
1634        .map(PathBuf::from);
1635    drive.unwrap_or(path)
1636}
1637
1638/// The address to serve on, as an address rather than as text.
1639fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1640    named.trim().parse().map_err(|error| {
1641        ConfigError::about(
1642            ConfigField::Listen,
1643            format!("{named:?} is no address to listen on: {error}"),
1644        )
1645    })
1646}
1647
1648/// Everything the printer adapter needs to reach the instance, refused by the
1649/// field whose value it could not take.
1650fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1651    let fan = fan_support(&section.fan)?;
1652    let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1653    let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1654    OctoPrintConfig::new(&url, key)
1655        .map(|configured| configured.with_fan(fan))
1656        .map_err(|error| {
1657            let field = match error {
1658                printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1659                _ => ConfigField::OctoprintUrl,
1660            };
1661            ConfigError::about(field, error.to_string())
1662        })
1663}
1664
1665/// The fan setting one word of the vocabulary names.
1666fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1667    FAN_VOCABULARY
1668        .iter()
1669        .find(|(spelling, _)| *spelling == named.trim())
1670        .map(|(_, support)| *support)
1671        .ok_or_else(|| {
1672            let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1673            ConfigError::about(
1674                ConfigField::OctoprintFan,
1675                format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1676            )
1677        })
1678}
1679
1680/// The envelope, refused when a range it declares admits nothing.
1681fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1682    if envelope.allowed.is_empty() {
1683        return Err(ConfigError::about(
1684            ConfigField::SafetyEnvelope,
1685            "it allows no adjustable at all, so no adjustment could ever be accepted",
1686        ));
1687    }
1688    for (adjustable, range) in &envelope.allowed {
1689        if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1690            return Err(ConfigError::about(
1691                ConfigField::SafetyEnvelope,
1692                format!(
1693                    "the range allowed for {adjustable} runs from {} to {}, which admits \
1694                     no value",
1695                    range.min, range.max
1696                ),
1697            ));
1698        }
1699    }
1700    // Closing a print record is the operator's judgement that the print is
1701    // over, so no configuration may hand it to the agent watching the print.
1702    if envelope
1703        .actions
1704        .get(&ActorClass::Agent)
1705        .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1706    {
1707        return Err(ConfigError::about(
1708            ConfigField::SafetyEnvelope,
1709            "it grants `close_print` to the agent, and closing a print record is the \
1710             operator's judgement that the print is over",
1711        ));
1712    }
1713    if envelope.agent_min_interval_s < 0 {
1714        return Err(ConfigError::about(
1715            ConfigField::SafetyEnvelope,
1716            format!(
1717                "the agent's minimum interval is {}s, and an interval is a count of seconds",
1718                envelope.agent_min_interval_s
1719            ),
1720        ));
1721    }
1722    Ok(())
1723}
1724
1725/// One optional path, read where it was named so that a path naming nothing is
1726/// refused here rather than hours later.
1727fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1728    let Some(path) = named else {
1729        return Ok(None);
1730    };
1731    std::fs::read_to_string(path)
1732        .map(|_| Some(path.to_path_buf()))
1733        .map_err(|error| {
1734            ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1735        })
1736}
1737
1738/// The camera's snapshot address and calibration, each when configured.
1739fn camera(
1740    section: CameraSection,
1741) -> Result<
1742    (
1743        Option<WebAddress>,
1744        Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
1745    ),
1746    ConfigError,
1747> {
1748    let snapshot_url = section
1749        .snapshot_url
1750        .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1751        .transpose()?;
1752    let calibration = section
1753        .calibration
1754        .as_deref()
1755        .map(calibration)
1756        .transpose()?
1757        .map(std::sync::Arc::new);
1758    Ok((snapshot_url, calibration))
1759}
1760
1761/// The camera's calibration file, read and validated where it was named, and
1762/// refused naming `camera.calibration` when it cannot be read or is not one.
1763fn calibration(path: &Path) -> Result<printobserver_panels::CameraCalibration, ConfigError> {
1764    let bytes = std::fs::read(path).map_err(|error| {
1765        ConfigError::about(
1766            ConfigField::CameraCalibration,
1767            format!("{} cannot be read: {error}", path.display()),
1768        )
1769    })?;
1770    printobserver_panels::CameraCalibration::from_json(&bytes).map_err(|error| {
1771        ConfigError::about(
1772            ConfigField::CameraCalibration,
1773            format!("{} is not a camera calibration: {error}", path.display()),
1774        )
1775    })
1776}
1777
1778/// The installed skill, refused naming how to install one when it is absent or
1779/// cannot be read.
1780fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1781    let Some(path) = named else {
1782        return Err(ConfigError::about(
1783            ConfigField::SkillPath,
1784            format!(
1785                "the configuration file carries no value for it, and this program carries \
1786                 no skill of its own: {SKILL_INSTALL}"
1787            ),
1788        ));
1789    };
1790    std::fs::read_to_string(path)
1791        .map(|_| path.to_path_buf())
1792        .map_err(|error| {
1793            ConfigError::about(
1794                ConfigField::SkillPath,
1795                format!(
1796                    "{} cannot be read: {error}. {SKILL_INSTALL}",
1797                    path.display()
1798                ),
1799            )
1800        })
1801}
1802
1803/// How spools are checked, each key left out taking the core's own default.
1804fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1805    let defaults = SpoolPolicy::default();
1806    let preflight = match section.preflight.as_deref() {
1807        None => defaults.preflight,
1808        Some("refuse") => PreflightMode::Refuse,
1809        Some("warn") => PreflightMode::Warn,
1810        Some("off") => PreflightMode::Off,
1811        Some(_) => {
1812            return Err(ConfigError::about(
1813                ConfigField::SpoolsPreflight,
1814                "the spool check is one of `refuse`, `warn` or `off`",
1815            ));
1816        }
1817    };
1818    let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1819        None => Ok(default),
1820        Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1821        Some(_) => Err(ConfigError::about(
1822            field,
1823            "a margin is a figure at or above zero; a negative one asks a spool for less \
1824             than the print needs",
1825        )),
1826    };
1827    let buffer_percent = margin(
1828        ConfigField::SpoolsBufferPercent,
1829        section.buffer_percent,
1830        defaults.buffer_percent,
1831    )?;
1832    let buffer_min_g = margin(
1833        ConfigField::SpoolsBufferMinG,
1834        section.buffer_min_g,
1835        defaults.buffer_min_g,
1836    )?;
1837    let analysis_wait_s = match section.analysis_wait_seconds {
1838        None => defaults.analysis_wait_s,
1839        Some(seconds) => u64::try_from(seconds).map_err(|_| {
1840            ConfigError::about(
1841                ConfigField::SpoolsAnalysisWaitSeconds,
1842                "a wait is a number of seconds at or above zero",
1843            )
1844        })?,
1845    };
1846    Ok(SpoolPolicy {
1847        preflight,
1848        buffer_percent,
1849        buffer_min_g,
1850        analysis_wait_s,
1851    })
1852}
1853
1854/// The printer's recovery facts, absent when the section states none.
1855fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
1856    if *section == RecoverySection::default() {
1857        return Ok(None);
1858    }
1859    let absent = |field: ConfigField| {
1860        ConfigError::about(
1861            field,
1862            "`[recovery]` states this printer's facts, and this one is one of them",
1863        )
1864    };
1865    let away_from_bed = match section.away_from_bed.as_deref() {
1866        None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
1867        Some("z_plus") => AwayFromBed::ZPlus,
1868        Some("z_minus") => AwayFromBed::ZMinus,
1869        Some(other) => {
1870            return Err(ConfigError::about(
1871                ConfigField::RecoveryAwayFromBed,
1872                format!("{other:?} is neither `z_plus` nor `z_minus`"),
1873            ));
1874        }
1875    };
1876    let max_z_mm = section
1877        .max_z_mm
1878        .ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
1879    if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
1880        return Err(ConfigError::about(
1881            ConfigField::RecoveryMaxZMm,
1882            format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
1883        ));
1884    }
1885    let max_lift_mm = section
1886        .max_lift_mm
1887        .unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
1888    if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
1889        return Err(ConfigError::about(
1890            ConfigField::RecoveryMaxLiftMm,
1891            format!(
1892                "{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
1893                 zero, and at most `recovery.max_z_mm`"
1894            ),
1895        ));
1896    }
1897    let clearance_margin_mm = section
1898        .clearance_margin_mm
1899        .unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
1900    if !(clearance_margin_mm.is_finite()
1901        && clearance_margin_mm >= 0.0
1902        && clearance_margin_mm < max_z_mm)
1903    {
1904        return Err(ConfigError::about(
1905            ConfigField::RecoveryClearanceMarginMm,
1906            format!(
1907                "{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
1908                 admits: at or above zero, and below `recovery.max_z_mm`"
1909            ),
1910        ));
1911    }
1912    let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
1913        None => Err(absent(field)),
1914        Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
1915        Some(_) => Err(ConfigError::about(
1916            field,
1917            "a place is `[x, y]`, two figures in millimetres at or above zero",
1918        )),
1919    };
1920    let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
1921    let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
1922    let z_home_sweeps_bed = section
1923        .z_home_sweeps_bed
1924        .ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
1925    Ok(Some(RecoveryConfig {
1926        away_from_bed,
1927        max_z_mm,
1928        max_lift_mm,
1929        clearance_margin_mm,
1930        park_xy,
1931        z_home_xy,
1932        z_home_sweeps_bed,
1933    }))
1934}
1935
1936/// Who may ask for which recovery action, each list left out taking its
1937/// default, and the two grants no configuration may make refused.
1938fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
1939    let defaults = RecoveryGrants::default();
1940    let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
1941        let Some(written) = written else {
1942            return Ok(default);
1943        };
1944        written
1945            .iter()
1946            .map(|name| {
1947                RecoveryActionKind::ALL
1948                    .iter()
1949                    .find(|kind| kind.as_str() == name.trim())
1950                    .copied()
1951                    .ok_or_else(|| {
1952                        ConfigError::about(
1953                            field,
1954                            format!("{name:?} is not a recovery action of this program"),
1955                        )
1956                    })
1957            })
1958            .collect::<Result<Vec<_>, _>>()
1959    };
1960    let operator = actions(
1961        ConfigField::PolicyRecoveryOperator,
1962        section.operator.as_ref(),
1963        defaults.operator,
1964    )?;
1965    let agent = actions(
1966        ConfigField::PolicyRecoveryAgent,
1967        section.agent.as_ref(),
1968        defaults.agent,
1969    )?;
1970    // Homing Z drives the nozzle or a gantry down onto whatever is on the bed,
1971    // and only a person standing at the machine can say nothing is.
1972    if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
1973        return Err(ConfigError::about(
1974            ConfigField::PolicyRecoveryAgent,
1975            "it grants `recover_home_z` to the agent, and only a person at the machine can \
1976             say the bed is clear for Z to be homed",
1977        ));
1978    }
1979    let asserting = match section.asserting.as_ref() {
1980        None => defaults.asserting,
1981        Some(written) => written
1982            .iter()
1983            .map(|class| match class.trim() {
1984                "operator" => Ok(ActorClass::Operator),
1985                // An assertion is a person's word for what they can see, and
1986                // an agent's word for clearance is no measurement of it.
1987                "agent" => Err(ConfigError::about(
1988                    ConfigField::PolicyRecoveryAsserting,
1989                    "it lets the agent assert clearance, and an assertion is a person's word \
1990                     for what they can see at the machine",
1991                )),
1992                other => Err(ConfigError::about(
1993                    ConfigField::PolicyRecoveryAsserting,
1994                    format!("{other:?} is not an actor whose word can count; only `operator` is"),
1995                )),
1996            })
1997            .collect::<Result<Vec<_>, _>>()?,
1998    };
1999    Ok(RecoveryGrants {
2000        operator,
2001        agent,
2002        asserting,
2003    })
2004}
2005
2006/// The observation interval, refused at zero.
2007fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
2008    if seconds == 0 {
2009        return Err(ConfigError::about(
2010            ConfigField::ObservationIntervalS,
2011            "an interval of zero seconds observes a print again the moment its last turn \
2012             returns, which is a turn that never ends",
2013        ));
2014    }
2015    Ok(core::time::Duration::from_secs(seconds))
2016}
2017
2018/// The harness's own compaction size and the idle compaction's, each when
2019/// written down.
2020fn compaction(
2021    auto: Option<i64>,
2022    idle: Option<i64>,
2023) -> Result<(Option<NonZeroU64>, Option<NonZeroU64>), ConfigError> {
2024    Ok((
2025        tokens(ConfigField::AutoCompactTokens, auto)?,
2026        tokens(ConfigField::IdleCompactTokens, idle)?,
2027    ))
2028}
2029
2030/// A count of tokens, when one is written down: refused naming its field
2031/// unless it is a whole number from 1, because a conversation of no tokens is
2032/// one every turn has already passed.
2033fn tokens(field: ConfigField, count: Option<i64>) -> Result<Option<NonZeroU64>, ConfigError> {
2034    count
2035        .map(|count| {
2036            u64::try_from(count)
2037                .ok()
2038                .and_then(NonZeroU64::new)
2039                .ok_or_else(|| {
2040                    ConfigError::about(
2041                        field,
2042                        format!(
2043                            "{count} tokens is no conversation size: it is a whole number from 1"
2044                        ),
2045                    )
2046                })
2047        })
2048        .transpose()
2049}
2050
2051/// How long a harness check's one turn may take, refused outside the range
2052/// `supervisor.check_turn_timeout_s` admits.
2053fn check_turn_timeout(seconds: u64) -> Result<core::time::Duration, ConfigError> {
2054    seconds_within(
2055        ConfigField::CheckTurnTimeoutS,
2056        seconds,
2057        CHECK_TURN_TIMEOUT_RANGE_S,
2058    )
2059}
2060
2061/// A number of seconds, refused outside the range its field admits.
2062fn seconds_within(
2063    field: ConfigField,
2064    seconds: u64,
2065    range: (u64, u64),
2066) -> Result<core::time::Duration, ConfigError> {
2067    let (least, most) = range;
2068    if !(least..=most).contains(&seconds) {
2069        return Err(ConfigError::about(
2070            field,
2071            format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
2072        ));
2073    }
2074    Ok(core::time::Duration::from_secs(seconds))
2075}
2076
2077/// The blank-frame bound, refused outside the range it admits.
2078fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
2079    written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
2080        BlankFrameBound::new(bound).map_err(|refused| {
2081            ConfigError::about(
2082                ConfigField::VisionBlankFrameMaxStddev,
2083                format!(
2084                    "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
2085                     {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
2086                ),
2087            )
2088        })
2089    })
2090}
2091
2092/// The answer bound, refused when it is not one this program admits.
2093fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
2094    if milliseconds == 0 {
2095        return Err(ConfigError::about(
2096            ConfigField::IngressAnswerBoundMs,
2097            "a bound of zero is an ingress that has run out of time before it starts",
2098        ));
2099    }
2100    if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
2101        return Err(ConfigError::about(
2102            ConfigField::IngressAnswerBoundMs,
2103            format!(
2104                "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
2105                 under, so an alert answered at that bound is one Obico has already \
2106                 abandoned — and its posting does not retry"
2107            ),
2108        ));
2109    }
2110    Ok(core::time::Duration::from_millis(milliseconds))
2111}
2112
2113#[cfg(test)]
2114mod tests {
2115    use super::CredentialVerifier;
2116
2117    /// The SHA-256 of `abc`, as FIPS 180-2 gives it.
2118    const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
2119
2120    /// A verifier is the SHA-256 of the credential's UTF-8 bytes, written and
2121    /// read back in one spelling, and it admits that credential and no other.
2122    #[test]
2123    fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
2124        let verifier = CredentialVerifier::of("abc");
2125
2126        assert_eq!(verifier.to_string(), ABC);
2127        assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
2128        assert!(verifier.admits(b"abc"));
2129        assert!(!verifier.admits(b"abd"));
2130        assert!(!verifier.admits(b""));
2131    }
2132
2133    /// Anything but `sha256:` and 64 lowercase hexadecimal digits is refused.
2134    #[test]
2135    fn a_verifier_in_any_other_spelling_is_refused() {
2136        for refused in [
2137            "",
2138            "sha256:",
2139            &ABC[..ABC.len() - 1],
2140            &format!("{ABC}0"),
2141            &ABC.to_uppercase(),
2142            &ABC.replace("sha256:", "sha512:"),
2143            &ABC.replace("sha256:", ""),
2144            &ABC.replace('a', "g"),
2145        ] {
2146            assert!(
2147                CredentialVerifier::parse(refused).is_err(),
2148                "{refused:?} was accepted"
2149            );
2150        }
2151    }
2152}