Skip to main content

printobserver_server/
server.rs

1//! The composition root: the one place an implementation crate is named.
2//!
3//! Everything below this file is written against the three ports and the
4//! supervision domain's store traits. This is where one implementation is
5//! chosen for each — `OctoPrint` behind the printer port, `Obico` behind the
6//! vision port, `OneHarness` behind the supervisor port, and `SQLite` behind
7//! the store traits — and `just check-repo` refuses any other crate that names
8//! one. The store is one implementation held once per aggregate: [`Stores::of`]
9//! coerces the one `SQLite` store to each of the seven trait objects, and every
10//! consumer below is handed the handle for the aggregate it names and no
11//! other.
12//!
13//! [`Server::start`] is that root. [`Server::start_with`] takes ports a caller
14//! composed, which is how the tiers that stand in for a machine drive the real
15//! surface without one; the two share every line after the ports exist, so what
16//! a tier drives is the server this file starts.
17
18use std::ffi::OsStr;
19use std::net::SocketAddr;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22
23use axum::Router;
24use axum::routing::post;
25use printobserver_core::store::Stores;
26use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
27use printobserver_obico::{ObicoVision, ObicoVisionConfig};
28use printobserver_octoprint::OctoPrintPrinter;
29use printobserver_oneharness::{
30    AgentCommand, AssessmentSchema, EnvAssignment, HarnessSignIn, OneharnessSupervisor,
31    SupervisorConfig,
32};
33use printobserver_printer_api::{PrinterError, PrinterPort};
34use printobserver_store_sqlite::SqliteStore;
35use printobserver_supervisor_api::SupervisorPort;
36use tokio::net::TcpListener;
37use tokio::sync::{oneshot, watch};
38use tokio::task::JoinHandle;
39
40use crate::api::{ApiState, router};
41use crate::config::{ApiCredential, ConfigError, ConfigField, CredentialVerifier, ServerConfig};
42use crate::events::Stored;
43use crate::ingress::{IngressState, receive};
44use crate::operations::{INGRESS_PATH, OPERATIONS, command_for};
45use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
46use crate::turns::TurnCredentials;
47
48/// The program a supervision turn runs to read its print's context.
49pub const CONTEXT_PROGRAM: &str = "printobserver";
50
51/// The file, under the state directory, a server before this one wrote the
52/// address it took and the credential in force into. A start deletes it: a
53/// supervision turn runs as the service's user and could read the operator's
54/// credential out of it.
55pub const CLIENT_CONFIG_FILE: &str = "client.toml";
56
57/// The file, under the state directory, a server before this one generated its
58/// API credential into, as plaintext. A start converts it into
59/// [`API_CREDENTIAL_VERIFIER_FILE`] and deletes it, so the credential it held
60/// keeps authenticating while nothing the service's user can read holds it.
61pub const API_CREDENTIAL_FILE: &str = "api-credential";
62
63/// The file, under the state directory, holding the verifier of the operator's
64/// credential — read when `api.credential_verifier` is not configured.
65pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
66
67/// The command that gives an operator a credential, as every refusal and
68/// warning about one names it.
69pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
70
71/// The command that prints the verifier of a credential an operator already
72/// holds.
73pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
74
75/// The mode the verifier file is created with.
76///
77/// Unix alone has one. A file Windows creates carries the access its directory
78/// grants rather than a mode, so there the state directory is what keeps it to
79/// the service's own account.
80#[cfg(unix)]
81const PRIVATE: u32 = 0o600;
82
83/// The command a supervision turn runs to read its print's context.
84///
85/// This program's own context read, against the print the turn is about, and
86/// nothing else: where the server is and the credential the turn answers to
87/// reach the turn through its environment alone — the address the server
88/// bound and a credential minted for that turn — so the command names no
89/// configuration file and the program reads none.
90/// `printobserver-oneharness` substitutes the print for the placeholder.
91#[must_use]
92pub fn context_command() -> String {
93    format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
94}
95
96/// Who an operator's credential is checked against, as one start settled it.
97#[derive(Debug, Clone)]
98pub enum OperatorCredential {
99    /// Its verifier, from `api.credential_verifier` or the state directory.
100    Verifier(CredentialVerifier),
101    /// A plaintext `api.credential` the configuration still carries, admitted
102    /// until it is replaced.
103    Plaintext(ApiCredential),
104    /// Nothing at all: a fresh install whose operator has not run
105    /// `printobserver credential issue` yet. No operator request is admitted.
106    Unconfigured,
107}
108
109impl OperatorCredential {
110    /// Whether a presented credential is the operator's.
111    #[must_use]
112    pub fn admits(&self, presented: &[u8]) -> bool {
113        match self {
114            Self::Verifier(verifier) => verifier.admits(presented),
115            Self::Plaintext(credential) => credential.admits(presented),
116            Self::Unconfigured => false,
117        }
118    }
119}
120
121/// The warning every start under a plaintext `api.credential` gives, which
122/// names the key, its replacement and the command that computes one, and never
123/// what the key holds.
124#[must_use]
125pub fn plaintext_credential_warning() -> String {
126    format!(
127        "the server configuration carries `api.credential`, an operator credential in \
128         plaintext. A supervision turn runs as this service's user and can read that file, \
129         so it can read that credential until it is replaced. Replace it with \
130         `api.credential_verifier`: pipe the credential into `{CREDENTIAL_VERIFIER}` to print \
131         that line, put it in the configuration, delete `api.credential`, and restart the \
132         service"
133    )
134}
135
136/// Write one file this start creates, exclusively and private to the service.
137fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
138    use std::io::Write as _;
139
140    let mut options = std::fs::OpenOptions::new();
141    options.write(true).create_new(true);
142    #[cfg(unix)]
143    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
144    let mut file = options.open(path)?;
145    // llmlint: ignore[changed_behavior_has_e2e] A write or sync failing into a file this start just created exclusively is a full or failing disk, which no journey can arrange on a runner without root; the conversion it serves, and the next start after it, are driven by `a_legacy_installation_keeps_its_operators_credential_through_every_route`.
146    let written = file.write_all(contents).and_then(|()| file.sync_all());
147    if written.is_err() {
148        // The file is this start's own and holds nothing usable, so it is
149        // taken back rather than left for the next start to refuse.
150        let _ = std::fs::remove_file(path);
151    }
152    written
153}
154
155/// Remove one file a server before this one left, when it is there.
156fn remove_if_there(path: &Path) -> std::io::Result<()> {
157    match std::fs::remove_file(path) {
158        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
159        _ => Ok(()),
160    }
161}
162
163/// Take the plaintext a server before this one left in the state directory out
164/// of it.
165///
166/// `client.toml` is deleted. `api-credential` is converted into the verifier
167/// file — written first, exclusively, so a start that stops between the two
168/// leaves the credential still convertible — and then deleted; one left beside
169/// a verifier file that is already there is deleted outright, because that
170/// verifier is what is in force.
171///
172/// # Errors
173///
174/// Returns [`StartError::Credential`] naming the file, and never what it holds,
175/// when the legacy credential cannot be read, holds nothing a header could
176/// present, or cannot be converted or removed; and [`StartError::State`] when
177/// `client.toml` cannot be removed.
178fn take_plaintext_out(state_dir: &Path) -> Result<(), StartError> {
179    let client_config = state_dir.join(CLIENT_CONFIG_FILE);
180    remove_if_there(&client_config).map_err(|error| StartError::State {
181        detail: format!(
182            "{} could not be removed, and it may carry the operator's credential where a \
183             supervision turn can read it: {error}",
184            client_config.display()
185        ),
186    })?;
187    let legacy = state_dir.join(API_CREDENTIAL_FILE);
188    let refusing = |detail: String| StartError::Credential {
189        path: legacy.clone(),
190        detail,
191    };
192    let held = match std::fs::read(&legacy) {
193        Ok(held) => held,
194        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
195        Err(error) => return Err(refusing(format!("it cannot be read: {error}"))),
196    };
197    let verifier_file = state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
198    if !verifier_file.exists() {
199        let text = core::str::from_utf8(&held).ok().map(without_terminator);
200        let credential = text
201            .ok_or("it is not text")
202            .and_then(ApiCredential::new)
203            .map_err(|why| {
204                refusing(format!(
205                    "{why}. This server converts the credential an earlier version generated \
206                     there into its verifier: correct the file, or remove it and run \
207                     `{CREDENTIAL_ISSUE} --replace`"
208                ))
209            })?;
210        write_private(
211            &verifier_file,
212            format!("{}\n", credential.verifier()).as_bytes(),
213        )
214        .map_err(|error| {
215            refusing(format!(
216                "its verifier could not be written to {}: {error}",
217                verifier_file.display()
218            ))
219        })?;
220    }
221    std::fs::remove_file(&legacy)
222        .map_err(|error| refusing(format!("it could not be removed: {error}")))
223}
224
225/// The operator credential this start serves under, and the warnings it owes.
226///
227/// The legacy plaintext is taken out of the state directory first. Then
228/// `api.credential_verifier` when it is configured, a plaintext
229/// `api.credential` when that is all the configuration carries, the verifier
230/// file in the state directory, and otherwise nothing — a fresh install, which
231/// supervises and admits no operator until one is issued. A plaintext
232/// `api.credential` warns whether or not a verifier wins over it.
233///
234/// # Errors
235///
236/// Returns [`StartError::Credential`] naming the file, and never what it
237/// holds, when the legacy plaintext cannot be taken out or the verifier file
238/// cannot be read as one.
239pub fn operator_credential(
240    config: &ServerConfig,
241) -> Result<(OperatorCredential, Vec<String>), StartError> {
242    take_plaintext_out(&config.state_dir)?;
243    let mut warnings = Vec::new();
244    if config.api_credential.is_some() {
245        warnings.push(plaintext_credential_warning());
246    }
247    if let Some(verifier) = &config.api_credential_verifier {
248        return Ok((OperatorCredential::Verifier(verifier.clone()), warnings));
249    }
250    if let Some(plaintext) = &config.api_credential {
251        return Ok((OperatorCredential::Plaintext(plaintext.clone()), warnings));
252    }
253    let path = config.state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
254    let held = match std::fs::read_to_string(&path) {
255        Ok(held) => held,
256        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
257            return Ok((OperatorCredential::Unconfigured, warnings));
258        }
259        Err(error) => {
260            return Err(StartError::Credential {
261                path,
262                detail: format!("it cannot be read: {error}"),
263            });
264        }
265    };
266    let verifier =
267        CredentialVerifier::parse(held.trim()).map_err(|why| StartError::Credential {
268            path: path.clone(),
269            detail: format!(
270                "{why}. Correct the file, or remove it and set `api.credential_verifier`"
271            ),
272        })?;
273    Ok((OperatorCredential::Verifier(verifier), warnings))
274}
275
276/// A credential file's text with the one line terminator a person's editor or
277/// shell ends it with set aside.
278///
279/// Exactly one, `\n` or `\r\n`: that terminator is not part of the credential,
280/// and anything else in the text — a second one included — is left for the
281/// character rule to refuse.
282fn without_terminator(text: &str) -> &str {
283    text.strip_suffix("\r\n")
284        .or_else(|| text.strip_suffix('\n'))
285        .unwrap_or(text)
286}
287
288/// The file name the agent's prompt template is materialized under.
289pub const PROMPT_FILE: &str = "turn-prompt.md";
290
291/// The file name the assessment schema is materialized under.
292pub const SCHEMA_FILE: &str = "assessment-schema.json";
293
294/// The prompt template this program carries and materializes.
295///
296/// The adapter's own committed asset rather than a copy of it, so what an
297/// installed program fills a turn with and what `just check-repo` reads are one
298/// file.
299pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
300
301/// The four implementations one running server was composed from.
302///
303/// A tier that stands in for a machine hands these in; [`Server::start`] builds
304/// them from the configuration.
305pub struct Ports {
306    /// The printer.
307    pub printer: Arc<dyn PrinterPort>,
308    /// Durable state, one handle per aggregate onto one store.
309    pub stores: Stores,
310    /// External observations, and the snapshot fetch.
311    pub vision: Arc<ObicoVision>,
312    /// The supervising agent's harness.
313    pub agent: Arc<dyn SupervisorPort>,
314}
315
316impl core::fmt::Debug for Ports {
317    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
318        formatter.debug_struct("Ports").finish_non_exhaustive()
319    }
320}
321
322/// Why this server did not start.
323#[derive(Debug)]
324pub enum StartError {
325    /// The configuration will not do, naming the field that will not.
326    Configuration(ConfigError),
327    /// The state directory could not be prepared.
328    State {
329        /// What went wrong.
330        detail: String,
331    },
332    /// A credential file in the state directory cannot be used.
333    Credential {
334        /// The file.
335        path: PathBuf,
336        /// Why it cannot be used, in words that never quote what it holds.
337        detail: String,
338    },
339    /// The address could not be listened on.
340    Listen {
341        /// The address that was asked for.
342        address: SocketAddr,
343        /// What went wrong.
344        detail: String,
345    },
346    /// The store could not be opened.
347    Store {
348        /// What the store said.
349        detail: String,
350    },
351    /// The supervising agent's harness could not be reached at all.
352    Supervisor {
353        /// What the harness said.
354        detail: String,
355    },
356    /// Reconciling what the store held failed.
357    Reconciliation {
358        /// What went wrong.
359        detail: String,
360    },
361}
362
363impl StartError {
364    /// The configuration field this refusal is about, when it is about one.
365    #[must_use]
366    pub const fn field(&self) -> Option<ConfigField> {
367        match self {
368            Self::Configuration(error) => error.field(),
369            _ => None,
370        }
371    }
372}
373
374impl core::fmt::Display for StartError {
375    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376        match self {
377            Self::Configuration(error) => write!(formatter, "{error}"),
378            Self::State { detail } => {
379                write!(
380                    formatter,
381                    "the state directory could not be prepared: {detail}"
382                )
383            }
384            Self::Credential { path, detail } => write!(
385                formatter,
386                "the credential file {} cannot be used: {detail}",
387                path.display()
388            ),
389            Self::Listen { address, detail } => {
390                write!(formatter, "{address} could not be listened on: {detail}")
391            }
392            Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
393            Self::Supervisor { detail } => write!(
394                formatter,
395                "the supervising agent's harness could not be reached: {detail}"
396            ),
397            Self::Reconciliation { detail } => write!(
398                formatter,
399                "what the store held could not be reconciled: {detail}"
400            ),
401        }
402    }
403}
404
405impl core::error::Error for StartError {}
406
407impl From<ConfigError> for StartError {
408    fn from(error: ConfigError) -> Self {
409        Self::Configuration(error)
410    }
411}
412
413/// The composition root.
414#[derive(Debug)]
415pub struct Server;
416
417impl Server {
418    /// Read one configuration file, compose the four implementations, and serve.
419    ///
420    /// # Errors
421    ///
422    /// Returns [`StartError::Configuration`] naming the field that will not do
423    /// — including the two only the machine can rule on, an `OctoPrint` address
424    /// nothing answers at and a key that instance refuses — and the other
425    /// variants for a host that will not let this server come up.
426    pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
427        let config = ServerConfig::load(config_path)?;
428        let store = SqliteStore::open(&config.state_dir).map_err(|error| StartError::Store {
429            detail: error.to_string(),
430        })?;
431        // A row a migration could not carry forward as it was is said once, as
432        // the start that migrated it comes up, beside the store's own record.
433        let migrated: Vec<String> = store.migrated().iter().map(ToString::to_string).collect();
434        let stores = Stores::of(Arc::new(store));
435        let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
436        probe(printer.as_ref()).await?;
437        let vision = Arc::new(
438            ObicoVision::new(ObicoVisionConfig::default())
439                .map_err(|error| StartError::State {
440                    detail: error.to_string(),
441                })?
442                .with_api(config.obico_api.clone()),
443        );
444        let agent = Arc::new(agent_for(&config)?);
445        let mut running = Self::start_with(
446            config,
447            Ports {
448                printer,
449                stores,
450                vision,
451                agent,
452            },
453        )
454        .await?;
455        running.warnings.extend(migrated);
456        Ok(running)
457    }
458
459    /// Serve over ports a caller composed.
460    ///
461    /// # Errors
462    ///
463    /// The same as [`Server::start`], less the refusals that belong to building
464    /// the implementations.
465    pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
466        // The operator's credential is settled before anything listens, so
467        // there is no moment at which this server answers a request it has
468        // nothing to check against — and the plaintext an earlier version left
469        // is out of the state directory before the first turn could read it.
470        let (operator, warnings) = operator_credential(&config)?;
471        // The listener is taken next, because the command a supervision turn
472        // runs to read its context names the address this server is answering
473        // on — and a configuration may ask for any free port.
474        let listener =
475            TcpListener::bind(config.listen)
476                .await
477                .map_err(|error| StartError::Listen {
478                    address: config.listen,
479                    detail: error.to_string(),
480                })?;
481        let address = listener.local_addr().map_err(|error| StartError::Listen {
482            address: config.listen,
483            detail: error.to_string(),
484        })?;
485        let clock = Arc::new(SystemClock);
486        let due = overdue(&ports.stores.actions, clock.now())
487            .await
488            .map_err(|error| StartError::Reconciliation {
489                detail: error.to_string(),
490            })?;
491        let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
492        core_config
493            .camera_snapshot_url
494            .clone_from(&config.camera_snapshot_url);
495        core_config.observation_interval = config.observation_interval;
496        core_config.spools = config.spools;
497        let supervisor = Supervisor::new(
498            core_config,
499            Arc::clone(&ports.printer),
500            ports.stores.clone(),
501            Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
502            Arc::clone(&ports.agent),
503            clock,
504        );
505        // Every turn's runs are told the address this server bound, beside the
506        // credential minted for them.
507        let turns = TurnCredentials::new(Some(address));
508        supervisor.install_turn_authority(Arc::new(turns.clone()));
509        let reconciliation = reconcile(
510            &supervisor,
511            &ReconcileStores {
512                prints: Arc::clone(&ports.stores.prints),
513                sessions: Arc::clone(&ports.stores.sessions),
514                events: Arc::clone(&ports.stores.events),
515            },
516            due,
517        )
518        .await
519        .map_err(|error| StartError::Reconciliation {
520            detail: error.to_string(),
521        })?;
522
523        let ingress = IngressState::start(
524            Arc::clone(&supervisor),
525            Arc::clone(&ports.stores.events),
526            Arc::clone(&ports.vision),
527            config.ingress_shared_secret.clone(),
528            config.ingress_answer_bound,
529        );
530        let completions = ingress.completions();
531        let observing = crate::observation::start(&supervisor);
532        // Every events read waits on this, and every write that stores an
533        // event raises it once committed — whichever of this server's parts
534        // made the write.
535        let (stored, signal) = Stored::channel();
536        ports.stores.events.on_stored(signal);
537        let application = router(ApiState {
538            supervisor: Arc::clone(&supervisor),
539            prints: Arc::clone(&ports.stores.prints),
540            events: Arc::clone(&ports.stores.events),
541            images: Arc::clone(&ports.stores.images),
542            sessions: Arc::clone(&ports.stores.sessions),
543            operator: Arc::new(operator),
544            turns,
545            stored,
546        })
547        .merge(
548            Router::new()
549                .route(INGRESS_PATH, post(receive))
550                .with_state(ingress),
551        );
552
553        let (stop, stopped) = oneshot::channel::<()>();
554        let serving = tokio::spawn(async move {
555            let _ = axum::serve(listener, application)
556                .with_graceful_shutdown(async move {
557                    let _ = stopped.await;
558                })
559                .await;
560        });
561        Ok(Running {
562            address,
563            config,
564            warnings,
565            supervisor,
566            stores: ports.stores,
567            reconciliation,
568            completions,
569            stop: Some(stop),
570            serving,
571            observing,
572        })
573    }
574}
575
576/// Ask the machine whether the address and the key are the ones it answers to.
577///
578/// Only the two answers that are *about the configuration* refuse a start. A
579/// printer that is off, in an error state, or answering something this adapter
580/// cannot read is a machine having a bad day rather than a file with the wrong
581/// value in it, and a supervisor that would not come up for one of those could
582/// not be used to find out why.
583async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
584    match printer.snapshot().await {
585        Err(PrinterError::Unreachable { detail }) => {
586            Err(StartError::Configuration(ConfigError::about(
587                ConfigField::OctoprintUrl,
588                format!("nothing answers there: {detail}"),
589            )))
590        }
591        Err(PrinterError::Unauthorized { detail }) => {
592            Err(StartError::Configuration(ConfigError::about(
593                ConfigField::OctoprintApiKey,
594                format!("the OctoPrint instance refused it: {detail}"),
595            )))
596        }
597        _ => Ok(()),
598    }
599}
600
601/// Write one of the agent's committed assets into the state directory.
602///
603/// The port reads its template and its schema from paths, so that editing one
604/// on a running host is a restart rather than a rebuild. An installed program
605/// has no checkout to read them out of, so the bytes it carries are written
606/// here — and an operator who configured a template of their own is pointed at
607/// theirs instead.
608fn materialize(
609    directory: &Path,
610    name: &str,
611    contents: &str,
612) -> Result<std::path::PathBuf, StartError> {
613    let path = directory.join(name);
614    std::fs::write(&path, contents).map_err(|error| StartError::State {
615        detail: format!("{} could not be written: {error}", path.display()),
616    })?;
617    Ok(path)
618}
619
620/// The directory the harness runs in: the one holding the configured skill.
621///
622/// An installed skill is a directory — its `SKILL.md` and the `reference/`
623/// documents that file links to by relative paths — so the agent stands where
624/// those links resolve. A skill named by a bare file name sits in this
625/// process's own working directory.
626fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
627    match skill_path.parent() {
628        Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
629        _ => std::path::PathBuf::from("."),
630    }
631}
632
633/// The supervising agent's harness, over the configured skill and the assets
634/// this program carries.
635fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
636    OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
637        detail: error.to_string(),
638    })
639}
640
641/// The supervising agent's configuration, as [`Server::start`] composes it.
642///
643/// The template and the assessment schema are written into the assets
644/// directory; the skill is the installed one `supervisor.skill_path` names, and
645/// every turn runs in the directory holding it — where an installed skill's
646/// `reference/` documents sit, so the links the skill carries resolve from
647/// where the agent stands. The harness is the one `supervisor.harness` names,
648/// found by name, and a harness this program can sign in is pointed at the
649/// sign-in kept under the state directory.
650///
651/// # Errors
652///
653/// Returns [`StartError::State`] when the assets or the sign-in directory
654/// cannot be written, and [`StartError::Supervisor`] when the schema it wrote
655/// constrains nothing.
656pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
657    let assets = config.assets_dir();
658    std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
659        detail: format!("{} could not be created: {error}", assets.display()),
660    })?;
661    let prompt_template_path = match &config.prompt_template_path {
662        Some(path) => path.clone(),
663        None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
664    };
665    let schema_path =
666        materialize(
667            &assets,
668            SCHEMA_FILE,
669            &printobserver_types::serde_json::to_string_pretty(&without_dialect(
670                printobserver_types::contract::schema_of::<
671                    printobserver_supervisor_api::AgentAssessment,
672                >(),
673            ))
674            .map_err(|error| StartError::State {
675                detail: error.to_string(),
676            })?,
677        )?;
678    let assessment_schema =
679        AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
680            detail: error.to_string(),
681        })?;
682    // A harness this program can sign in keeps that sign-in under the state
683    // directory — the one place the service's unit lets it write — and every
684    // turn is pointed at the directory `printobserver sign-in` wrote it to. A
685    // harness outside the table is handed nothing extra.
686    let mut harness_env = match HarnessSignIn::of(&config.harness) {
687        Some(sign_in) => {
688            let directory =
689                sign_in
690                    .prepare(&config.state_dir)
691                    .map_err(|error| StartError::State {
692                        detail: format!(
693                            "{} could not be created: {error}",
694                            sign_in.directory(&config.state_dir).display()
695                        ),
696                    })?;
697            vec![
698                sign_in
699                    .assignment(&directory)
700                    .map_err(|error| StartError::Supervisor {
701                        detail: error.to_string(),
702                    })?,
703            ]
704        }
705        None => Vec::new(),
706    };
707    let search_path = std::env::var_os("PATH").unwrap_or_default();
708    harness_env.extend(path_led_by_this_program(&search_path)?);
709    Ok(SupervisorConfig {
710        state_dir: config.state_dir.clone(),
711        skill_path: config.skill_path.clone(),
712        prompt_template_path,
713        assessment_schema,
714        harness: config.harness.clone(),
715        model: config.model.clone(),
716        // The skill's own directory rather than the state or assets directory,
717        // so that the skill's relative links to the reference documents beside
718        // it resolve from where the agent is standing as well as from the skill.
719        working_dir: beside_the_skill(&config.skill_path),
720        turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
721        // Found by name, unless npm's launcher is all a search finds: then the
722        // native program behind it, which `OneHarness` can start where the
723        // launcher cannot be.
724        harness_bin: HarnessSignIn::of(&config.harness)
725            .and_then(|harness| harness.program_behind_launcher(&search_path)),
726        harness_env,
727        agent_commands: agent_commands()?,
728    })
729}
730
731/// The key a JSON Schema declares its dialect under.
732const DIALECT_KEY: &str = "$schema";
733
734/// A schema with its dialect declaration taken off, and nothing else changed.
735///
736/// The generated assessment schema declares draft 2020-12, and Claude Code
737/// refuses a `--json-schema` naming a dialect its validator was not given ("no
738/// schema with key or ref `https://json-schema.org/draft/2020-12/schema`"), so
739/// every turn ended before the agent was asked anything. Left undeclared, the
740/// harness reads the schema in its own dialect and `OneHarness` in its default,
741/// and the keywords this schema uses mean the same in both. The checked-in
742/// schema keeps its declaration: only the copy a turn is handed drops it.
743fn without_dialect(
744    mut schema: printobserver_types::serde_json::Value,
745) -> printobserver_types::serde_json::Value {
746    if let Some(object) = schema.as_object_mut() {
747        object.remove(DIALECT_KEY);
748    }
749    schema
750}
751
752/// The commands the supervising agent may run: this program's own, one per
753/// operation the server serves, and no other.
754///
755/// Every one of them is a request to this server, so what the agent can change
756/// is still exactly what the policy grants its actor. Derived from
757/// [`OPERATIONS`] through the command-line program's own spelling, so an
758/// operation the server gains is a command the agent may run from the same
759/// change.
760fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
761    OPERATIONS
762        .iter()
763        .map(|operation| {
764            AgentCommand::new(&format!(
765                "{CONTEXT_PROGRAM} {}",
766                command_for(operation.name)
767            ))
768        })
769        .collect::<Result<_, _>>()
770        .map_err(|error| StartError::Supervisor {
771            detail: error.to_string(),
772        })
773}
774
775/// A turn's `PATH`: the directory this program is running from, then the
776/// search path this process was given.
777///
778/// The context command, and every command the agent may run, names this
779/// program by name rather than by path, and nothing makes that name resolve in
780/// a service's environment: neither installer puts the program's directory on
781/// a `PATH`, and Windows' service control manager hands a service the
782/// environment it had at boot. Leading the turn's `PATH` with this program's
783/// own directory makes the name the program that is serving.
784///
785/// Nothing is added when the running program's path cannot be read, which
786/// leaves the turn the `PATH` it inherits.
787fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
788    let Some(directory) = std::env::current_exe()
789        .ok()
790        .and_then(|program| program.parent().map(Path::to_path_buf))
791    else {
792        return Ok(None);
793    };
794    let refused = |detail: String| StartError::Supervisor {
795        detail: format!(
796            "a turn's PATH cannot lead with {}: {detail}",
797            directory.display()
798        ),
799    };
800    let joined = std::env::join_paths(
801        std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
802    )
803    .map_err(|error| refused(error.to_string()))?;
804    let joined = joined
805        .to_str()
806        .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
807    EnvAssignment::new(&format!("PATH={joined}"))
808        .map(Some)
809        .map_err(|error| refused(error.to_string()))
810}
811
812/// One server, serving.
813///
814/// Dropping this stops it, and so does [`Running::stop`]; nothing here outlives
815/// the handle a caller holds.
816pub struct Running {
817    /// Where it is answering.
818    address: SocketAddr,
819    /// What it was configured with.
820    config: ServerConfig,
821    /// What this start found that its operator should change, in words that
822    /// quote no credential.
823    warnings: Vec<String>,
824    /// The supervision core.
825    supervisor: Arc<Supervisor>,
826    /// Durable state, one handle per aggregate.
827    stores: Stores,
828    /// What this start adopted.
829    reconciliation: Reconciliation,
830    /// How many posts the ingress worker has finished handling.
831    completions: watch::Receiver<u64>,
832    /// The graceful-shutdown signal, taken when it is sent.
833    stop: Option<oneshot::Sender<()>>,
834    /// The task serving requests.
835    serving: JoinHandle<()>,
836    /// The task giving every active print its periodic observation.
837    observing: JoinHandle<()>,
838}
839
840impl core::fmt::Debug for Running {
841    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
842        formatter
843            .debug_struct("Running")
844            .field("address", &self.address)
845            .field("reconciliation", &self.reconciliation)
846            .finish_non_exhaustive()
847    }
848}
849
850impl Running {
851    /// Where this server is answering.
852    #[must_use]
853    pub const fn address(&self) -> SocketAddr {
854        self.address
855    }
856
857    /// The base URL of its versioned surface.
858    #[must_use]
859    pub fn base_url(&self) -> String {
860        format!(
861            "http://{}{}",
862            self.address,
863            crate::operations::VERSION_PREFIX
864        )
865    }
866
867    /// The URL its ingress endpoint answers on.
868    #[must_use]
869    pub fn ingress_url(&self) -> String {
870        format!("http://{}{INGRESS_PATH}", self.address)
871    }
872
873    /// What it was configured with.
874    #[must_use]
875    pub const fn config(&self) -> &ServerConfig {
876        &self.config
877    }
878
879    /// What this start found that its operator should change — a plaintext
880    /// `api.credential` among them — in words that quote no credential. The
881    /// program running the server writes each to its log on every start.
882    #[must_use]
883    pub fn warnings(&self) -> &[String] {
884        &self.warnings
885    }
886
887    /// What this start adopted from the store.
888    #[must_use]
889    pub const fn reconciliation(&self) -> &Reconciliation {
890        &self.reconciliation
891    }
892
893    /// The supervision core it is serving over.
894    #[must_use]
895    pub const fn supervisor(&self) -> &Arc<Supervisor> {
896        &self.supervisor
897    }
898
899    /// Durable state, as it is serving over it.
900    #[must_use]
901    pub const fn stores(&self) -> &Stores {
902        &self.stores
903    }
904
905    /// How many posts the ingress worker has finished handling, watchable while
906    /// it works.
907    #[must_use]
908    pub fn completions(&self) -> watch::Receiver<u64> {
909        self.completions.clone()
910    }
911
912    /// Stop serving, and wait for the last request to finish.
913    pub async fn stop(mut self) {
914        if let Some(stop) = self.stop.take() {
915            let _ = stop.send(());
916        }
917        self.observing.abort();
918        let _ = (&mut self.serving).await;
919    }
920
921    /// Serve until the operating system asks this process to stop.
922    ///
923    /// This is what the `server` subcommand runs. It answers however this
924    /// platform asks a process to stop — see [`stop_requested`] — and every one
925    /// of those ways enters the same shutdown: [`Running::stop`].
926    ///
927    /// # Errors
928    ///
929    /// Returns [`StartError::State`] when the stop handlers cannot be
930    /// installed, which is a process that could not be stopped cleanly.
931    pub async fn serve_until_signalled(self) -> Result<(), StartError> {
932        stop_requested().await?;
933        self.stop().await;
934        Ok(())
935    }
936}
937
938/// A stop handler that could not be installed, naming which.
939fn unhandled(what: &str, error: &std::io::Error) -> StartError {
940    StartError::State {
941        detail: format!("{what} cannot be handled: {error}"),
942    }
943}
944
945/// Wait until the operating system asks this process to stop.
946///
947/// On Unix that is the signal a service manager stops a unit with, or the
948/// interrupt from the terminal that started it.
949#[cfg(unix)]
950async fn stop_requested() -> Result<(), StartError> {
951    use tokio::signal::unix::{SignalKind, signal};
952
953    let mut terminate = signal(SignalKind::terminate())
954        .map_err(|error| unhandled("the termination signal", &error))?;
955    let mut interrupt = signal(SignalKind::interrupt())
956        .map_err(|error| unhandled("the interrupt signal", &error))?;
957    tokio::select! {
958        _ = terminate.recv() => {}
959        _ = interrupt.recv() => {}
960    }
961    Ok(())
962}
963
964/// Wait until the operating system asks this process to stop.
965///
966/// Windows has no signals: a console process is stopped by a console control
967/// event. `CTRL_C` and `CTRL_BREAK` are the terminal's interrupt — the second is
968/// the one another process can send a process group started apart from its own
969/// — and `CTRL_CLOSE` and `CTRL_SHUTDOWN` are the console closing and the
970/// machine shutting down.
971#[cfg(windows)]
972async fn stop_requested() -> Result<(), StartError> {
973    use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
974
975    let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
976    let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
977    let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
978    let mut shutting_down =
979        ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
980    tokio::select! {
981        _ = interrupt.recv() => {}
982        _ = breaking.recv() => {}
983        _ = closing.recv() => {}
984        _ = shutting_down.recv() => {}
985    }
986    Ok(())
987}
988
989impl Drop for Running {
990    fn drop(&mut self) {
991        if let Some(stop) = self.stop.take() {
992            let _ = stop.send(());
993        }
994        self.serving.abort();
995    }
996}